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 __esm = (fn, res) => function __init() {
  return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
};
var __commonJS = (cb, mod) => function __require() {
  return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
};
var __copyProps = (to, from2, except, desc) => {
  if (from2 && typeof from2 === "object" || typeof from2 === "function") {
    for (let key of __getOwnPropNames(from2))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from2[key], enumerable: !(desc = __getOwnPropDesc(from2, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target2) => (target2 = 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(target2, "default", { value: mod, enumerable: true }) : target2,
  mod
));

// ../../node_modules/.pnpm/react@19.2.3/node_modules/react/cjs/react.development.js
var require_react_development = __commonJS({
  "../../node_modules/.pnpm/react@19.2.3/node_modules/react/cjs/react.development.js"(exports, module) {
    "use strict";
    (function() {
      function defineDeprecationWarning(methodName, info) {
        Object.defineProperty(Component.prototype, methodName, {
          get: function() {
            console.warn(
              "%s(...) is deprecated in plain JavaScript React classes. %s",
              info[0],
              info[1]
            );
          }
        });
      }
      function getIteratorFn(maybeIterable) {
        if (null === maybeIterable || "object" !== typeof maybeIterable)
          return null;
        maybeIterable = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable["@@iterator"];
        return "function" === typeof maybeIterable ? maybeIterable : null;
      }
      function warnNoop(publicInstance, callerName) {
        publicInstance = (publicInstance = publicInstance.constructor) && (publicInstance.displayName || publicInstance.name) || "ReactClass";
        var warningKey = publicInstance + "." + callerName;
        didWarnStateUpdateForUnmountedComponent[warningKey] || (console.error(
          "Can't call %s on a component that is not yet mounted. This is a no-op, but it might indicate a bug in your application. Instead, assign to `this.state` directly or define a `state = {};` class property with the desired state in the %s component.",
          callerName,
          publicInstance
        ), didWarnStateUpdateForUnmountedComponent[warningKey] = true);
      }
      function Component(props, context, updater) {
        this.props = props;
        this.context = context;
        this.refs = emptyObject;
        this.updater = updater || ReactNoopUpdateQueue;
      }
      function ComponentDummy() {
      }
      function PureComponent(props, context, updater) {
        this.props = props;
        this.context = context;
        this.refs = emptyObject;
        this.updater = updater || ReactNoopUpdateQueue;
      }
      function noop3() {
      }
      function testStringCoercion(value) {
        return "" + value;
      }
      function checkKeyStringCoercion(value) {
        try {
          testStringCoercion(value);
          var JSCompiler_inline_result = false;
        } catch (e) {
          JSCompiler_inline_result = true;
        }
        if (JSCompiler_inline_result) {
          JSCompiler_inline_result = console;
          var JSCompiler_temp_const = JSCompiler_inline_result.error;
          var JSCompiler_inline_result$jscomp$0 = "function" === typeof Symbol && Symbol.toStringTag && value[Symbol.toStringTag] || value.constructor.name || "Object";
          JSCompiler_temp_const.call(
            JSCompiler_inline_result,
            "The provided key is an unsupported type %s. This value must be coerced to a string before using it here.",
            JSCompiler_inline_result$jscomp$0
          );
          return testStringCoercion(value);
        }
      }
      function getComponentNameFromType(type) {
        if (null == type) return null;
        if ("function" === typeof type)
          return type.$$typeof === REACT_CLIENT_REFERENCE ? null : type.displayName || type.name || null;
        if ("string" === typeof type) return type;
        switch (type) {
          case REACT_FRAGMENT_TYPE:
            return "Fragment";
          case REACT_PROFILER_TYPE:
            return "Profiler";
          case REACT_STRICT_MODE_TYPE:
            return "StrictMode";
          case REACT_SUSPENSE_TYPE:
            return "Suspense";
          case REACT_SUSPENSE_LIST_TYPE:
            return "SuspenseList";
          case REACT_ACTIVITY_TYPE:
            return "Activity";
        }
        if ("object" === typeof type)
          switch ("number" === typeof type.tag && console.error(
            "Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."
          ), type.$$typeof) {
            case REACT_PORTAL_TYPE:
              return "Portal";
            case REACT_CONTEXT_TYPE:
              return type.displayName || "Context";
            case REACT_CONSUMER_TYPE:
              return (type._context.displayName || "Context") + ".Consumer";
            case REACT_FORWARD_REF_TYPE:
              var innerType = type.render;
              type = type.displayName;
              type || (type = innerType.displayName || innerType.name || "", type = "" !== type ? "ForwardRef(" + type + ")" : "ForwardRef");
              return type;
            case REACT_MEMO_TYPE:
              return innerType = type.displayName || null, null !== innerType ? innerType : getComponentNameFromType(type.type) || "Memo";
            case REACT_LAZY_TYPE:
              innerType = type._payload;
              type = type._init;
              try {
                return getComponentNameFromType(type(innerType));
              } catch (x5) {
              }
          }
        return null;
      }
      function getTaskName(type) {
        if (type === REACT_FRAGMENT_TYPE) return "<>";
        if ("object" === typeof type && null !== type && type.$$typeof === REACT_LAZY_TYPE)
          return "<...>";
        try {
          var name = getComponentNameFromType(type);
          return name ? "<" + name + ">" : "<...>";
        } catch (x5) {
          return "<...>";
        }
      }
      function getOwner() {
        var dispatcher = ReactSharedInternals.A;
        return null === dispatcher ? null : dispatcher.getOwner();
      }
      function UnknownOwner() {
        return Error("react-stack-top-frame");
      }
      function hasValidKey(config) {
        if (hasOwnProperty2.call(config, "key")) {
          var getter = Object.getOwnPropertyDescriptor(config, "key").get;
          if (getter && getter.isReactWarning) return false;
        }
        return void 0 !== config.key;
      }
      function defineKeyPropWarningGetter(props, displayName) {
        function warnAboutAccessingKey() {
          specialPropKeyWarningShown || (specialPropKeyWarningShown = true, console.error(
            "%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://react.dev/link/special-props)",
            displayName
          ));
        }
        warnAboutAccessingKey.isReactWarning = true;
        Object.defineProperty(props, "key", {
          get: warnAboutAccessingKey,
          configurable: true
        });
      }
      function elementRefGetterWithDeprecationWarning() {
        var componentName = getComponentNameFromType(this.type);
        didWarnAboutElementRef[componentName] || (didWarnAboutElementRef[componentName] = true, console.error(
          "Accessing element.ref was removed in React 19. ref is now a regular prop. It will be removed from the JSX Element type in a future release."
        ));
        componentName = this.props.ref;
        return void 0 !== componentName ? componentName : null;
      }
      function ReactElement(type, key, props, owner, debugStack, debugTask) {
        var refProp = props.ref;
        type = {
          $$typeof: REACT_ELEMENT_TYPE,
          type,
          key,
          props,
          _owner: owner
        };
        null !== (void 0 !== refProp ? refProp : null) ? Object.defineProperty(type, "ref", {
          enumerable: false,
          get: elementRefGetterWithDeprecationWarning
        }) : Object.defineProperty(type, "ref", { enumerable: false, value: null });
        type._store = {};
        Object.defineProperty(type._store, "validated", {
          configurable: false,
          enumerable: false,
          writable: true,
          value: 0
        });
        Object.defineProperty(type, "_debugInfo", {
          configurable: false,
          enumerable: false,
          writable: true,
          value: null
        });
        Object.defineProperty(type, "_debugStack", {
          configurable: false,
          enumerable: false,
          writable: true,
          value: debugStack
        });
        Object.defineProperty(type, "_debugTask", {
          configurable: false,
          enumerable: false,
          writable: true,
          value: debugTask
        });
        Object.freeze && (Object.freeze(type.props), Object.freeze(type));
        return type;
      }
      function cloneAndReplaceKey(oldElement, newKey) {
        newKey = ReactElement(
          oldElement.type,
          newKey,
          oldElement.props,
          oldElement._owner,
          oldElement._debugStack,
          oldElement._debugTask
        );
        oldElement._store && (newKey._store.validated = oldElement._store.validated);
        return newKey;
      }
      function validateChildKeys(node) {
        isValidElement(node) ? node._store && (node._store.validated = 1) : "object" === typeof node && null !== node && node.$$typeof === REACT_LAZY_TYPE && ("fulfilled" === node._payload.status ? isValidElement(node._payload.value) && node._payload.value._store && (node._payload.value._store.validated = 1) : node._store && (node._store.validated = 1));
      }
      function isValidElement(object) {
        return "object" === typeof object && null !== object && object.$$typeof === REACT_ELEMENT_TYPE;
      }
      function escape2(key) {
        var escaperLookup = { "=": "=0", ":": "=2" };
        return "$" + key.replace(/[=:]/g, function(match) {
          return escaperLookup[match];
        });
      }
      function getElementKey(element, index) {
        return "object" === typeof element && null !== element && null != element.key ? (checkKeyStringCoercion(element.key), escape2("" + element.key)) : index.toString(36);
      }
      function resolveThenable(thenable) {
        switch (thenable.status) {
          case "fulfilled":
            return thenable.value;
          case "rejected":
            throw thenable.reason;
          default:
            switch ("string" === typeof thenable.status ? thenable.then(noop3, noop3) : (thenable.status = "pending", thenable.then(
              function(fulfilledValue) {
                "pending" === thenable.status && (thenable.status = "fulfilled", thenable.value = fulfilledValue);
              },
              function(error) {
                "pending" === thenable.status && (thenable.status = "rejected", thenable.reason = error);
              }
            )), thenable.status) {
              case "fulfilled":
                return thenable.value;
              case "rejected":
                throw thenable.reason;
            }
        }
        throw thenable;
      }
      function mapIntoArray(children, array, escapedPrefix, nameSoFar, callback) {
        var type = typeof children;
        if ("undefined" === type || "boolean" === type) children = null;
        var invokeCallback = false;
        if (null === children) invokeCallback = true;
        else
          switch (type) {
            case "bigint":
            case "string":
            case "number":
              invokeCallback = true;
              break;
            case "object":
              switch (children.$$typeof) {
                case REACT_ELEMENT_TYPE:
                case REACT_PORTAL_TYPE:
                  invokeCallback = true;
                  break;
                case REACT_LAZY_TYPE:
                  return invokeCallback = children._init, mapIntoArray(
                    invokeCallback(children._payload),
                    array,
                    escapedPrefix,
                    nameSoFar,
                    callback
                  );
              }
          }
        if (invokeCallback) {
          invokeCallback = children;
          callback = callback(invokeCallback);
          var childKey = "" === nameSoFar ? "." + getElementKey(invokeCallback, 0) : nameSoFar;
          isArrayImpl(callback) ? (escapedPrefix = "", null != childKey && (escapedPrefix = childKey.replace(userProvidedKeyEscapeRegex, "$&/") + "/"), mapIntoArray(callback, array, escapedPrefix, "", function(c) {
            return c;
          })) : null != callback && (isValidElement(callback) && (null != callback.key && (invokeCallback && invokeCallback.key === callback.key || checkKeyStringCoercion(callback.key)), escapedPrefix = cloneAndReplaceKey(
            callback,
            escapedPrefix + (null == callback.key || invokeCallback && invokeCallback.key === callback.key ? "" : ("" + callback.key).replace(
              userProvidedKeyEscapeRegex,
              "$&/"
            ) + "/") + childKey
          ), "" !== nameSoFar && null != invokeCallback && isValidElement(invokeCallback) && null == invokeCallback.key && invokeCallback._store && !invokeCallback._store.validated && (escapedPrefix._store.validated = 2), callback = escapedPrefix), array.push(callback));
          return 1;
        }
        invokeCallback = 0;
        childKey = "" === nameSoFar ? "." : nameSoFar + ":";
        if (isArrayImpl(children))
          for (var i = 0; i < children.length; i++)
            nameSoFar = children[i], type = childKey + getElementKey(nameSoFar, i), invokeCallback += mapIntoArray(
              nameSoFar,
              array,
              escapedPrefix,
              type,
              callback
            );
        else if (i = getIteratorFn(children), "function" === typeof i)
          for (i === children.entries && (didWarnAboutMaps || console.warn(
            "Using Maps as children is not supported. Use an array of keyed ReactElements instead."
          ), didWarnAboutMaps = true), children = i.call(children), i = 0; !(nameSoFar = children.next()).done; )
            nameSoFar = nameSoFar.value, type = childKey + getElementKey(nameSoFar, i++), invokeCallback += mapIntoArray(
              nameSoFar,
              array,
              escapedPrefix,
              type,
              callback
            );
        else if ("object" === type) {
          if ("function" === typeof children.then)
            return mapIntoArray(
              resolveThenable(children),
              array,
              escapedPrefix,
              nameSoFar,
              callback
            );
          array = String(children);
          throw Error(
            "Objects are not valid as a React child (found: " + ("[object Object]" === array ? "object with keys {" + Object.keys(children).join(", ") + "}" : array) + "). If you meant to render a collection of children, use an array instead."
          );
        }
        return invokeCallback;
      }
      function mapChildren2(children, func, context) {
        if (null == children) return children;
        var result = [], count = 0;
        mapIntoArray(children, result, "", "", function(child) {
          return func.call(context, child, count++);
        });
        return result;
      }
      function lazyInitializer(payload) {
        if (-1 === payload._status) {
          var ioInfo = payload._ioInfo;
          null != ioInfo && (ioInfo.start = ioInfo.end = performance.now());
          ioInfo = payload._result;
          var thenable = ioInfo();
          thenable.then(
            function(moduleObject) {
              if (0 === payload._status || -1 === payload._status) {
                payload._status = 1;
                payload._result = moduleObject;
                var _ioInfo = payload._ioInfo;
                null != _ioInfo && (_ioInfo.end = performance.now());
                void 0 === thenable.status && (thenable.status = "fulfilled", thenable.value = moduleObject);
              }
            },
            function(error) {
              if (0 === payload._status || -1 === payload._status) {
                payload._status = 2;
                payload._result = error;
                var _ioInfo2 = payload._ioInfo;
                null != _ioInfo2 && (_ioInfo2.end = performance.now());
                void 0 === thenable.status && (thenable.status = "rejected", thenable.reason = error);
              }
            }
          );
          ioInfo = payload._ioInfo;
          if (null != ioInfo) {
            ioInfo.value = thenable;
            var displayName = thenable.displayName;
            "string" === typeof displayName && (ioInfo.name = displayName);
          }
          -1 === payload._status && (payload._status = 0, payload._result = thenable);
        }
        if (1 === payload._status)
          return ioInfo = payload._result, void 0 === ioInfo && console.error(
            "lazy: Expected the result of a dynamic import() call. Instead received: %s\n\nYour code should look like: \n  const MyComponent = lazy(() => import('./MyComponent'))\n\nDid you accidentally put curly braces around the import?",
            ioInfo
          ), "default" in ioInfo || console.error(
            "lazy: Expected the result of a dynamic import() call. Instead received: %s\n\nYour code should look like: \n  const MyComponent = lazy(() => import('./MyComponent'))",
            ioInfo
          ), ioInfo.default;
        throw payload._result;
      }
      function resolveDispatcher() {
        var dispatcher = ReactSharedInternals.H;
        null === dispatcher && console.error(
          "Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:\n1. You might have mismatching versions of React and the renderer (such as React DOM)\n2. You might be breaking the Rules of Hooks\n3. You might have more than one copy of React in the same app\nSee https://react.dev/link/invalid-hook-call for tips about how to debug and fix this problem."
        );
        return dispatcher;
      }
      function releaseAsyncTransition() {
        ReactSharedInternals.asyncTransitions--;
      }
      function enqueueTask(task) {
        if (null === enqueueTaskImpl)
          try {
            var requireString = ("require" + Math.random()).slice(0, 7);
            enqueueTaskImpl = (module && module[requireString]).call(
              module,
              "timers"
            ).setImmediate;
          } catch (_err) {
            enqueueTaskImpl = function(callback) {
              false === didWarnAboutMessageChannel && (didWarnAboutMessageChannel = true, "undefined" === typeof MessageChannel && console.error(
                "This browser does not have a MessageChannel implementation, so enqueuing tasks via await act(async () => ...) will fail. Please file an issue at https://github.com/facebook/react/issues if you encounter this warning."
              ));
              var channel = new MessageChannel();
              channel.port1.onmessage = callback;
              channel.port2.postMessage(void 0);
            };
          }
        return enqueueTaskImpl(task);
      }
      function aggregateErrors(errors) {
        return 1 < errors.length && "function" === typeof AggregateError ? new AggregateError(errors) : errors[0];
      }
      function popActScope(prevActQueue, prevActScopeDepth) {
        prevActScopeDepth !== actScopeDepth - 1 && console.error(
          "You seem to have overlapping act() calls, this is not supported. Be sure to await previous act() calls before making a new one. "
        );
        actScopeDepth = prevActScopeDepth;
      }
      function recursivelyFlushAsyncActWork(returnValue, resolve, reject) {
        var queue = ReactSharedInternals.actQueue;
        if (null !== queue)
          if (0 !== queue.length)
            try {
              flushActQueue(queue);
              enqueueTask(function() {
                return recursivelyFlushAsyncActWork(returnValue, resolve, reject);
              });
              return;
            } catch (error) {
              ReactSharedInternals.thrownErrors.push(error);
            }
          else ReactSharedInternals.actQueue = null;
        0 < ReactSharedInternals.thrownErrors.length ? (queue = aggregateErrors(ReactSharedInternals.thrownErrors), ReactSharedInternals.thrownErrors.length = 0, reject(queue)) : resolve(returnValue);
      }
      function flushActQueue(queue) {
        if (!isFlushing) {
          isFlushing = true;
          var i = 0;
          try {
            for (; i < queue.length; i++) {
              var callback = queue[i];
              do {
                ReactSharedInternals.didUsePromise = false;
                var continuation = callback(false);
                if (null !== continuation) {
                  if (ReactSharedInternals.didUsePromise) {
                    queue[i] = callback;
                    queue.splice(0, i);
                    return;
                  }
                  callback = continuation;
                } else break;
              } while (1);
            }
            queue.length = 0;
          } catch (error) {
            queue.splice(0, i + 1), ReactSharedInternals.thrownErrors.push(error);
          } finally {
            isFlushing = false;
          }
        }
      }
      "undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ && "function" === typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart && __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(Error());
      var REACT_ELEMENT_TYPE = /* @__PURE__ */ Symbol.for("react.transitional.element"), REACT_PORTAL_TYPE = /* @__PURE__ */ Symbol.for("react.portal"), REACT_FRAGMENT_TYPE = /* @__PURE__ */ Symbol.for("react.fragment"), REACT_STRICT_MODE_TYPE = /* @__PURE__ */ Symbol.for("react.strict_mode"), REACT_PROFILER_TYPE = /* @__PURE__ */ Symbol.for("react.profiler"), REACT_CONSUMER_TYPE = /* @__PURE__ */ Symbol.for("react.consumer"), REACT_CONTEXT_TYPE = /* @__PURE__ */ Symbol.for("react.context"), REACT_FORWARD_REF_TYPE = /* @__PURE__ */ Symbol.for("react.forward_ref"), REACT_SUSPENSE_TYPE = /* @__PURE__ */ Symbol.for("react.suspense"), REACT_SUSPENSE_LIST_TYPE = /* @__PURE__ */ Symbol.for("react.suspense_list"), REACT_MEMO_TYPE = /* @__PURE__ */ Symbol.for("react.memo"), REACT_LAZY_TYPE = /* @__PURE__ */ Symbol.for("react.lazy"), REACT_ACTIVITY_TYPE = /* @__PURE__ */ Symbol.for("react.activity"), MAYBE_ITERATOR_SYMBOL = Symbol.iterator, didWarnStateUpdateForUnmountedComponent = {}, ReactNoopUpdateQueue = {
        isMounted: function() {
          return false;
        },
        enqueueForceUpdate: function(publicInstance) {
          warnNoop(publicInstance, "forceUpdate");
        },
        enqueueReplaceState: function(publicInstance) {
          warnNoop(publicInstance, "replaceState");
        },
        enqueueSetState: function(publicInstance) {
          warnNoop(publicInstance, "setState");
        }
      }, assign = Object.assign, emptyObject = {};
      Object.freeze(emptyObject);
      Component.prototype.isReactComponent = {};
      Component.prototype.setState = function(partialState, callback) {
        if ("object" !== typeof partialState && "function" !== typeof partialState && null != partialState)
          throw Error(
            "takes an object of state variables to update or a function which returns an object of state variables."
          );
        this.updater.enqueueSetState(this, partialState, callback, "setState");
      };
      Component.prototype.forceUpdate = function(callback) {
        this.updater.enqueueForceUpdate(this, callback, "forceUpdate");
      };
      var deprecatedAPIs = {
        isMounted: [
          "isMounted",
          "Instead, make sure to clean up subscriptions and pending requests in componentWillUnmount to prevent memory leaks."
        ],
        replaceState: [
          "replaceState",
          "Refactor your code to use setState instead (see https://github.com/facebook/react/issues/3236)."
        ]
      };
      for (fnName in deprecatedAPIs)
        deprecatedAPIs.hasOwnProperty(fnName) && defineDeprecationWarning(fnName, deprecatedAPIs[fnName]);
      ComponentDummy.prototype = Component.prototype;
      deprecatedAPIs = PureComponent.prototype = new ComponentDummy();
      deprecatedAPIs.constructor = PureComponent;
      assign(deprecatedAPIs, Component.prototype);
      deprecatedAPIs.isPureReactComponent = true;
      var isArrayImpl = Array.isArray, REACT_CLIENT_REFERENCE = /* @__PURE__ */ Symbol.for("react.client.reference"), ReactSharedInternals = {
        H: null,
        A: null,
        T: null,
        S: null,
        actQueue: null,
        asyncTransitions: 0,
        isBatchingLegacy: false,
        didScheduleLegacyUpdate: false,
        didUsePromise: false,
        thrownErrors: [],
        getCurrentStack: null,
        recentlyCreatedOwnerStacks: 0
      }, hasOwnProperty2 = Object.prototype.hasOwnProperty, createTask = console.createTask ? console.createTask : function() {
        return null;
      };
      deprecatedAPIs = {
        react_stack_bottom_frame: function(callStackForError) {
          return callStackForError();
        }
      };
      var specialPropKeyWarningShown, didWarnAboutOldJSXRuntime;
      var didWarnAboutElementRef = {};
      var unknownOwnerDebugStack = deprecatedAPIs.react_stack_bottom_frame.bind(
        deprecatedAPIs,
        UnknownOwner
      )();
      var unknownOwnerDebugTask = createTask(getTaskName(UnknownOwner));
      var didWarnAboutMaps = false, userProvidedKeyEscapeRegex = /\/+/g, reportGlobalError = "function" === typeof reportError ? reportError : function(error) {
        if ("object" === typeof window && "function" === typeof window.ErrorEvent) {
          var event = new window.ErrorEvent("error", {
            bubbles: true,
            cancelable: true,
            message: "object" === typeof error && null !== error && "string" === typeof error.message ? String(error.message) : String(error),
            error
          });
          if (!window.dispatchEvent(event)) return;
        } else if ("object" === typeof process && "function" === typeof process.emit) {
          process.emit("uncaughtException", error);
          return;
        }
        console.error(error);
      }, didWarnAboutMessageChannel = false, enqueueTaskImpl = null, actScopeDepth = 0, didWarnNoAwaitAct = false, isFlushing = false, queueSeveralMicrotasks = "function" === typeof queueMicrotask ? function(callback) {
        queueMicrotask(function() {
          return queueMicrotask(callback);
        });
      } : enqueueTask;
      deprecatedAPIs = Object.freeze({
        __proto__: null,
        c: function(size) {
          return resolveDispatcher().useMemoCache(size);
        }
      });
      var fnName = {
        map: mapChildren2,
        forEach: function(children, forEachFunc, forEachContext) {
          mapChildren2(
            children,
            function() {
              forEachFunc.apply(this, arguments);
            },
            forEachContext
          );
        },
        count: function(children) {
          var n = 0;
          mapChildren2(children, function() {
            n++;
          });
          return n;
        },
        toArray: function(children) {
          return mapChildren2(children, function(child) {
            return child;
          }) || [];
        },
        only: function(children) {
          if (!isValidElement(children))
            throw Error(
              "React.Children.only expected to receive a single React element child."
            );
          return children;
        }
      };
      exports.Activity = REACT_ACTIVITY_TYPE;
      exports.Children = fnName;
      exports.Component = Component;
      exports.Fragment = REACT_FRAGMENT_TYPE;
      exports.Profiler = REACT_PROFILER_TYPE;
      exports.PureComponent = PureComponent;
      exports.StrictMode = REACT_STRICT_MODE_TYPE;
      exports.Suspense = REACT_SUSPENSE_TYPE;
      exports.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE = ReactSharedInternals;
      exports.__COMPILER_RUNTIME = deprecatedAPIs;
      exports.act = function(callback) {
        var prevActQueue = ReactSharedInternals.actQueue, prevActScopeDepth = actScopeDepth;
        actScopeDepth++;
        var queue = ReactSharedInternals.actQueue = null !== prevActQueue ? prevActQueue : [], didAwaitActCall = false;
        try {
          var result = callback();
        } catch (error) {
          ReactSharedInternals.thrownErrors.push(error);
        }
        if (0 < ReactSharedInternals.thrownErrors.length)
          throw popActScope(prevActQueue, prevActScopeDepth), callback = aggregateErrors(ReactSharedInternals.thrownErrors), ReactSharedInternals.thrownErrors.length = 0, callback;
        if (null !== result && "object" === typeof result && "function" === typeof result.then) {
          var thenable = result;
          queueSeveralMicrotasks(function() {
            didAwaitActCall || didWarnNoAwaitAct || (didWarnNoAwaitAct = true, console.error(
              "You called act(async () => ...) without await. This could lead to unexpected testing behaviour, interleaving multiple act calls and mixing their scopes. You should - await act(async () => ...);"
            ));
          });
          return {
            then: function(resolve, reject) {
              didAwaitActCall = true;
              thenable.then(
                function(returnValue) {
                  popActScope(prevActQueue, prevActScopeDepth);
                  if (0 === prevActScopeDepth) {
                    try {
                      flushActQueue(queue), enqueueTask(function() {
                        return recursivelyFlushAsyncActWork(
                          returnValue,
                          resolve,
                          reject
                        );
                      });
                    } catch (error$0) {
                      ReactSharedInternals.thrownErrors.push(error$0);
                    }
                    if (0 < ReactSharedInternals.thrownErrors.length) {
                      var _thrownError = aggregateErrors(
                        ReactSharedInternals.thrownErrors
                      );
                      ReactSharedInternals.thrownErrors.length = 0;
                      reject(_thrownError);
                    }
                  } else resolve(returnValue);
                },
                function(error) {
                  popActScope(prevActQueue, prevActScopeDepth);
                  0 < ReactSharedInternals.thrownErrors.length ? (error = aggregateErrors(
                    ReactSharedInternals.thrownErrors
                  ), ReactSharedInternals.thrownErrors.length = 0, reject(error)) : reject(error);
                }
              );
            }
          };
        }
        var returnValue$jscomp$0 = result;
        popActScope(prevActQueue, prevActScopeDepth);
        0 === prevActScopeDepth && (flushActQueue(queue), 0 !== queue.length && queueSeveralMicrotasks(function() {
          didAwaitActCall || didWarnNoAwaitAct || (didWarnNoAwaitAct = true, console.error(
            "A component suspended inside an `act` scope, but the `act` call was not awaited. When testing React components that depend on asynchronous data, you must await the result:\n\nawait act(() => ...)"
          ));
        }), ReactSharedInternals.actQueue = null);
        if (0 < ReactSharedInternals.thrownErrors.length)
          throw callback = aggregateErrors(ReactSharedInternals.thrownErrors), ReactSharedInternals.thrownErrors.length = 0, callback;
        return {
          then: function(resolve, reject) {
            didAwaitActCall = true;
            0 === prevActScopeDepth ? (ReactSharedInternals.actQueue = queue, enqueueTask(function() {
              return recursivelyFlushAsyncActWork(
                returnValue$jscomp$0,
                resolve,
                reject
              );
            })) : resolve(returnValue$jscomp$0);
          }
        };
      };
      exports.cache = function(fn) {
        return function() {
          return fn.apply(null, arguments);
        };
      };
      exports.cacheSignal = function() {
        return null;
      };
      exports.captureOwnerStack = function() {
        var getCurrentStack = ReactSharedInternals.getCurrentStack;
        return null === getCurrentStack ? null : getCurrentStack();
      };
      exports.cloneElement = function(element, config, children) {
        if (null === element || void 0 === element)
          throw Error(
            "The argument must be a React element, but you passed " + element + "."
          );
        var props = assign({}, element.props), key = element.key, owner = element._owner;
        if (null != config) {
          var JSCompiler_inline_result;
          a: {
            if (hasOwnProperty2.call(config, "ref") && (JSCompiler_inline_result = Object.getOwnPropertyDescriptor(
              config,
              "ref"
            ).get) && JSCompiler_inline_result.isReactWarning) {
              JSCompiler_inline_result = false;
              break a;
            }
            JSCompiler_inline_result = void 0 !== config.ref;
          }
          JSCompiler_inline_result && (owner = getOwner());
          hasValidKey(config) && (checkKeyStringCoercion(config.key), key = "" + config.key);
          for (propName in config)
            !hasOwnProperty2.call(config, propName) || "key" === propName || "__self" === propName || "__source" === propName || "ref" === propName && void 0 === config.ref || (props[propName] = config[propName]);
        }
        var propName = arguments.length - 2;
        if (1 === propName) props.children = children;
        else if (1 < propName) {
          JSCompiler_inline_result = Array(propName);
          for (var i = 0; i < propName; i++)
            JSCompiler_inline_result[i] = arguments[i + 2];
          props.children = JSCompiler_inline_result;
        }
        props = ReactElement(
          element.type,
          key,
          props,
          owner,
          element._debugStack,
          element._debugTask
        );
        for (key = 2; key < arguments.length; key++)
          validateChildKeys(arguments[key]);
        return props;
      };
      exports.createContext = function(defaultValue) {
        defaultValue = {
          $$typeof: REACT_CONTEXT_TYPE,
          _currentValue: defaultValue,
          _currentValue2: defaultValue,
          _threadCount: 0,
          Provider: null,
          Consumer: null
        };
        defaultValue.Provider = defaultValue;
        defaultValue.Consumer = {
          $$typeof: REACT_CONSUMER_TYPE,
          _context: defaultValue
        };
        defaultValue._currentRenderer = null;
        defaultValue._currentRenderer2 = null;
        return defaultValue;
      };
      exports.createElement = function(type, config, children) {
        for (var i = 2; i < arguments.length; i++)
          validateChildKeys(arguments[i]);
        i = {};
        var key = null;
        if (null != config)
          for (propName in didWarnAboutOldJSXRuntime || !("__self" in config) || "key" in config || (didWarnAboutOldJSXRuntime = true, console.warn(
            "Your app (or one of its dependencies) is using an outdated JSX transform. Update to the modern JSX transform for faster performance: https://react.dev/link/new-jsx-transform"
          )), hasValidKey(config) && (checkKeyStringCoercion(config.key), key = "" + config.key), config)
            hasOwnProperty2.call(config, propName) && "key" !== propName && "__self" !== propName && "__source" !== propName && (i[propName] = config[propName]);
        var childrenLength = arguments.length - 2;
        if (1 === childrenLength) i.children = children;
        else if (1 < childrenLength) {
          for (var childArray = Array(childrenLength), _i = 0; _i < childrenLength; _i++)
            childArray[_i] = arguments[_i + 2];
          Object.freeze && Object.freeze(childArray);
          i.children = childArray;
        }
        if (type && type.defaultProps)
          for (propName in childrenLength = type.defaultProps, childrenLength)
            void 0 === i[propName] && (i[propName] = childrenLength[propName]);
        key && defineKeyPropWarningGetter(
          i,
          "function" === typeof type ? type.displayName || type.name || "Unknown" : type
        );
        var propName = 1e4 > ReactSharedInternals.recentlyCreatedOwnerStacks++;
        return ReactElement(
          type,
          key,
          i,
          getOwner(),
          propName ? Error("react-stack-top-frame") : unknownOwnerDebugStack,
          propName ? createTask(getTaskName(type)) : unknownOwnerDebugTask
        );
      };
      exports.createRef = function() {
        var refObject = { current: null };
        Object.seal(refObject);
        return refObject;
      };
      exports.forwardRef = function(render3) {
        null != render3 && render3.$$typeof === REACT_MEMO_TYPE ? console.error(
          "forwardRef requires a render function but received a `memo` component. Instead of forwardRef(memo(...)), use memo(forwardRef(...))."
        ) : "function" !== typeof render3 ? console.error(
          "forwardRef requires a render function but was given %s.",
          null === render3 ? "null" : typeof render3
        ) : 0 !== render3.length && 2 !== render3.length && console.error(
          "forwardRef render functions accept exactly two parameters: props and ref. %s",
          1 === render3.length ? "Did you forget to use the ref parameter?" : "Any additional parameter will be undefined."
        );
        null != render3 && null != render3.defaultProps && console.error(
          "forwardRef render functions do not support defaultProps. Did you accidentally pass a React component?"
        );
        var elementType = { $$typeof: REACT_FORWARD_REF_TYPE, render: render3 }, ownName;
        Object.defineProperty(elementType, "displayName", {
          enumerable: false,
          configurable: true,
          get: function() {
            return ownName;
          },
          set: function(name) {
            ownName = name;
            render3.name || render3.displayName || (Object.defineProperty(render3, "name", { value: name }), render3.displayName = name);
          }
        });
        return elementType;
      };
      exports.isValidElement = isValidElement;
      exports.lazy = function(ctor) {
        ctor = { _status: -1, _result: ctor };
        var lazyType = {
          $$typeof: REACT_LAZY_TYPE,
          _payload: ctor,
          _init: lazyInitializer
        }, ioInfo = {
          name: "lazy",
          start: -1,
          end: -1,
          value: null,
          owner: null,
          debugStack: Error("react-stack-top-frame"),
          debugTask: console.createTask ? console.createTask("lazy()") : null
        };
        ctor._ioInfo = ioInfo;
        lazyType._debugInfo = [{ awaited: ioInfo }];
        return lazyType;
      };
      exports.memo = function(type, compare) {
        null == type && console.error(
          "memo: The first argument must be a component. Instead received: %s",
          null === type ? "null" : typeof type
        );
        compare = {
          $$typeof: REACT_MEMO_TYPE,
          type,
          compare: void 0 === compare ? null : compare
        };
        var ownName;
        Object.defineProperty(compare, "displayName", {
          enumerable: false,
          configurable: true,
          get: function() {
            return ownName;
          },
          set: function(name) {
            ownName = name;
            type.name || type.displayName || (Object.defineProperty(type, "name", { value: name }), type.displayName = name);
          }
        });
        return compare;
      };
      exports.startTransition = function(scope) {
        var prevTransition = ReactSharedInternals.T, currentTransition = {};
        currentTransition._updatedFibers = /* @__PURE__ */ new Set();
        ReactSharedInternals.T = currentTransition;
        try {
          var returnValue = scope(), onStartTransitionFinish = ReactSharedInternals.S;
          null !== onStartTransitionFinish && onStartTransitionFinish(currentTransition, returnValue);
          "object" === typeof returnValue && null !== returnValue && "function" === typeof returnValue.then && (ReactSharedInternals.asyncTransitions++, returnValue.then(releaseAsyncTransition, releaseAsyncTransition), returnValue.then(noop3, reportGlobalError));
        } catch (error) {
          reportGlobalError(error);
        } finally {
          null === prevTransition && currentTransition._updatedFibers && (scope = currentTransition._updatedFibers.size, currentTransition._updatedFibers.clear(), 10 < scope && console.warn(
            "Detected a large number of updates inside startTransition. If this is due to a subscription please re-write it to use React provided hooks. Otherwise concurrent mode guarantees are off the table."
          )), null !== prevTransition && null !== currentTransition.types && (null !== prevTransition.types && prevTransition.types !== currentTransition.types && console.error(
            "We expected inner Transitions to have transferred the outer types set and that you cannot add to the outer Transition while inside the inner.This is a bug in React."
          ), prevTransition.types = currentTransition.types), ReactSharedInternals.T = prevTransition;
        }
      };
      exports.unstable_useCacheRefresh = function() {
        return resolveDispatcher().useCacheRefresh();
      };
      exports.use = function(usable) {
        return resolveDispatcher().use(usable);
      };
      exports.useActionState = function(action, initialState, permalink) {
        return resolveDispatcher().useActionState(
          action,
          initialState,
          permalink
        );
      };
      exports.useCallback = function(callback, deps) {
        return resolveDispatcher().useCallback(callback, deps);
      };
      exports.useContext = function(Context) {
        var dispatcher = resolveDispatcher();
        Context.$$typeof === REACT_CONSUMER_TYPE && console.error(
          "Calling useContext(Context.Consumer) is not supported and will cause bugs. Did you mean to call useContext(Context) instead?"
        );
        return dispatcher.useContext(Context);
      };
      exports.useDebugValue = function(value, formatterFn) {
        return resolveDispatcher().useDebugValue(value, formatterFn);
      };
      exports.useDeferredValue = function(value, initialValue) {
        return resolveDispatcher().useDeferredValue(value, initialValue);
      };
      exports.useEffect = function(create, deps) {
        null == create && console.warn(
          "React Hook useEffect requires an effect callback. Did you forget to pass a callback to the hook?"
        );
        return resolveDispatcher().useEffect(create, deps);
      };
      exports.useEffectEvent = function(callback) {
        return resolveDispatcher().useEffectEvent(callback);
      };
      exports.useId = function() {
        return resolveDispatcher().useId();
      };
      exports.useImperativeHandle = function(ref, create, deps) {
        return resolveDispatcher().useImperativeHandle(ref, create, deps);
      };
      exports.useInsertionEffect = function(create, deps) {
        null == create && console.warn(
          "React Hook useInsertionEffect requires an effect callback. Did you forget to pass a callback to the hook?"
        );
        return resolveDispatcher().useInsertionEffect(create, deps);
      };
      exports.useLayoutEffect = function(create, deps) {
        null == create && console.warn(
          "React Hook useLayoutEffect requires an effect callback. Did you forget to pass a callback to the hook?"
        );
        return resolveDispatcher().useLayoutEffect(create, deps);
      };
      exports.useMemo = function(create, deps) {
        return resolveDispatcher().useMemo(create, deps);
      };
      exports.useOptimistic = function(passthrough, reducer) {
        return resolveDispatcher().useOptimistic(passthrough, reducer);
      };
      exports.useReducer = function(reducer, initialArg, init2) {
        return resolveDispatcher().useReducer(reducer, initialArg, init2);
      };
      exports.useRef = function(initialValue) {
        return resolveDispatcher().useRef(initialValue);
      };
      exports.useState = function(initialState) {
        return resolveDispatcher().useState(initialState);
      };
      exports.useSyncExternalStore = function(subscribe2, getSnapshot, getServerSnapshot) {
        return resolveDispatcher().useSyncExternalStore(
          subscribe2,
          getSnapshot,
          getServerSnapshot
        );
      };
      exports.useTransition = function() {
        return resolveDispatcher().useTransition();
      };
      exports.version = "19.2.3";
      "undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ && "function" === typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop && __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(Error());
    })();
  }
});

// ../../node_modules/.pnpm/react@19.2.3/node_modules/react/index.js
var require_react = __commonJS({
  "../../node_modules/.pnpm/react@19.2.3/node_modules/react/index.js"(exports, module) {
    "use strict";
    if (false) {
      module.exports = null;
    } else {
      module.exports = require_react_development();
    }
  }
});

// ../../node_modules/.pnpm/scheduler@0.27.0/node_modules/scheduler/cjs/scheduler.development.js
var require_scheduler_development = __commonJS({
  "../../node_modules/.pnpm/scheduler@0.27.0/node_modules/scheduler/cjs/scheduler.development.js"(exports) {
    "use strict";
    (function() {
      function performWorkUntilDeadline() {
        needsPaint = false;
        if (isMessageLoopRunning) {
          var currentTime = exports.unstable_now();
          startTime = currentTime;
          var hasMoreWork = true;
          try {
            a: {
              isHostCallbackScheduled = false;
              isHostTimeoutScheduled && (isHostTimeoutScheduled = false, localClearTimeout(taskTimeoutID), taskTimeoutID = -1);
              isPerformingWork = true;
              var previousPriorityLevel = currentPriorityLevel;
              try {
                b: {
                  advanceTimers(currentTime);
                  for (currentTask = peek(taskQueue); null !== currentTask && !(currentTask.expirationTime > currentTime && shouldYieldToHost()); ) {
                    var callback = currentTask.callback;
                    if ("function" === typeof callback) {
                      currentTask.callback = null;
                      currentPriorityLevel = currentTask.priorityLevel;
                      var continuationCallback = callback(
                        currentTask.expirationTime <= currentTime
                      );
                      currentTime = exports.unstable_now();
                      if ("function" === typeof continuationCallback) {
                        currentTask.callback = continuationCallback;
                        advanceTimers(currentTime);
                        hasMoreWork = true;
                        break b;
                      }
                      currentTask === peek(taskQueue) && pop(taskQueue);
                      advanceTimers(currentTime);
                    } else pop(taskQueue);
                    currentTask = peek(taskQueue);
                  }
                  if (null !== currentTask) hasMoreWork = true;
                  else {
                    var firstTimer = peek(timerQueue);
                    null !== firstTimer && requestHostTimeout(
                      handleTimeout,
                      firstTimer.startTime - currentTime
                    );
                    hasMoreWork = false;
                  }
                }
                break a;
              } finally {
                currentTask = null, currentPriorityLevel = previousPriorityLevel, isPerformingWork = false;
              }
              hasMoreWork = void 0;
            }
          } finally {
            hasMoreWork ? schedulePerformWorkUntilDeadline() : isMessageLoopRunning = false;
          }
        }
      }
      function push(heap, node) {
        var index = heap.length;
        heap.push(node);
        a: for (; 0 < index; ) {
          var parentIndex = index - 1 >>> 1, parent = heap[parentIndex];
          if (0 < compare(parent, node))
            heap[parentIndex] = node, heap[index] = parent, index = parentIndex;
          else break a;
        }
      }
      function peek(heap) {
        return 0 === heap.length ? null : heap[0];
      }
      function pop(heap) {
        if (0 === heap.length) return null;
        var first2 = heap[0], last = heap.pop();
        if (last !== first2) {
          heap[0] = last;
          a: for (var index = 0, length = heap.length, halfLength = length >>> 1; index < halfLength; ) {
            var leftIndex = 2 * (index + 1) - 1, left = heap[leftIndex], rightIndex = leftIndex + 1, right = heap[rightIndex];
            if (0 > compare(left, last))
              rightIndex < length && 0 > compare(right, left) ? (heap[index] = right, heap[rightIndex] = last, index = rightIndex) : (heap[index] = left, heap[leftIndex] = last, index = leftIndex);
            else if (rightIndex < length && 0 > compare(right, last))
              heap[index] = right, heap[rightIndex] = last, index = rightIndex;
            else break a;
          }
        }
        return first2;
      }
      function compare(a2, b2) {
        var diff = a2.sortIndex - b2.sortIndex;
        return 0 !== diff ? diff : a2.id - b2.id;
      }
      function advanceTimers(currentTime) {
        for (var timer = peek(timerQueue); null !== timer; ) {
          if (null === timer.callback) pop(timerQueue);
          else if (timer.startTime <= currentTime)
            pop(timerQueue), timer.sortIndex = timer.expirationTime, push(taskQueue, timer);
          else break;
          timer = peek(timerQueue);
        }
      }
      function handleTimeout(currentTime) {
        isHostTimeoutScheduled = false;
        advanceTimers(currentTime);
        if (!isHostCallbackScheduled)
          if (null !== peek(taskQueue))
            isHostCallbackScheduled = true, isMessageLoopRunning || (isMessageLoopRunning = true, schedulePerformWorkUntilDeadline());
          else {
            var firstTimer = peek(timerQueue);
            null !== firstTimer && requestHostTimeout(
              handleTimeout,
              firstTimer.startTime - currentTime
            );
          }
      }
      function shouldYieldToHost() {
        return needsPaint ? true : exports.unstable_now() - startTime < frameInterval ? false : true;
      }
      function requestHostTimeout(callback, ms) {
        taskTimeoutID = localSetTimeout(function() {
          callback(exports.unstable_now());
        }, ms);
      }
      "undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ && "function" === typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart && __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(Error());
      exports.unstable_now = void 0;
      if ("object" === typeof performance && "function" === typeof performance.now) {
        var localPerformance = performance;
        exports.unstable_now = function() {
          return localPerformance.now();
        };
      } else {
        var localDate = Date, initialTime = localDate.now();
        exports.unstable_now = function() {
          return localDate.now() - initialTime;
        };
      }
      var taskQueue = [], timerQueue = [], taskIdCounter = 1, currentTask = null, currentPriorityLevel = 3, isPerformingWork = false, isHostCallbackScheduled = false, isHostTimeoutScheduled = false, needsPaint = false, localSetTimeout = "function" === typeof setTimeout ? setTimeout : null, localClearTimeout = "function" === typeof clearTimeout ? clearTimeout : null, localSetImmediate = "undefined" !== typeof setImmediate ? setImmediate : null, isMessageLoopRunning = false, taskTimeoutID = -1, frameInterval = 5, startTime = -1;
      if ("function" === typeof localSetImmediate)
        var schedulePerformWorkUntilDeadline = function() {
          localSetImmediate(performWorkUntilDeadline);
        };
      else if ("undefined" !== typeof MessageChannel) {
        var channel = new MessageChannel(), port = channel.port2;
        channel.port1.onmessage = performWorkUntilDeadline;
        schedulePerformWorkUntilDeadline = function() {
          port.postMessage(null);
        };
      } else
        schedulePerformWorkUntilDeadline = function() {
          localSetTimeout(performWorkUntilDeadline, 0);
        };
      exports.unstable_IdlePriority = 5;
      exports.unstable_ImmediatePriority = 1;
      exports.unstable_LowPriority = 4;
      exports.unstable_NormalPriority = 3;
      exports.unstable_Profiling = null;
      exports.unstable_UserBlockingPriority = 2;
      exports.unstable_cancelCallback = function(task) {
        task.callback = null;
      };
      exports.unstable_forceFrameRate = function(fps) {
        0 > fps || 125 < fps ? console.error(
          "forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"
        ) : frameInterval = 0 < fps ? Math.floor(1e3 / fps) : 5;
      };
      exports.unstable_getCurrentPriorityLevel = function() {
        return currentPriorityLevel;
      };
      exports.unstable_next = function(eventHandler) {
        switch (currentPriorityLevel) {
          case 1:
          case 2:
          case 3:
            var priorityLevel = 3;
            break;
          default:
            priorityLevel = currentPriorityLevel;
        }
        var previousPriorityLevel = currentPriorityLevel;
        currentPriorityLevel = priorityLevel;
        try {
          return eventHandler();
        } finally {
          currentPriorityLevel = previousPriorityLevel;
        }
      };
      exports.unstable_requestPaint = function() {
        needsPaint = true;
      };
      exports.unstable_runWithPriority = function(priorityLevel, eventHandler) {
        switch (priorityLevel) {
          case 1:
          case 2:
          case 3:
          case 4:
          case 5:
            break;
          default:
            priorityLevel = 3;
        }
        var previousPriorityLevel = currentPriorityLevel;
        currentPriorityLevel = priorityLevel;
        try {
          return eventHandler();
        } finally {
          currentPriorityLevel = previousPriorityLevel;
        }
      };
      exports.unstable_scheduleCallback = function(priorityLevel, callback, options) {
        var currentTime = exports.unstable_now();
        "object" === typeof options && null !== options ? (options = options.delay, options = "number" === typeof options && 0 < options ? currentTime + options : currentTime) : options = currentTime;
        switch (priorityLevel) {
          case 1:
            var timeout = -1;
            break;
          case 2:
            timeout = 250;
            break;
          case 5:
            timeout = 1073741823;
            break;
          case 4:
            timeout = 1e4;
            break;
          default:
            timeout = 5e3;
        }
        timeout = options + timeout;
        priorityLevel = {
          id: taskIdCounter++,
          callback,
          priorityLevel,
          startTime: options,
          expirationTime: timeout,
          sortIndex: -1
        };
        options > currentTime ? (priorityLevel.sortIndex = options, push(timerQueue, priorityLevel), null === peek(taskQueue) && priorityLevel === peek(timerQueue) && (isHostTimeoutScheduled ? (localClearTimeout(taskTimeoutID), taskTimeoutID = -1) : isHostTimeoutScheduled = true, requestHostTimeout(handleTimeout, options - currentTime))) : (priorityLevel.sortIndex = timeout, push(taskQueue, priorityLevel), isHostCallbackScheduled || isPerformingWork || (isHostCallbackScheduled = true, isMessageLoopRunning || (isMessageLoopRunning = true, schedulePerformWorkUntilDeadline())));
        return priorityLevel;
      };
      exports.unstable_shouldYield = shouldYieldToHost;
      exports.unstable_wrapCallback = function(callback) {
        var parentPriorityLevel = currentPriorityLevel;
        return function() {
          var previousPriorityLevel = currentPriorityLevel;
          currentPriorityLevel = parentPriorityLevel;
          try {
            return callback.apply(this, arguments);
          } finally {
            currentPriorityLevel = previousPriorityLevel;
          }
        };
      };
      "undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ && "function" === typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop && __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(Error());
    })();
  }
});

// ../../node_modules/.pnpm/scheduler@0.27.0/node_modules/scheduler/index.js
var require_scheduler = __commonJS({
  "../../node_modules/.pnpm/scheduler@0.27.0/node_modules/scheduler/index.js"(exports, module) {
    "use strict";
    if (false) {
      module.exports = null;
    } else {
      module.exports = require_scheduler_development();
    }
  }
});

// ../../node_modules/.pnpm/react-dom@19.2.3_react@19.2.3/node_modules/react-dom/cjs/react-dom.development.js
var require_react_dom_development = __commonJS({
  "../../node_modules/.pnpm/react-dom@19.2.3_react@19.2.3/node_modules/react-dom/cjs/react-dom.development.js"(exports) {
    "use strict";
    (function() {
      function noop3() {
      }
      function testStringCoercion(value) {
        return "" + value;
      }
      function createPortal$1(children, containerInfo, implementation) {
        var key = 3 < arguments.length && void 0 !== arguments[3] ? arguments[3] : null;
        try {
          testStringCoercion(key);
          var JSCompiler_inline_result = false;
        } catch (e) {
          JSCompiler_inline_result = true;
        }
        JSCompiler_inline_result && (console.error(
          "The provided key is an unsupported type %s. This value must be coerced to a string before using it here.",
          "function" === typeof Symbol && Symbol.toStringTag && key[Symbol.toStringTag] || key.constructor.name || "Object"
        ), testStringCoercion(key));
        return {
          $$typeof: REACT_PORTAL_TYPE,
          key: null == key ? null : "" + key,
          children,
          containerInfo,
          implementation
        };
      }
      function getCrossOriginStringAs(as, input) {
        if ("font" === as) return "";
        if ("string" === typeof input)
          return "use-credentials" === input ? input : "";
      }
      function getValueDescriptorExpectingObjectForWarning(thing) {
        return null === thing ? "`null`" : void 0 === thing ? "`undefined`" : "" === thing ? "an empty string" : 'something with type "' + typeof thing + '"';
      }
      function getValueDescriptorExpectingEnumForWarning(thing) {
        return null === thing ? "`null`" : void 0 === thing ? "`undefined`" : "" === thing ? "an empty string" : "string" === typeof thing ? JSON.stringify(thing) : "number" === typeof thing ? "`" + thing + "`" : 'something with type "' + typeof thing + '"';
      }
      function resolveDispatcher() {
        var dispatcher = ReactSharedInternals.H;
        null === dispatcher && console.error(
          "Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:\n1. You might have mismatching versions of React and the renderer (such as React DOM)\n2. You might be breaking the Rules of Hooks\n3. You might have more than one copy of React in the same app\nSee https://react.dev/link/invalid-hook-call for tips about how to debug and fix this problem."
        );
        return dispatcher;
      }
      "undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ && "function" === typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart && __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(Error());
      var React7 = require_react(), Internals = {
        d: {
          f: noop3,
          r: function() {
            throw Error(
              "Invalid form element. requestFormReset must be passed a form that was rendered by React."
            );
          },
          D: noop3,
          C: noop3,
          L: noop3,
          m: noop3,
          X: noop3,
          S: noop3,
          M: noop3
        },
        p: 0,
        findDOMNode: null
      }, REACT_PORTAL_TYPE = /* @__PURE__ */ Symbol.for("react.portal"), ReactSharedInternals = React7.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE;
      "function" === typeof Map && null != Map.prototype && "function" === typeof Map.prototype.forEach && "function" === typeof Set && null != Set.prototype && "function" === typeof Set.prototype.clear && "function" === typeof Set.prototype.forEach || console.error(
        "React depends on Map and Set built-in types. Make sure that you load a polyfill in older browsers. https://reactjs.org/link/react-polyfills"
      );
      exports.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE = Internals;
      exports.createPortal = function(children, container) {
        var key = 2 < arguments.length && void 0 !== arguments[2] ? arguments[2] : null;
        if (!container || 1 !== container.nodeType && 9 !== container.nodeType && 11 !== container.nodeType)
          throw Error("Target container is not a DOM element.");
        return createPortal$1(children, container, null, key);
      };
      exports.flushSync = function(fn) {
        var previousTransition = ReactSharedInternals.T, previousUpdatePriority = Internals.p;
        try {
          if (ReactSharedInternals.T = null, Internals.p = 2, fn)
            return fn();
        } finally {
          ReactSharedInternals.T = previousTransition, Internals.p = previousUpdatePriority, Internals.d.f() && console.error(
            "flushSync was called from inside a lifecycle method. React cannot flush when React is already rendering. Consider moving this call to a scheduler task or micro task."
          );
        }
      };
      exports.preconnect = function(href, options) {
        "string" === typeof href && href ? null != options && "object" !== typeof options ? console.error(
          "ReactDOM.preconnect(): Expected the `options` argument (second) to be an object but encountered %s instead. The only supported option at this time is `crossOrigin` which accepts a string.",
          getValueDescriptorExpectingEnumForWarning(options)
        ) : null != options && "string" !== typeof options.crossOrigin && console.error(
          "ReactDOM.preconnect(): Expected the `crossOrigin` option (second argument) to be a string but encountered %s instead. Try removing this option or passing a string value instead.",
          getValueDescriptorExpectingObjectForWarning(options.crossOrigin)
        ) : console.error(
          "ReactDOM.preconnect(): Expected the `href` argument (first) to be a non-empty string but encountered %s instead.",
          getValueDescriptorExpectingObjectForWarning(href)
        );
        "string" === typeof href && (options ? (options = options.crossOrigin, options = "string" === typeof options ? "use-credentials" === options ? options : "" : void 0) : options = null, Internals.d.C(href, options));
      };
      exports.prefetchDNS = function(href) {
        if ("string" !== typeof href || !href)
          console.error(
            "ReactDOM.prefetchDNS(): Expected the `href` argument (first) to be a non-empty string but encountered %s instead.",
            getValueDescriptorExpectingObjectForWarning(href)
          );
        else if (1 < arguments.length) {
          var options = arguments[1];
          "object" === typeof options && options.hasOwnProperty("crossOrigin") ? console.error(
            "ReactDOM.prefetchDNS(): Expected only one argument, `href`, but encountered %s as a second argument instead. This argument is reserved for future options and is currently disallowed. It looks like the you are attempting to set a crossOrigin property for this DNS lookup hint. Browsers do not perform DNS queries using CORS and setting this attribute on the resource hint has no effect. Try calling ReactDOM.prefetchDNS() with just a single string argument, `href`.",
            getValueDescriptorExpectingEnumForWarning(options)
          ) : console.error(
            "ReactDOM.prefetchDNS(): Expected only one argument, `href`, but encountered %s as a second argument instead. This argument is reserved for future options and is currently disallowed. Try calling ReactDOM.prefetchDNS() with just a single string argument, `href`.",
            getValueDescriptorExpectingEnumForWarning(options)
          );
        }
        "string" === typeof href && Internals.d.D(href);
      };
      exports.preinit = function(href, options) {
        "string" === typeof href && href ? null == options || "object" !== typeof options ? console.error(
          "ReactDOM.preinit(): Expected the `options` argument (second) to be an object with an `as` property describing the type of resource to be preinitialized but encountered %s instead.",
          getValueDescriptorExpectingEnumForWarning(options)
        ) : "style" !== options.as && "script" !== options.as && console.error(
          'ReactDOM.preinit(): Expected the `as` property in the `options` argument (second) to contain a valid value describing the type of resource to be preinitialized but encountered %s instead. Valid values for `as` are "style" and "script".',
          getValueDescriptorExpectingEnumForWarning(options.as)
        ) : console.error(
          "ReactDOM.preinit(): Expected the `href` argument (first) to be a non-empty string but encountered %s instead.",
          getValueDescriptorExpectingObjectForWarning(href)
        );
        if ("string" === typeof href && options && "string" === typeof options.as) {
          var as = options.as, crossOrigin = getCrossOriginStringAs(as, options.crossOrigin), integrity = "string" === typeof options.integrity ? options.integrity : void 0, fetchPriority = "string" === typeof options.fetchPriority ? options.fetchPriority : void 0;
          "style" === as ? Internals.d.S(
            href,
            "string" === typeof options.precedence ? options.precedence : void 0,
            {
              crossOrigin,
              integrity,
              fetchPriority
            }
          ) : "script" === as && Internals.d.X(href, {
            crossOrigin,
            integrity,
            fetchPriority,
            nonce: "string" === typeof options.nonce ? options.nonce : void 0
          });
        }
      };
      exports.preinitModule = function(href, options) {
        var encountered = "";
        "string" === typeof href && href || (encountered += " The `href` argument encountered was " + getValueDescriptorExpectingObjectForWarning(href) + ".");
        void 0 !== options && "object" !== typeof options ? encountered += " The `options` argument encountered was " + getValueDescriptorExpectingObjectForWarning(options) + "." : options && "as" in options && "script" !== options.as && (encountered += " The `as` option encountered was " + getValueDescriptorExpectingEnumForWarning(options.as) + ".");
        if (encountered)
          console.error(
            "ReactDOM.preinitModule(): Expected up to two arguments, a non-empty `href` string and, optionally, an `options` object with a valid `as` property.%s",
            encountered
          );
        else
          switch (encountered = options && "string" === typeof options.as ? options.as : "script", encountered) {
            case "script":
              break;
            default:
              encountered = getValueDescriptorExpectingEnumForWarning(encountered), console.error(
                'ReactDOM.preinitModule(): Currently the only supported "as" type for this function is "script" but received "%s" instead. This warning was generated for `href` "%s". In the future other module types will be supported, aligning with the import-attributes proposal. Learn more here: (https://github.com/tc39/proposal-import-attributes)',
                encountered,
                href
              );
          }
        if ("string" === typeof href)
          if ("object" === typeof options && null !== options) {
            if (null == options.as || "script" === options.as)
              encountered = getCrossOriginStringAs(
                options.as,
                options.crossOrigin
              ), Internals.d.M(href, {
                crossOrigin: encountered,
                integrity: "string" === typeof options.integrity ? options.integrity : void 0,
                nonce: "string" === typeof options.nonce ? options.nonce : void 0
              });
          } else null == options && Internals.d.M(href);
      };
      exports.preload = function(href, options) {
        var encountered = "";
        "string" === typeof href && href || (encountered += " The `href` argument encountered was " + getValueDescriptorExpectingObjectForWarning(href) + ".");
        null == options || "object" !== typeof options ? encountered += " The `options` argument encountered was " + getValueDescriptorExpectingObjectForWarning(options) + "." : "string" === typeof options.as && options.as || (encountered += " The `as` option encountered was " + getValueDescriptorExpectingObjectForWarning(options.as) + ".");
        encountered && console.error(
          'ReactDOM.preload(): Expected two arguments, a non-empty `href` string and an `options` object with an `as` property valid for a `<link rel="preload" as="..." />` tag.%s',
          encountered
        );
        if ("string" === typeof href && "object" === typeof options && null !== options && "string" === typeof options.as) {
          encountered = options.as;
          var crossOrigin = getCrossOriginStringAs(
            encountered,
            options.crossOrigin
          );
          Internals.d.L(href, encountered, {
            crossOrigin,
            integrity: "string" === typeof options.integrity ? options.integrity : void 0,
            nonce: "string" === typeof options.nonce ? options.nonce : void 0,
            type: "string" === typeof options.type ? options.type : void 0,
            fetchPriority: "string" === typeof options.fetchPriority ? options.fetchPriority : void 0,
            referrerPolicy: "string" === typeof options.referrerPolicy ? options.referrerPolicy : void 0,
            imageSrcSet: "string" === typeof options.imageSrcSet ? options.imageSrcSet : void 0,
            imageSizes: "string" === typeof options.imageSizes ? options.imageSizes : void 0,
            media: "string" === typeof options.media ? options.media : void 0
          });
        }
      };
      exports.preloadModule = function(href, options) {
        var encountered = "";
        "string" === typeof href && href || (encountered += " The `href` argument encountered was " + getValueDescriptorExpectingObjectForWarning(href) + ".");
        void 0 !== options && "object" !== typeof options ? encountered += " The `options` argument encountered was " + getValueDescriptorExpectingObjectForWarning(options) + "." : options && "as" in options && "string" !== typeof options.as && (encountered += " The `as` option encountered was " + getValueDescriptorExpectingObjectForWarning(options.as) + ".");
        encountered && console.error(
          'ReactDOM.preloadModule(): Expected two arguments, a non-empty `href` string and, optionally, an `options` object with an `as` property valid for a `<link rel="modulepreload" as="..." />` tag.%s',
          encountered
        );
        "string" === typeof href && (options ? (encountered = getCrossOriginStringAs(
          options.as,
          options.crossOrigin
        ), Internals.d.m(href, {
          as: "string" === typeof options.as && "script" !== options.as ? options.as : void 0,
          crossOrigin: encountered,
          integrity: "string" === typeof options.integrity ? options.integrity : void 0
        })) : Internals.d.m(href));
      };
      exports.requestFormReset = function(form) {
        Internals.d.r(form);
      };
      exports.unstable_batchedUpdates = function(fn, a2) {
        return fn(a2);
      };
      exports.useFormState = function(action, initialState, permalink) {
        return resolveDispatcher().useFormState(action, initialState, permalink);
      };
      exports.useFormStatus = function() {
        return resolveDispatcher().useHostTransitionStatus();
      };
      exports.version = "19.2.3";
      "undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ && "function" === typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop && __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(Error());
    })();
  }
});

// ../../node_modules/.pnpm/react-dom@19.2.3_react@19.2.3/node_modules/react-dom/index.js
var require_react_dom = __commonJS({
  "../../node_modules/.pnpm/react-dom@19.2.3_react@19.2.3/node_modules/react-dom/index.js"(exports, module) {
    "use strict";
    if (false) {
      checkDCE();
      module.exports = null;
    } else {
      module.exports = require_react_dom_development();
    }
  }
});

// ../../node_modules/.pnpm/react-dom@19.2.3_react@19.2.3/node_modules/react-dom/cjs/react-dom-client.development.js
var require_react_dom_client_development = __commonJS({
  "../../node_modules/.pnpm/react-dom@19.2.3_react@19.2.3/node_modules/react-dom/cjs/react-dom-client.development.js"(exports) {
    "use strict";
    (function() {
      function findHook(fiber, id) {
        for (fiber = fiber.memoizedState; null !== fiber && 0 < id; )
          fiber = fiber.next, id--;
        return fiber;
      }
      function copyWithSetImpl(obj, path2, index, value) {
        if (index >= path2.length) return value;
        var key = path2[index], updated = isArrayImpl(obj) ? obj.slice() : assign({}, obj);
        updated[key] = copyWithSetImpl(obj[key], path2, index + 1, value);
        return updated;
      }
      function copyWithRename(obj, oldPath, newPath) {
        if (oldPath.length !== newPath.length)
          console.warn("copyWithRename() expects paths of the same length");
        else {
          for (var i = 0; i < newPath.length - 1; i++)
            if (oldPath[i] !== newPath[i]) {
              console.warn(
                "copyWithRename() expects paths to be the same except for the deepest key"
              );
              return;
            }
          return copyWithRenameImpl(obj, oldPath, newPath, 0);
        }
      }
      function copyWithRenameImpl(obj, oldPath, newPath, index) {
        var oldKey = oldPath[index], updated = isArrayImpl(obj) ? obj.slice() : assign({}, obj);
        index + 1 === oldPath.length ? (updated[newPath[index]] = updated[oldKey], isArrayImpl(updated) ? updated.splice(oldKey, 1) : delete updated[oldKey]) : updated[oldKey] = copyWithRenameImpl(
          obj[oldKey],
          oldPath,
          newPath,
          index + 1
        );
        return updated;
      }
      function copyWithDeleteImpl(obj, path2, index) {
        var key = path2[index], updated = isArrayImpl(obj) ? obj.slice() : assign({}, obj);
        if (index + 1 === path2.length)
          return isArrayImpl(updated) ? updated.splice(key, 1) : delete updated[key], updated;
        updated[key] = copyWithDeleteImpl(obj[key], path2, index + 1);
        return updated;
      }
      function shouldSuspendImpl() {
        return false;
      }
      function shouldErrorImpl() {
        return null;
      }
      function warnInvalidHookAccess() {
        console.error(
          "Do not call Hooks inside useEffect(...), useMemo(...), or other built-in Hooks. You can only call Hooks at the top level of your React function. For more information, see https://react.dev/link/rules-of-hooks"
        );
      }
      function warnInvalidContextAccess() {
        console.error(
          "Context can only be read while React is rendering. In classes, you can read it in the render method or getDerivedStateFromProps. In function components, you can read it directly in the function body, but not inside Hooks like useReducer() or useMemo()."
        );
      }
      function noop3() {
      }
      function warnForMissingKey() {
      }
      function setToSortedString(set) {
        var array = [];
        set.forEach(function(value) {
          array.push(value);
        });
        return array.sort().join(", ");
      }
      function createFiber(tag, pendingProps, key, mode) {
        return new FiberNode(tag, pendingProps, key, mode);
      }
      function scheduleRoot(root2, element) {
        root2.context === emptyContextObject && (updateContainerImpl(root2.current, 2, element, root2, null, null), flushSyncWork$1());
      }
      function scheduleRefresh(root2, update) {
        if (null !== resolveFamily) {
          var staleFamilies = update.staleFamilies;
          update = update.updatedFamilies;
          flushPendingEffects();
          scheduleFibersWithFamiliesRecursively(
            root2.current,
            update,
            staleFamilies
          );
          flushSyncWork$1();
        }
      }
      function setRefreshHandler(handler) {
        resolveFamily = handler;
      }
      function isValidContainer(node) {
        return !(!node || 1 !== node.nodeType && 9 !== node.nodeType && 11 !== node.nodeType);
      }
      function getNearestMountedFiber(fiber) {
        var node = fiber, nearestMounted = fiber;
        if (fiber.alternate) for (; node.return; ) node = node.return;
        else {
          fiber = node;
          do
            node = fiber, 0 !== (node.flags & 4098) && (nearestMounted = node.return), fiber = node.return;
          while (fiber);
        }
        return 3 === node.tag ? nearestMounted : null;
      }
      function getSuspenseInstanceFromFiber(fiber) {
        if (13 === fiber.tag) {
          var suspenseState = fiber.memoizedState;
          null === suspenseState && (fiber = fiber.alternate, null !== fiber && (suspenseState = fiber.memoizedState));
          if (null !== suspenseState) return suspenseState.dehydrated;
        }
        return null;
      }
      function getActivityInstanceFromFiber(fiber) {
        if (31 === fiber.tag) {
          var activityState = fiber.memoizedState;
          null === activityState && (fiber = fiber.alternate, null !== fiber && (activityState = fiber.memoizedState));
          if (null !== activityState) return activityState.dehydrated;
        }
        return null;
      }
      function assertIsMounted(fiber) {
        if (getNearestMountedFiber(fiber) !== fiber)
          throw Error("Unable to find node on an unmounted component.");
      }
      function findCurrentFiberUsingSlowPath(fiber) {
        var alternate = fiber.alternate;
        if (!alternate) {
          alternate = getNearestMountedFiber(fiber);
          if (null === alternate)
            throw Error("Unable to find node on an unmounted component.");
          return alternate !== fiber ? null : fiber;
        }
        for (var a2 = fiber, b2 = alternate; ; ) {
          var parentA = a2.return;
          if (null === parentA) break;
          var parentB = parentA.alternate;
          if (null === parentB) {
            b2 = parentA.return;
            if (null !== b2) {
              a2 = b2;
              continue;
            }
            break;
          }
          if (parentA.child === parentB.child) {
            for (parentB = parentA.child; parentB; ) {
              if (parentB === a2) return assertIsMounted(parentA), fiber;
              if (parentB === b2) return assertIsMounted(parentA), alternate;
              parentB = parentB.sibling;
            }
            throw Error("Unable to find node on an unmounted component.");
          }
          if (a2.return !== b2.return) a2 = parentA, b2 = parentB;
          else {
            for (var didFindChild = false, _child = parentA.child; _child; ) {
              if (_child === a2) {
                didFindChild = true;
                a2 = parentA;
                b2 = parentB;
                break;
              }
              if (_child === b2) {
                didFindChild = true;
                b2 = parentA;
                a2 = parentB;
                break;
              }
              _child = _child.sibling;
            }
            if (!didFindChild) {
              for (_child = parentB.child; _child; ) {
                if (_child === a2) {
                  didFindChild = true;
                  a2 = parentB;
                  b2 = parentA;
                  break;
                }
                if (_child === b2) {
                  didFindChild = true;
                  b2 = parentB;
                  a2 = parentA;
                  break;
                }
                _child = _child.sibling;
              }
              if (!didFindChild)
                throw Error(
                  "Child was not found in either parent set. This indicates a bug in React related to the return pointer. Please file an issue."
                );
            }
          }
          if (a2.alternate !== b2)
            throw Error(
              "Return fibers should always be each others' alternates. This error is likely caused by a bug in React. Please file an issue."
            );
        }
        if (3 !== a2.tag)
          throw Error("Unable to find node on an unmounted component.");
        return a2.stateNode.current === a2 ? fiber : alternate;
      }
      function findCurrentHostFiberImpl(node) {
        var tag = node.tag;
        if (5 === tag || 26 === tag || 27 === tag || 6 === tag) return node;
        for (node = node.child; null !== node; ) {
          tag = findCurrentHostFiberImpl(node);
          if (null !== tag) return tag;
          node = node.sibling;
        }
        return null;
      }
      function getIteratorFn(maybeIterable) {
        if (null === maybeIterable || "object" !== typeof maybeIterable)
          return null;
        maybeIterable = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable["@@iterator"];
        return "function" === typeof maybeIterable ? maybeIterable : null;
      }
      function getComponentNameFromType(type) {
        if (null == type) return null;
        if ("function" === typeof type)
          return type.$$typeof === REACT_CLIENT_REFERENCE ? null : type.displayName || type.name || null;
        if ("string" === typeof type) return type;
        switch (type) {
          case REACT_FRAGMENT_TYPE:
            return "Fragment";
          case REACT_PROFILER_TYPE:
            return "Profiler";
          case REACT_STRICT_MODE_TYPE:
            return "StrictMode";
          case REACT_SUSPENSE_TYPE:
            return "Suspense";
          case REACT_SUSPENSE_LIST_TYPE:
            return "SuspenseList";
          case REACT_ACTIVITY_TYPE:
            return "Activity";
        }
        if ("object" === typeof type)
          switch ("number" === typeof type.tag && console.error(
            "Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."
          ), type.$$typeof) {
            case REACT_PORTAL_TYPE:
              return "Portal";
            case REACT_CONTEXT_TYPE:
              return type.displayName || "Context";
            case REACT_CONSUMER_TYPE:
              return (type._context.displayName || "Context") + ".Consumer";
            case REACT_FORWARD_REF_TYPE:
              var innerType = type.render;
              type = type.displayName;
              type || (type = innerType.displayName || innerType.name || "", type = "" !== type ? "ForwardRef(" + type + ")" : "ForwardRef");
              return type;
            case REACT_MEMO_TYPE:
              return innerType = type.displayName || null, null !== innerType ? innerType : getComponentNameFromType(type.type) || "Memo";
            case REACT_LAZY_TYPE:
              innerType = type._payload;
              type = type._init;
              try {
                return getComponentNameFromType(type(innerType));
              } catch (x5) {
              }
          }
        return null;
      }
      function getComponentNameFromOwner(owner) {
        return "number" === typeof owner.tag ? getComponentNameFromFiber(owner) : "string" === typeof owner.name ? owner.name : null;
      }
      function getComponentNameFromFiber(fiber) {
        var type = fiber.type;
        switch (fiber.tag) {
          case 31:
            return "Activity";
          case 24:
            return "Cache";
          case 9:
            return (type._context.displayName || "Context") + ".Consumer";
          case 10:
            return type.displayName || "Context";
          case 18:
            return "DehydratedFragment";
          case 11:
            return fiber = type.render, fiber = fiber.displayName || fiber.name || "", type.displayName || ("" !== fiber ? "ForwardRef(" + fiber + ")" : "ForwardRef");
          case 7:
            return "Fragment";
          case 26:
          case 27:
          case 5:
            return type;
          case 4:
            return "Portal";
          case 3:
            return "Root";
          case 6:
            return "Text";
          case 16:
            return getComponentNameFromType(type);
          case 8:
            return type === REACT_STRICT_MODE_TYPE ? "StrictMode" : "Mode";
          case 22:
            return "Offscreen";
          case 12:
            return "Profiler";
          case 21:
            return "Scope";
          case 13:
            return "Suspense";
          case 19:
            return "SuspenseList";
          case 25:
            return "TracingMarker";
          case 1:
          case 0:
          case 14:
          case 15:
            if ("function" === typeof type)
              return type.displayName || type.name || null;
            if ("string" === typeof type) return type;
            break;
          case 29:
            type = fiber._debugInfo;
            if (null != type) {
              for (var i = type.length - 1; 0 <= i; i--)
                if ("string" === typeof type[i].name) return type[i].name;
            }
            if (null !== fiber.return)
              return getComponentNameFromFiber(fiber.return);
        }
        return null;
      }
      function createCursor(defaultValue) {
        return { current: defaultValue };
      }
      function pop(cursor, fiber) {
        0 > index$jscomp$0 ? console.error("Unexpected pop.") : (fiber !== fiberStack[index$jscomp$0] && console.error("Unexpected Fiber popped."), cursor.current = valueStack[index$jscomp$0], valueStack[index$jscomp$0] = null, fiberStack[index$jscomp$0] = null, index$jscomp$0--);
      }
      function push(cursor, value, fiber) {
        index$jscomp$0++;
        valueStack[index$jscomp$0] = cursor.current;
        fiberStack[index$jscomp$0] = fiber;
        cursor.current = value;
      }
      function requiredContext(c) {
        null === c && console.error(
          "Expected host context to exist. This error is likely caused by a bug in React. Please file an issue."
        );
        return c;
      }
      function pushHostContainer(fiber, nextRootInstance) {
        push(rootInstanceStackCursor, nextRootInstance, fiber);
        push(contextFiberStackCursor, fiber, fiber);
        push(contextStackCursor, null, fiber);
        var nextRootContext = nextRootInstance.nodeType;
        switch (nextRootContext) {
          case 9:
          case 11:
            nextRootContext = 9 === nextRootContext ? "#document" : "#fragment";
            nextRootInstance = (nextRootInstance = nextRootInstance.documentElement) ? (nextRootInstance = nextRootInstance.namespaceURI) ? getOwnHostContext(nextRootInstance) : HostContextNamespaceNone : HostContextNamespaceNone;
            break;
          default:
            if (nextRootContext = nextRootInstance.tagName, nextRootInstance = nextRootInstance.namespaceURI)
              nextRootInstance = getOwnHostContext(nextRootInstance), nextRootInstance = getChildHostContextProd(
                nextRootInstance,
                nextRootContext
              );
            else
              switch (nextRootContext) {
                case "svg":
                  nextRootInstance = HostContextNamespaceSvg;
                  break;
                case "math":
                  nextRootInstance = HostContextNamespaceMath;
                  break;
                default:
                  nextRootInstance = HostContextNamespaceNone;
              }
        }
        nextRootContext = nextRootContext.toLowerCase();
        nextRootContext = updatedAncestorInfoDev(null, nextRootContext);
        nextRootContext = {
          context: nextRootInstance,
          ancestorInfo: nextRootContext
        };
        pop(contextStackCursor, fiber);
        push(contextStackCursor, nextRootContext, fiber);
      }
      function popHostContainer(fiber) {
        pop(contextStackCursor, fiber);
        pop(contextFiberStackCursor, fiber);
        pop(rootInstanceStackCursor, fiber);
      }
      function getHostContext() {
        return requiredContext(contextStackCursor.current);
      }
      function pushHostContext(fiber) {
        null !== fiber.memoizedState && push(hostTransitionProviderCursor, fiber, fiber);
        var context = requiredContext(contextStackCursor.current);
        var type = fiber.type;
        var nextContext = getChildHostContextProd(context.context, type);
        type = updatedAncestorInfoDev(context.ancestorInfo, type);
        nextContext = { context: nextContext, ancestorInfo: type };
        context !== nextContext && (push(contextFiberStackCursor, fiber, fiber), push(contextStackCursor, nextContext, fiber));
      }
      function popHostContext(fiber) {
        contextFiberStackCursor.current === fiber && (pop(contextStackCursor, fiber), pop(contextFiberStackCursor, fiber));
        hostTransitionProviderCursor.current === fiber && (pop(hostTransitionProviderCursor, fiber), HostTransitionContext._currentValue = NotPendingTransition);
      }
      function disabledLog() {
      }
      function disableLogs() {
        if (0 === disabledDepth) {
          prevLog = console.log;
          prevInfo = console.info;
          prevWarn = console.warn;
          prevError = console.error;
          prevGroup = console.group;
          prevGroupCollapsed = console.groupCollapsed;
          prevGroupEnd = console.groupEnd;
          var props = {
            configurable: true,
            enumerable: true,
            value: disabledLog,
            writable: true
          };
          Object.defineProperties(console, {
            info: props,
            log: props,
            warn: props,
            error: props,
            group: props,
            groupCollapsed: props,
            groupEnd: props
          });
        }
        disabledDepth++;
      }
      function reenableLogs() {
        disabledDepth--;
        if (0 === disabledDepth) {
          var props = { configurable: true, enumerable: true, writable: true };
          Object.defineProperties(console, {
            log: assign({}, props, { value: prevLog }),
            info: assign({}, props, { value: prevInfo }),
            warn: assign({}, props, { value: prevWarn }),
            error: assign({}, props, { value: prevError }),
            group: assign({}, props, { value: prevGroup }),
            groupCollapsed: assign({}, props, { value: prevGroupCollapsed }),
            groupEnd: assign({}, props, { value: prevGroupEnd })
          });
        }
        0 > disabledDepth && console.error(
          "disabledDepth fell below zero. This is a bug in React. Please file an issue."
        );
      }
      function formatOwnerStack(error) {
        var prevPrepareStackTrace = Error.prepareStackTrace;
        Error.prepareStackTrace = void 0;
        error = error.stack;
        Error.prepareStackTrace = prevPrepareStackTrace;
        error.startsWith("Error: react-stack-top-frame\n") && (error = error.slice(29));
        prevPrepareStackTrace = error.indexOf("\n");
        -1 !== prevPrepareStackTrace && (error = error.slice(prevPrepareStackTrace + 1));
        prevPrepareStackTrace = error.indexOf("react_stack_bottom_frame");
        -1 !== prevPrepareStackTrace && (prevPrepareStackTrace = error.lastIndexOf(
          "\n",
          prevPrepareStackTrace
        ));
        if (-1 !== prevPrepareStackTrace)
          error = error.slice(0, prevPrepareStackTrace);
        else return "";
        return error;
      }
      function describeBuiltInComponentFrame(name) {
        if (void 0 === prefix)
          try {
            throw Error();
          } catch (x5) {
            var match = x5.stack.trim().match(/\n( *(at )?)/);
            prefix = match && match[1] || "";
            suffix = -1 < x5.stack.indexOf("\n    at") ? " (<anonymous>)" : -1 < x5.stack.indexOf("@") ? "@unknown:0:0" : "";
          }
        return "\n" + prefix + name + suffix;
      }
      function describeNativeComponentFrame(fn, construct) {
        if (!fn || reentry) return "";
        var frame = componentFrameCache.get(fn);
        if (void 0 !== frame) return frame;
        reentry = true;
        frame = Error.prepareStackTrace;
        Error.prepareStackTrace = void 0;
        var previousDispatcher2 = null;
        previousDispatcher2 = ReactSharedInternals.H;
        ReactSharedInternals.H = null;
        disableLogs();
        try {
          var RunInRootFrame = {
            DetermineComponentFrameRoot: function() {
              try {
                if (construct) {
                  var Fake = function() {
                    throw Error();
                  };
                  Object.defineProperty(Fake.prototype, "props", {
                    set: function() {
                      throw Error();
                    }
                  });
                  if ("object" === typeof Reflect && Reflect.construct) {
                    try {
                      Reflect.construct(Fake, []);
                    } catch (x5) {
                      var control = x5;
                    }
                    Reflect.construct(fn, [], Fake);
                  } else {
                    try {
                      Fake.call();
                    } catch (x$0) {
                      control = x$0;
                    }
                    fn.call(Fake.prototype);
                  }
                } else {
                  try {
                    throw Error();
                  } catch (x$1) {
                    control = x$1;
                  }
                  (Fake = fn()) && "function" === typeof Fake.catch && Fake.catch(function() {
                  });
                }
              } catch (sample) {
                if (sample && control && "string" === typeof sample.stack)
                  return [sample.stack, control.stack];
              }
              return [null, null];
            }
          };
          RunInRootFrame.DetermineComponentFrameRoot.displayName = "DetermineComponentFrameRoot";
          var namePropDescriptor = Object.getOwnPropertyDescriptor(
            RunInRootFrame.DetermineComponentFrameRoot,
            "name"
          );
          namePropDescriptor && namePropDescriptor.configurable && Object.defineProperty(
            RunInRootFrame.DetermineComponentFrameRoot,
            "name",
            { value: "DetermineComponentFrameRoot" }
          );
          var _RunInRootFrame$Deter = RunInRootFrame.DetermineComponentFrameRoot(), sampleStack = _RunInRootFrame$Deter[0], controlStack = _RunInRootFrame$Deter[1];
          if (sampleStack && controlStack) {
            var sampleLines = sampleStack.split("\n"), controlLines = controlStack.split("\n");
            for (_RunInRootFrame$Deter = namePropDescriptor = 0; namePropDescriptor < sampleLines.length && !sampleLines[namePropDescriptor].includes(
              "DetermineComponentFrameRoot"
            ); )
              namePropDescriptor++;
            for (; _RunInRootFrame$Deter < controlLines.length && !controlLines[_RunInRootFrame$Deter].includes(
              "DetermineComponentFrameRoot"
            ); )
              _RunInRootFrame$Deter++;
            if (namePropDescriptor === sampleLines.length || _RunInRootFrame$Deter === controlLines.length)
              for (namePropDescriptor = sampleLines.length - 1, _RunInRootFrame$Deter = controlLines.length - 1; 1 <= namePropDescriptor && 0 <= _RunInRootFrame$Deter && sampleLines[namePropDescriptor] !== controlLines[_RunInRootFrame$Deter]; )
                _RunInRootFrame$Deter--;
            for (; 1 <= namePropDescriptor && 0 <= _RunInRootFrame$Deter; namePropDescriptor--, _RunInRootFrame$Deter--)
              if (sampleLines[namePropDescriptor] !== controlLines[_RunInRootFrame$Deter]) {
                if (1 !== namePropDescriptor || 1 !== _RunInRootFrame$Deter) {
                  do
                    if (namePropDescriptor--, _RunInRootFrame$Deter--, 0 > _RunInRootFrame$Deter || sampleLines[namePropDescriptor] !== controlLines[_RunInRootFrame$Deter]) {
                      var _frame = "\n" + sampleLines[namePropDescriptor].replace(
                        " at new ",
                        " at "
                      );
                      fn.displayName && _frame.includes("<anonymous>") && (_frame = _frame.replace("<anonymous>", fn.displayName));
                      "function" === typeof fn && componentFrameCache.set(fn, _frame);
                      return _frame;
                    }
                  while (1 <= namePropDescriptor && 0 <= _RunInRootFrame$Deter);
                }
                break;
              }
          }
        } finally {
          reentry = false, ReactSharedInternals.H = previousDispatcher2, reenableLogs(), Error.prepareStackTrace = frame;
        }
        sampleLines = (sampleLines = fn ? fn.displayName || fn.name : "") ? describeBuiltInComponentFrame(sampleLines) : "";
        "function" === typeof fn && componentFrameCache.set(fn, sampleLines);
        return sampleLines;
      }
      function describeFiber(fiber, childFiber) {
        switch (fiber.tag) {
          case 26:
          case 27:
          case 5:
            return describeBuiltInComponentFrame(fiber.type);
          case 16:
            return describeBuiltInComponentFrame("Lazy");
          case 13:
            return fiber.child !== childFiber && null !== childFiber ? describeBuiltInComponentFrame("Suspense Fallback") : describeBuiltInComponentFrame("Suspense");
          case 19:
            return describeBuiltInComponentFrame("SuspenseList");
          case 0:
          case 15:
            return describeNativeComponentFrame(fiber.type, false);
          case 11:
            return describeNativeComponentFrame(fiber.type.render, false);
          case 1:
            return describeNativeComponentFrame(fiber.type, true);
          case 31:
            return describeBuiltInComponentFrame("Activity");
          default:
            return "";
        }
      }
      function getStackByFiberInDevAndProd(workInProgress2) {
        try {
          var info = "", previous = null;
          do {
            info += describeFiber(workInProgress2, previous);
            var debugInfo = workInProgress2._debugInfo;
            if (debugInfo)
              for (var i = debugInfo.length - 1; 0 <= i; i--) {
                var entry = debugInfo[i];
                if ("string" === typeof entry.name) {
                  var JSCompiler_temp_const = info;
                  a: {
                    var name = entry.name, env = entry.env, location = entry.debugLocation;
                    if (null != location) {
                      var childStack = formatOwnerStack(location), idx = childStack.lastIndexOf("\n"), lastLine = -1 === idx ? childStack : childStack.slice(idx + 1);
                      if (-1 !== lastLine.indexOf(name)) {
                        var JSCompiler_inline_result = "\n" + lastLine;
                        break a;
                      }
                    }
                    JSCompiler_inline_result = describeBuiltInComponentFrame(
                      name + (env ? " [" + env + "]" : "")
                    );
                  }
                  info = JSCompiler_temp_const + JSCompiler_inline_result;
                }
              }
            previous = workInProgress2;
            workInProgress2 = workInProgress2.return;
          } while (workInProgress2);
          return info;
        } catch (x5) {
          return "\nError generating stack: " + x5.message + "\n" + x5.stack;
        }
      }
      function describeFunctionComponentFrameWithoutLineNumber(fn) {
        return (fn = fn ? fn.displayName || fn.name : "") ? describeBuiltInComponentFrame(fn) : "";
      }
      function getCurrentFiberOwnerNameInDevOrNull() {
        if (null === current) return null;
        var owner = current._debugOwner;
        return null != owner ? getComponentNameFromOwner(owner) : null;
      }
      function getCurrentFiberStackInDev() {
        if (null === current) return "";
        var workInProgress2 = current;
        try {
          var info = "";
          6 === workInProgress2.tag && (workInProgress2 = workInProgress2.return);
          switch (workInProgress2.tag) {
            case 26:
            case 27:
            case 5:
              info += describeBuiltInComponentFrame(workInProgress2.type);
              break;
            case 13:
              info += describeBuiltInComponentFrame("Suspense");
              break;
            case 19:
              info += describeBuiltInComponentFrame("SuspenseList");
              break;
            case 31:
              info += describeBuiltInComponentFrame("Activity");
              break;
            case 30:
            case 0:
            case 15:
            case 1:
              workInProgress2._debugOwner || "" !== info || (info += describeFunctionComponentFrameWithoutLineNumber(
                workInProgress2.type
              ));
              break;
            case 11:
              workInProgress2._debugOwner || "" !== info || (info += describeFunctionComponentFrameWithoutLineNumber(
                workInProgress2.type.render
              ));
          }
          for (; workInProgress2; )
            if ("number" === typeof workInProgress2.tag) {
              var fiber = workInProgress2;
              workInProgress2 = fiber._debugOwner;
              var debugStack = fiber._debugStack;
              if (workInProgress2 && debugStack) {
                var formattedStack = formatOwnerStack(debugStack);
                "" !== formattedStack && (info += "\n" + formattedStack);
              }
            } else if (null != workInProgress2.debugStack) {
              var ownerStack = workInProgress2.debugStack;
              (workInProgress2 = workInProgress2.owner) && ownerStack && (info += "\n" + formatOwnerStack(ownerStack));
            } else break;
          var JSCompiler_inline_result = info;
        } catch (x5) {
          JSCompiler_inline_result = "\nError generating stack: " + x5.message + "\n" + x5.stack;
        }
        return JSCompiler_inline_result;
      }
      function runWithFiberInDEV(fiber, callback, arg0, arg1, arg2, arg3, arg4) {
        var previousFiber = current;
        setCurrentFiber(fiber);
        try {
          return null !== fiber && fiber._debugTask ? fiber._debugTask.run(
            callback.bind(null, arg0, arg1, arg2, arg3, arg4)
          ) : callback(arg0, arg1, arg2, arg3, arg4);
        } finally {
          setCurrentFiber(previousFiber);
        }
        throw Error(
          "runWithFiberInDEV should never be called in production. This is a bug in React."
        );
      }
      function setCurrentFiber(fiber) {
        ReactSharedInternals.getCurrentStack = null === fiber ? null : getCurrentFiberStackInDev;
        isRendering = false;
        current = fiber;
      }
      function typeName(value) {
        return "function" === typeof Symbol && Symbol.toStringTag && value[Symbol.toStringTag] || value.constructor.name || "Object";
      }
      function willCoercionThrow(value) {
        try {
          return testStringCoercion(value), false;
        } catch (e) {
          return true;
        }
      }
      function testStringCoercion(value) {
        return "" + value;
      }
      function checkAttributeStringCoercion(value, attributeName) {
        if (willCoercionThrow(value))
          return console.error(
            "The provided `%s` attribute is an unsupported type %s. This value must be coerced to a string before using it here.",
            attributeName,
            typeName(value)
          ), testStringCoercion(value);
      }
      function checkCSSPropertyStringCoercion(value, propName) {
        if (willCoercionThrow(value))
          return console.error(
            "The provided `%s` CSS property is an unsupported type %s. This value must be coerced to a string before using it here.",
            propName,
            typeName(value)
          ), testStringCoercion(value);
      }
      function checkFormFieldValueStringCoercion(value) {
        if (willCoercionThrow(value))
          return console.error(
            "Form field values (value, checked, defaultValue, or defaultChecked props) must be strings, not %s. This value must be coerced to a string before using it here.",
            typeName(value)
          ), testStringCoercion(value);
      }
      function injectInternals(internals) {
        if ("undefined" === typeof __REACT_DEVTOOLS_GLOBAL_HOOK__) return false;
        var hook = __REACT_DEVTOOLS_GLOBAL_HOOK__;
        if (hook.isDisabled) return true;
        if (!hook.supportsFiber)
          return console.error(
            "The installed version of React DevTools is too old and will not work with the current version of React. Please update React DevTools. https://react.dev/link/react-devtools"
          ), true;
        try {
          rendererID = hook.inject(internals), injectedHook = hook;
        } catch (err) {
          console.error("React instrumentation encountered an error: %o.", err);
        }
        return hook.checkDCE ? true : false;
      }
      function setIsStrictModeForDevtools(newIsStrictMode) {
        "function" === typeof log$1 && unstable_setDisableYieldValue(newIsStrictMode);
        if (injectedHook && "function" === typeof injectedHook.setStrictMode)
          try {
            injectedHook.setStrictMode(rendererID, newIsStrictMode);
          } catch (err) {
            hasLoggedError || (hasLoggedError = true, console.error(
              "React instrumentation encountered an error: %o",
              err
            ));
          }
      }
      function clz32Fallback(x5) {
        x5 >>>= 0;
        return 0 === x5 ? 32 : 31 - (log(x5) / LN2 | 0) | 0;
      }
      function getHighestPriorityLanes(lanes) {
        var pendingSyncLanes = lanes & 42;
        if (0 !== pendingSyncLanes) return pendingSyncLanes;
        switch (lanes & -lanes) {
          case 1:
            return 1;
          case 2:
            return 2;
          case 4:
            return 4;
          case 8:
            return 8;
          case 16:
            return 16;
          case 32:
            return 32;
          case 64:
            return 64;
          case 128:
            return 128;
          case 256:
          case 512:
          case 1024:
          case 2048:
          case 4096:
          case 8192:
          case 16384:
          case 32768:
          case 65536:
          case 131072:
            return lanes & 261888;
          case 262144:
          case 524288:
          case 1048576:
          case 2097152:
            return lanes & 3932160;
          case 4194304:
          case 8388608:
          case 16777216:
          case 33554432:
            return lanes & 62914560;
          case 67108864:
            return 67108864;
          case 134217728:
            return 134217728;
          case 268435456:
            return 268435456;
          case 536870912:
            return 536870912;
          case 1073741824:
            return 0;
          default:
            return console.error(
              "Should have found matching lanes. This is a bug in React."
            ), lanes;
        }
      }
      function getNextLanes(root2, wipLanes, rootHasPendingCommit) {
        var pendingLanes = root2.pendingLanes;
        if (0 === pendingLanes) return 0;
        var nextLanes = 0, suspendedLanes = root2.suspendedLanes, pingedLanes = root2.pingedLanes;
        root2 = root2.warmLanes;
        var nonIdlePendingLanes = pendingLanes & 134217727;
        0 !== nonIdlePendingLanes ? (pendingLanes = nonIdlePendingLanes & ~suspendedLanes, 0 !== pendingLanes ? nextLanes = getHighestPriorityLanes(pendingLanes) : (pingedLanes &= nonIdlePendingLanes, 0 !== pingedLanes ? nextLanes = getHighestPriorityLanes(pingedLanes) : rootHasPendingCommit || (rootHasPendingCommit = nonIdlePendingLanes & ~root2, 0 !== rootHasPendingCommit && (nextLanes = getHighestPriorityLanes(rootHasPendingCommit))))) : (nonIdlePendingLanes = pendingLanes & ~suspendedLanes, 0 !== nonIdlePendingLanes ? nextLanes = getHighestPriorityLanes(nonIdlePendingLanes) : 0 !== pingedLanes ? nextLanes = getHighestPriorityLanes(pingedLanes) : rootHasPendingCommit || (rootHasPendingCommit = pendingLanes & ~root2, 0 !== rootHasPendingCommit && (nextLanes = getHighestPriorityLanes(rootHasPendingCommit))));
        return 0 === nextLanes ? 0 : 0 !== wipLanes && wipLanes !== nextLanes && 0 === (wipLanes & suspendedLanes) && (suspendedLanes = nextLanes & -nextLanes, rootHasPendingCommit = wipLanes & -wipLanes, suspendedLanes >= rootHasPendingCommit || 32 === suspendedLanes && 0 !== (rootHasPendingCommit & 4194048)) ? wipLanes : nextLanes;
      }
      function checkIfRootIsPrerendering(root2, renderLanes2) {
        return 0 === (root2.pendingLanes & ~(root2.suspendedLanes & ~root2.pingedLanes) & renderLanes2);
      }
      function computeExpirationTime(lane, currentTime) {
        switch (lane) {
          case 1:
          case 2:
          case 4:
          case 8:
          case 64:
            return currentTime + 250;
          case 16:
          case 32:
          case 128:
          case 256:
          case 512:
          case 1024:
          case 2048:
          case 4096:
          case 8192:
          case 16384:
          case 32768:
          case 65536:
          case 131072:
          case 262144:
          case 524288:
          case 1048576:
          case 2097152:
            return currentTime + 5e3;
          case 4194304:
          case 8388608:
          case 16777216:
          case 33554432:
            return -1;
          case 67108864:
          case 134217728:
          case 268435456:
          case 536870912:
          case 1073741824:
            return -1;
          default:
            return console.error(
              "Should have found matching lanes. This is a bug in React."
            ), -1;
        }
      }
      function claimNextRetryLane() {
        var lane = nextRetryLane;
        nextRetryLane <<= 1;
        0 === (nextRetryLane & 62914560) && (nextRetryLane = 4194304);
        return lane;
      }
      function createLaneMap(initial) {
        for (var laneMap = [], i = 0; 31 > i; i++) laneMap.push(initial);
        return laneMap;
      }
      function markRootUpdated$1(root2, updateLane) {
        root2.pendingLanes |= updateLane;
        268435456 !== updateLane && (root2.suspendedLanes = 0, root2.pingedLanes = 0, root2.warmLanes = 0);
      }
      function markRootFinished(root2, finishedLanes, remainingLanes, spawnedLane, updatedLanes, suspendedRetryLanes) {
        var previouslyPendingLanes = root2.pendingLanes;
        root2.pendingLanes = remainingLanes;
        root2.suspendedLanes = 0;
        root2.pingedLanes = 0;
        root2.warmLanes = 0;
        root2.expiredLanes &= remainingLanes;
        root2.entangledLanes &= remainingLanes;
        root2.errorRecoveryDisabledLanes &= remainingLanes;
        root2.shellSuspendCounter = 0;
        var entanglements = root2.entanglements, expirationTimes = root2.expirationTimes, hiddenUpdates = root2.hiddenUpdates;
        for (remainingLanes = previouslyPendingLanes & ~remainingLanes; 0 < remainingLanes; ) {
          var index = 31 - clz32(remainingLanes), lane = 1 << index;
          entanglements[index] = 0;
          expirationTimes[index] = -1;
          var hiddenUpdatesForLane = hiddenUpdates[index];
          if (null !== hiddenUpdatesForLane)
            for (hiddenUpdates[index] = null, index = 0; index < hiddenUpdatesForLane.length; index++) {
              var update = hiddenUpdatesForLane[index];
              null !== update && (update.lane &= -536870913);
            }
          remainingLanes &= ~lane;
        }
        0 !== spawnedLane && markSpawnedDeferredLane(root2, spawnedLane, 0);
        0 !== suspendedRetryLanes && 0 === updatedLanes && 0 !== root2.tag && (root2.suspendedLanes |= suspendedRetryLanes & ~(previouslyPendingLanes & ~finishedLanes));
      }
      function markSpawnedDeferredLane(root2, spawnedLane, entangledLanes) {
        root2.pendingLanes |= spawnedLane;
        root2.suspendedLanes &= ~spawnedLane;
        var spawnedLaneIndex = 31 - clz32(spawnedLane);
        root2.entangledLanes |= spawnedLane;
        root2.entanglements[spawnedLaneIndex] = root2.entanglements[spawnedLaneIndex] | 1073741824 | entangledLanes & 261930;
      }
      function markRootEntangled(root2, entangledLanes) {
        var rootEntangledLanes = root2.entangledLanes |= entangledLanes;
        for (root2 = root2.entanglements; rootEntangledLanes; ) {
          var index = 31 - clz32(rootEntangledLanes), lane = 1 << index;
          lane & entangledLanes | root2[index] & entangledLanes && (root2[index] |= entangledLanes);
          rootEntangledLanes &= ~lane;
        }
      }
      function getBumpedLaneForHydration(root2, renderLanes2) {
        var renderLane = renderLanes2 & -renderLanes2;
        renderLane = 0 !== (renderLane & 42) ? 1 : getBumpedLaneForHydrationByLane(renderLane);
        return 0 !== (renderLane & (root2.suspendedLanes | renderLanes2)) ? 0 : renderLane;
      }
      function getBumpedLaneForHydrationByLane(lane) {
        switch (lane) {
          case 2:
            lane = 1;
            break;
          case 8:
            lane = 4;
            break;
          case 32:
            lane = 16;
            break;
          case 256:
          case 512:
          case 1024:
          case 2048:
          case 4096:
          case 8192:
          case 16384:
          case 32768:
          case 65536:
          case 131072:
          case 262144:
          case 524288:
          case 1048576:
          case 2097152:
          case 4194304:
          case 8388608:
          case 16777216:
          case 33554432:
            lane = 128;
            break;
          case 268435456:
            lane = 134217728;
            break;
          default:
            lane = 0;
        }
        return lane;
      }
      function addFiberToLanesMap(root2, fiber, lanes) {
        if (isDevToolsPresent)
          for (root2 = root2.pendingUpdatersLaneMap; 0 < lanes; ) {
            var index = 31 - clz32(lanes), lane = 1 << index;
            root2[index].add(fiber);
            lanes &= ~lane;
          }
      }
      function movePendingFibersToMemoized(root2, lanes) {
        if (isDevToolsPresent)
          for (var pendingUpdatersLaneMap = root2.pendingUpdatersLaneMap, memoizedUpdaters = root2.memoizedUpdaters; 0 < lanes; ) {
            var index = 31 - clz32(lanes);
            root2 = 1 << index;
            index = pendingUpdatersLaneMap[index];
            0 < index.size && (index.forEach(function(fiber) {
              var alternate = fiber.alternate;
              null !== alternate && memoizedUpdaters.has(alternate) || memoizedUpdaters.add(fiber);
            }), index.clear());
            lanes &= ~root2;
          }
      }
      function lanesToEventPriority(lanes) {
        lanes &= -lanes;
        return 0 !== DiscreteEventPriority && DiscreteEventPriority < lanes ? 0 !== ContinuousEventPriority && ContinuousEventPriority < lanes ? 0 !== (lanes & 134217727) ? DefaultEventPriority : IdleEventPriority : ContinuousEventPriority : DiscreteEventPriority;
      }
      function resolveUpdatePriority() {
        var updatePriority = ReactDOMSharedInternals.p;
        if (0 !== updatePriority) return updatePriority;
        updatePriority = window.event;
        return void 0 === updatePriority ? DefaultEventPriority : getEventPriority(updatePriority.type);
      }
      function runWithPriority(priority, fn) {
        var previousPriority = ReactDOMSharedInternals.p;
        try {
          return ReactDOMSharedInternals.p = priority, fn();
        } finally {
          ReactDOMSharedInternals.p = previousPriority;
        }
      }
      function detachDeletedInstance(node) {
        delete node[internalInstanceKey];
        delete node[internalPropsKey];
        delete node[internalEventHandlersKey];
        delete node[internalEventHandlerListenersKey];
        delete node[internalEventHandlesSetKey];
      }
      function getClosestInstanceFromNode(targetNode) {
        var targetInst = targetNode[internalInstanceKey];
        if (targetInst) return targetInst;
        for (var parentNode2 = targetNode.parentNode; parentNode2; ) {
          if (targetInst = parentNode2[internalContainerInstanceKey] || parentNode2[internalInstanceKey]) {
            parentNode2 = targetInst.alternate;
            if (null !== targetInst.child || null !== parentNode2 && null !== parentNode2.child)
              for (targetNode = getParentHydrationBoundary(targetNode); null !== targetNode; ) {
                if (parentNode2 = targetNode[internalInstanceKey])
                  return parentNode2;
                targetNode = getParentHydrationBoundary(targetNode);
              }
            return targetInst;
          }
          targetNode = parentNode2;
          parentNode2 = targetNode.parentNode;
        }
        return null;
      }
      function getInstanceFromNode(node) {
        if (node = node[internalInstanceKey] || node[internalContainerInstanceKey]) {
          var tag = node.tag;
          if (5 === tag || 6 === tag || 13 === tag || 31 === tag || 26 === tag || 27 === tag || 3 === tag)
            return node;
        }
        return null;
      }
      function getNodeFromInstance(inst) {
        var tag = inst.tag;
        if (5 === tag || 26 === tag || 27 === tag || 6 === tag)
          return inst.stateNode;
        throw Error("getNodeFromInstance: Invalid argument.");
      }
      function getResourcesFromRoot(root2) {
        var resources = root2[internalRootNodeResourcesKey];
        resources || (resources = root2[internalRootNodeResourcesKey] = { hoistableStyles: /* @__PURE__ */ new Map(), hoistableScripts: /* @__PURE__ */ new Map() });
        return resources;
      }
      function markNodeAsHoistable(node) {
        node[internalHoistableMarker] = true;
      }
      function registerTwoPhaseEvent(registrationName, dependencies) {
        registerDirectEvent(registrationName, dependencies);
        registerDirectEvent(registrationName + "Capture", dependencies);
      }
      function registerDirectEvent(registrationName, dependencies) {
        registrationNameDependencies[registrationName] && console.error(
          "EventRegistry: More than one plugin attempted to publish the same registration name, `%s`.",
          registrationName
        );
        registrationNameDependencies[registrationName] = dependencies;
        var lowerCasedName = registrationName.toLowerCase();
        possibleRegistrationNames[lowerCasedName] = registrationName;
        "onDoubleClick" === registrationName && (possibleRegistrationNames.ondblclick = registrationName);
        for (registrationName = 0; registrationName < dependencies.length; registrationName++)
          allNativeEvents.add(dependencies[registrationName]);
      }
      function checkControlledValueProps(tagName, props) {
        hasReadOnlyValue[props.type] || props.onChange || props.onInput || props.readOnly || props.disabled || null == props.value || ("select" === tagName ? console.error(
          "You provided a `value` prop to a form field without an `onChange` handler. This will render a read-only field. If the field should be mutable use `defaultValue`. Otherwise, set `onChange`."
        ) : console.error(
          "You provided a `value` prop to a form field without an `onChange` handler. This will render a read-only field. If the field should be mutable use `defaultValue`. Otherwise, set either `onChange` or `readOnly`."
        ));
        props.onChange || props.readOnly || props.disabled || null == props.checked || console.error(
          "You provided a `checked` prop to a form field without an `onChange` handler. This will render a read-only field. If the field should be mutable use `defaultChecked`. Otherwise, set either `onChange` or `readOnly`."
        );
      }
      function isAttributeNameSafe(attributeName) {
        if (hasOwnProperty2.call(validatedAttributeNameCache, attributeName))
          return true;
        if (hasOwnProperty2.call(illegalAttributeNameCache, attributeName))
          return false;
        if (VALID_ATTRIBUTE_NAME_REGEX.test(attributeName))
          return validatedAttributeNameCache[attributeName] = true;
        illegalAttributeNameCache[attributeName] = true;
        console.error("Invalid attribute name: `%s`", attributeName);
        return false;
      }
      function getValueForAttributeOnCustomComponent(node, name, expected) {
        if (isAttributeNameSafe(name)) {
          if (!node.hasAttribute(name)) {
            switch (typeof expected) {
              case "symbol":
              case "object":
                return expected;
              case "function":
                return expected;
              case "boolean":
                if (false === expected) return expected;
            }
            return void 0 === expected ? void 0 : null;
          }
          node = node.getAttribute(name);
          if ("" === node && true === expected) return true;
          checkAttributeStringCoercion(expected, name);
          return node === "" + expected ? expected : node;
        }
      }
      function setValueForAttribute(node, name, value) {
        if (isAttributeNameSafe(name))
          if (null === value) node.removeAttribute(name);
          else {
            switch (typeof value) {
              case "undefined":
              case "function":
              case "symbol":
                node.removeAttribute(name);
                return;
              case "boolean":
                var prefix2 = name.toLowerCase().slice(0, 5);
                if ("data-" !== prefix2 && "aria-" !== prefix2) {
                  node.removeAttribute(name);
                  return;
                }
            }
            checkAttributeStringCoercion(value, name);
            node.setAttribute(name, "" + value);
          }
      }
      function setValueForKnownAttribute(node, name, value) {
        if (null === value) node.removeAttribute(name);
        else {
          switch (typeof value) {
            case "undefined":
            case "function":
            case "symbol":
            case "boolean":
              node.removeAttribute(name);
              return;
          }
          checkAttributeStringCoercion(value, name);
          node.setAttribute(name, "" + value);
        }
      }
      function setValueForNamespacedAttribute(node, namespace, name, value) {
        if (null === value) node.removeAttribute(name);
        else {
          switch (typeof value) {
            case "undefined":
            case "function":
            case "symbol":
            case "boolean":
              node.removeAttribute(name);
              return;
          }
          checkAttributeStringCoercion(value, name);
          node.setAttributeNS(namespace, name, "" + value);
        }
      }
      function getToStringValue(value) {
        switch (typeof value) {
          case "bigint":
          case "boolean":
          case "number":
          case "string":
          case "undefined":
            return value;
          case "object":
            return checkFormFieldValueStringCoercion(value), value;
          default:
            return "";
        }
      }
      function isCheckable(elem) {
        var type = elem.type;
        return (elem = elem.nodeName) && "input" === elem.toLowerCase() && ("checkbox" === type || "radio" === type);
      }
      function trackValueOnNode(node, valueField, currentValue) {
        var descriptor = Object.getOwnPropertyDescriptor(
          node.constructor.prototype,
          valueField
        );
        if (!node.hasOwnProperty(valueField) && "undefined" !== typeof descriptor && "function" === typeof descriptor.get && "function" === typeof descriptor.set) {
          var get2 = descriptor.get, set = descriptor.set;
          Object.defineProperty(node, valueField, {
            configurable: true,
            get: function() {
              return get2.call(this);
            },
            set: function(value) {
              checkFormFieldValueStringCoercion(value);
              currentValue = "" + value;
              set.call(this, value);
            }
          });
          Object.defineProperty(node, valueField, {
            enumerable: descriptor.enumerable
          });
          return {
            getValue: function() {
              return currentValue;
            },
            setValue: function(value) {
              checkFormFieldValueStringCoercion(value);
              currentValue = "" + value;
            },
            stopTracking: function() {
              node._valueTracker = null;
              delete node[valueField];
            }
          };
        }
      }
      function track(node) {
        if (!node._valueTracker) {
          var valueField = isCheckable(node) ? "checked" : "value";
          node._valueTracker = trackValueOnNode(
            node,
            valueField,
            "" + node[valueField]
          );
        }
      }
      function updateValueIfChanged(node) {
        if (!node) return false;
        var tracker = node._valueTracker;
        if (!tracker) return true;
        var lastValue = tracker.getValue();
        var value = "";
        node && (value = isCheckable(node) ? node.checked ? "true" : "false" : node.value);
        node = value;
        return node !== lastValue ? (tracker.setValue(node), true) : false;
      }
      function getActiveElement(doc3) {
        doc3 = doc3 || ("undefined" !== typeof document ? document : void 0);
        if ("undefined" === typeof doc3) return null;
        try {
          return doc3.activeElement || doc3.body;
        } catch (e) {
          return doc3.body;
        }
      }
      function escapeSelectorAttributeValueInsideDoubleQuotes(value) {
        return value.replace(
          escapeSelectorAttributeValueInsideDoubleQuotesRegex,
          function(ch) {
            return "\\" + ch.charCodeAt(0).toString(16) + " ";
          }
        );
      }
      function validateInputProps(element, props) {
        void 0 === props.checked || void 0 === props.defaultChecked || didWarnCheckedDefaultChecked || (console.error(
          "%s contains an input of type %s with both checked and defaultChecked props. Input elements must be either controlled or uncontrolled (specify either the checked prop, or the defaultChecked prop, but not both). Decide between using a controlled or uncontrolled input element and remove one of these props. More info: https://react.dev/link/controlled-components",
          getCurrentFiberOwnerNameInDevOrNull() || "A component",
          props.type
        ), didWarnCheckedDefaultChecked = true);
        void 0 === props.value || void 0 === props.defaultValue || didWarnValueDefaultValue$1 || (console.error(
          "%s contains an input of type %s with both value and defaultValue props. Input elements must be either controlled or uncontrolled (specify either the value prop, or the defaultValue prop, but not both). Decide between using a controlled or uncontrolled input element and remove one of these props. More info: https://react.dev/link/controlled-components",
          getCurrentFiberOwnerNameInDevOrNull() || "A component",
          props.type
        ), didWarnValueDefaultValue$1 = true);
      }
      function updateInput(element, value, defaultValue, lastDefaultValue, checked, defaultChecked, type, name) {
        element.name = "";
        null != type && "function" !== typeof type && "symbol" !== typeof type && "boolean" !== typeof type ? (checkAttributeStringCoercion(type, "type"), element.type = type) : element.removeAttribute("type");
        if (null != value)
          if ("number" === type) {
            if (0 === value && "" === element.value || element.value != value)
              element.value = "" + getToStringValue(value);
          } else
            element.value !== "" + getToStringValue(value) && (element.value = "" + getToStringValue(value));
        else
          "submit" !== type && "reset" !== type || element.removeAttribute("value");
        null != value ? setDefaultValue(element, type, getToStringValue(value)) : null != defaultValue ? setDefaultValue(element, type, getToStringValue(defaultValue)) : null != lastDefaultValue && element.removeAttribute("value");
        null == checked && null != defaultChecked && (element.defaultChecked = !!defaultChecked);
        null != checked && (element.checked = checked && "function" !== typeof checked && "symbol" !== typeof checked);
        null != name && "function" !== typeof name && "symbol" !== typeof name && "boolean" !== typeof name ? (checkAttributeStringCoercion(name, "name"), element.name = "" + getToStringValue(name)) : element.removeAttribute("name");
      }
      function initInput2(element, value, defaultValue, checked, defaultChecked, type, name, isHydrating2) {
        null != type && "function" !== typeof type && "symbol" !== typeof type && "boolean" !== typeof type && (checkAttributeStringCoercion(type, "type"), element.type = type);
        if (null != value || null != defaultValue) {
          if (!("submit" !== type && "reset" !== type || void 0 !== value && null !== value)) {
            track(element);
            return;
          }
          defaultValue = null != defaultValue ? "" + getToStringValue(defaultValue) : "";
          value = null != value ? "" + getToStringValue(value) : defaultValue;
          isHydrating2 || value === element.value || (element.value = value);
          element.defaultValue = value;
        }
        checked = null != checked ? checked : defaultChecked;
        checked = "function" !== typeof checked && "symbol" !== typeof checked && !!checked;
        element.checked = isHydrating2 ? element.checked : !!checked;
        element.defaultChecked = !!checked;
        null != name && "function" !== typeof name && "symbol" !== typeof name && "boolean" !== typeof name && (checkAttributeStringCoercion(name, "name"), element.name = name);
        track(element);
      }
      function setDefaultValue(node, type, value) {
        "number" === type && getActiveElement(node.ownerDocument) === node || node.defaultValue === "" + value || (node.defaultValue = "" + value);
      }
      function validateOptionProps(element, props) {
        null == props.value && ("object" === typeof props.children && null !== props.children ? React7.Children.forEach(props.children, function(child) {
          null == child || "string" === typeof child || "number" === typeof child || "bigint" === typeof child || didWarnInvalidChild || (didWarnInvalidChild = true, console.error(
            "Cannot infer the option value of complex children. Pass a `value` prop or use a plain string as children to <option>."
          ));
        }) : null == props.dangerouslySetInnerHTML || didWarnInvalidInnerHTML || (didWarnInvalidInnerHTML = true, console.error(
          "Pass a `value` prop if you set dangerouslyInnerHTML so React knows which value should be selected."
        )));
        null == props.selected || didWarnSelectedSetOnOption || (console.error(
          "Use the `defaultValue` or `value` props on <select> instead of setting `selected` on <option>."
        ), didWarnSelectedSetOnOption = true);
      }
      function getDeclarationErrorAddendum() {
        var ownerName = getCurrentFiberOwnerNameInDevOrNull();
        return ownerName ? "\n\nCheck the render method of `" + ownerName + "`." : "";
      }
      function updateOptions(node, multiple, propValue, setDefaultSelected) {
        node = node.options;
        if (multiple) {
          multiple = {};
          for (var i = 0; i < propValue.length; i++)
            multiple["$" + propValue[i]] = true;
          for (propValue = 0; propValue < node.length; propValue++)
            i = multiple.hasOwnProperty("$" + node[propValue].value), node[propValue].selected !== i && (node[propValue].selected = i), i && setDefaultSelected && (node[propValue].defaultSelected = true);
        } else {
          propValue = "" + getToStringValue(propValue);
          multiple = null;
          for (i = 0; i < node.length; i++) {
            if (node[i].value === propValue) {
              node[i].selected = true;
              setDefaultSelected && (node[i].defaultSelected = true);
              return;
            }
            null !== multiple || node[i].disabled || (multiple = node[i]);
          }
          null !== multiple && (multiple.selected = true);
        }
      }
      function validateSelectProps(element, props) {
        for (element = 0; element < valuePropNames.length; element++) {
          var propName = valuePropNames[element];
          if (null != props[propName]) {
            var propNameIsArray = isArrayImpl(props[propName]);
            props.multiple && !propNameIsArray ? console.error(
              "The `%s` prop supplied to <select> must be an array if `multiple` is true.%s",
              propName,
              getDeclarationErrorAddendum()
            ) : !props.multiple && propNameIsArray && console.error(
              "The `%s` prop supplied to <select> must be a scalar value if `multiple` is false.%s",
              propName,
              getDeclarationErrorAddendum()
            );
          }
        }
        void 0 === props.value || void 0 === props.defaultValue || didWarnValueDefaultValue || (console.error(
          "Select elements must be either controlled or uncontrolled (specify either the value prop, or the defaultValue prop, but not both). Decide between using a controlled or uncontrolled select element and remove one of these props. More info: https://react.dev/link/controlled-components"
        ), didWarnValueDefaultValue = true);
      }
      function validateTextareaProps(element, props) {
        void 0 === props.value || void 0 === props.defaultValue || didWarnValDefaultVal || (console.error(
          "%s contains a textarea with both value and defaultValue props. Textarea elements must be either controlled or uncontrolled (specify either the value prop, or the defaultValue prop, but not both). Decide between using a controlled or uncontrolled textarea and remove one of these props. More info: https://react.dev/link/controlled-components",
          getCurrentFiberOwnerNameInDevOrNull() || "A component"
        ), didWarnValDefaultVal = true);
        null != props.children && null == props.value && console.error(
          "Use the `defaultValue` or `value` props instead of setting children on <textarea>."
        );
      }
      function updateTextarea(element, value, defaultValue) {
        if (null != value && (value = "" + getToStringValue(value), value !== element.value && (element.value = value), null == defaultValue)) {
          element.defaultValue !== value && (element.defaultValue = value);
          return;
        }
        element.defaultValue = null != defaultValue ? "" + getToStringValue(defaultValue) : "";
      }
      function initTextarea(element, value, defaultValue, children) {
        if (null == value) {
          if (null != children) {
            if (null != defaultValue)
              throw Error(
                "If you supply `defaultValue` on a <textarea>, do not pass children."
              );
            if (isArrayImpl(children)) {
              if (1 < children.length)
                throw Error("<textarea> can only have at most one child.");
              children = children[0];
            }
            defaultValue = children;
          }
          null == defaultValue && (defaultValue = "");
          value = defaultValue;
        }
        defaultValue = getToStringValue(value);
        element.defaultValue = defaultValue;
        children = element.textContent;
        children === defaultValue && "" !== children && null !== children && (element.value = children);
        track(element);
      }
      function findNotableNode(node, indent) {
        return void 0 === node.serverProps && 0 === node.serverTail.length && 1 === node.children.length && 3 < node.distanceFromLeaf && node.distanceFromLeaf > 15 - indent ? findNotableNode(node.children[0], indent) : node;
      }
      function indentation(indent) {
        return "  " + "  ".repeat(indent);
      }
      function added(indent) {
        return "+ " + "  ".repeat(indent);
      }
      function removed(indent) {
        return "- " + "  ".repeat(indent);
      }
      function describeFiberType(fiber) {
        switch (fiber.tag) {
          case 26:
          case 27:
          case 5:
            return fiber.type;
          case 16:
            return "Lazy";
          case 31:
            return "Activity";
          case 13:
            return "Suspense";
          case 19:
            return "SuspenseList";
          case 0:
          case 15:
            return fiber = fiber.type, fiber.displayName || fiber.name || null;
          case 11:
            return fiber = fiber.type.render, fiber.displayName || fiber.name || null;
          case 1:
            return fiber = fiber.type, fiber.displayName || fiber.name || null;
          default:
            return null;
        }
      }
      function describeTextNode(content, maxLength) {
        return needsEscaping.test(content) ? (content = JSON.stringify(content), content.length > maxLength - 2 ? 8 > maxLength ? '{"..."}' : "{" + content.slice(0, maxLength - 7) + '..."}' : "{" + content + "}") : content.length > maxLength ? 5 > maxLength ? '{"..."}' : content.slice(0, maxLength - 3) + "..." : content;
      }
      function describeTextDiff(clientText, serverProps, indent) {
        var maxLength = 120 - 2 * indent;
        if (null === serverProps)
          return added(indent) + describeTextNode(clientText, maxLength) + "\n";
        if ("string" === typeof serverProps) {
          for (var firstDiff = 0; firstDiff < serverProps.length && firstDiff < clientText.length && serverProps.charCodeAt(firstDiff) === clientText.charCodeAt(firstDiff); firstDiff++) ;
          firstDiff > maxLength - 8 && 10 < firstDiff && (clientText = "..." + clientText.slice(firstDiff - 8), serverProps = "..." + serverProps.slice(firstDiff - 8));
          return added(indent) + describeTextNode(clientText, maxLength) + "\n" + removed(indent) + describeTextNode(serverProps, maxLength) + "\n";
        }
        return indentation(indent) + describeTextNode(clientText, maxLength) + "\n";
      }
      function objectName(object) {
        return Object.prototype.toString.call(object).replace(/^\[object (.*)\]$/, function(m, p0) {
          return p0;
        });
      }
      function describeValue(value, maxLength) {
        switch (typeof value) {
          case "string":
            return value = JSON.stringify(value), value.length > maxLength ? 5 > maxLength ? '"..."' : value.slice(0, maxLength - 4) + '..."' : value;
          case "object":
            if (null === value) return "null";
            if (isArrayImpl(value)) return "[...]";
            if (value.$$typeof === REACT_ELEMENT_TYPE)
              return (maxLength = getComponentNameFromType(value.type)) ? "<" + maxLength + ">" : "<...>";
            var name = objectName(value);
            if ("Object" === name) {
              name = "";
              maxLength -= 2;
              for (var propName in value)
                if (value.hasOwnProperty(propName)) {
                  var jsonPropName = JSON.stringify(propName);
                  jsonPropName !== '"' + propName + '"' && (propName = jsonPropName);
                  maxLength -= propName.length - 2;
                  jsonPropName = describeValue(
                    value[propName],
                    15 > maxLength ? maxLength : 15
                  );
                  maxLength -= jsonPropName.length;
                  if (0 > maxLength) {
                    name += "" === name ? "..." : ", ...";
                    break;
                  }
                  name += ("" === name ? "" : ",") + propName + ":" + jsonPropName;
                }
              return "{" + name + "}";
            }
            return name;
          case "function":
            return (maxLength = value.displayName || value.name) ? "function " + maxLength : "function";
          default:
            return String(value);
        }
      }
      function describePropValue(value, maxLength) {
        return "string" !== typeof value || needsEscaping.test(value) ? "{" + describeValue(value, maxLength - 2) + "}" : value.length > maxLength - 2 ? 5 > maxLength ? '"..."' : '"' + value.slice(0, maxLength - 5) + '..."' : '"' + value + '"';
      }
      function describeExpandedElement(type, props, rowPrefix) {
        var remainingRowLength = 120 - rowPrefix.length - type.length, properties = [], propName;
        for (propName in props)
          if (props.hasOwnProperty(propName) && "children" !== propName) {
            var propValue = describePropValue(
              props[propName],
              120 - rowPrefix.length - propName.length - 1
            );
            remainingRowLength -= propName.length + propValue.length + 2;
            properties.push(propName + "=" + propValue);
          }
        return 0 === properties.length ? rowPrefix + "<" + type + ">\n" : 0 < remainingRowLength ? rowPrefix + "<" + type + " " + properties.join(" ") + ">\n" : rowPrefix + "<" + type + "\n" + rowPrefix + "  " + properties.join("\n" + rowPrefix + "  ") + "\n" + rowPrefix + ">\n";
      }
      function describePropertiesDiff(clientObject, serverObject, indent) {
        var properties = "", remainingServerProperties = assign({}, serverObject), propName;
        for (propName in clientObject)
          if (clientObject.hasOwnProperty(propName)) {
            delete remainingServerProperties[propName];
            var maxLength = 120 - 2 * indent - propName.length - 2, clientPropValue = describeValue(clientObject[propName], maxLength);
            serverObject.hasOwnProperty(propName) ? (maxLength = describeValue(serverObject[propName], maxLength), properties += added(indent) + propName + ": " + clientPropValue + "\n", properties += removed(indent) + propName + ": " + maxLength + "\n") : properties += added(indent) + propName + ": " + clientPropValue + "\n";
          }
        for (var _propName in remainingServerProperties)
          remainingServerProperties.hasOwnProperty(_propName) && (clientObject = describeValue(
            remainingServerProperties[_propName],
            120 - 2 * indent - _propName.length - 2
          ), properties += removed(indent) + _propName + ": " + clientObject + "\n");
        return properties;
      }
      function describeElementDiff(type, clientProps, serverProps, indent) {
        var content = "", serverPropNames = /* @__PURE__ */ new Map();
        for (propName$jscomp$0 in serverProps)
          serverProps.hasOwnProperty(propName$jscomp$0) && serverPropNames.set(
            propName$jscomp$0.toLowerCase(),
            propName$jscomp$0
          );
        if (1 === serverPropNames.size && serverPropNames.has("children"))
          content += describeExpandedElement(
            type,
            clientProps,
            indentation(indent)
          );
        else {
          for (var _propName2 in clientProps)
            if (clientProps.hasOwnProperty(_propName2) && "children" !== _propName2) {
              var maxLength$jscomp$0 = 120 - 2 * (indent + 1) - _propName2.length - 1, serverPropName = serverPropNames.get(_propName2.toLowerCase());
              if (void 0 !== serverPropName) {
                serverPropNames.delete(_propName2.toLowerCase());
                var propName$jscomp$0 = clientProps[_propName2];
                serverPropName = serverProps[serverPropName];
                var clientPropValue = describePropValue(
                  propName$jscomp$0,
                  maxLength$jscomp$0
                );
                maxLength$jscomp$0 = describePropValue(
                  serverPropName,
                  maxLength$jscomp$0
                );
                "object" === typeof propName$jscomp$0 && null !== propName$jscomp$0 && "object" === typeof serverPropName && null !== serverPropName && "Object" === objectName(propName$jscomp$0) && "Object" === objectName(serverPropName) && (2 < Object.keys(propName$jscomp$0).length || 2 < Object.keys(serverPropName).length || -1 < clientPropValue.indexOf("...") || -1 < maxLength$jscomp$0.indexOf("...")) ? content += indentation(indent + 1) + _propName2 + "={{\n" + describePropertiesDiff(
                  propName$jscomp$0,
                  serverPropName,
                  indent + 2
                ) + indentation(indent + 1) + "}}\n" : (content += added(indent + 1) + _propName2 + "=" + clientPropValue + "\n", content += removed(indent + 1) + _propName2 + "=" + maxLength$jscomp$0 + "\n");
              } else
                content += indentation(indent + 1) + _propName2 + "=" + describePropValue(clientProps[_propName2], maxLength$jscomp$0) + "\n";
            }
          serverPropNames.forEach(function(propName) {
            if ("children" !== propName) {
              var maxLength = 120 - 2 * (indent + 1) - propName.length - 1;
              content += removed(indent + 1) + propName + "=" + describePropValue(serverProps[propName], maxLength) + "\n";
            }
          });
          content = "" === content ? indentation(indent) + "<" + type + ">\n" : indentation(indent) + "<" + type + "\n" + content + indentation(indent) + ">\n";
        }
        type = serverProps.children;
        clientProps = clientProps.children;
        if ("string" === typeof type || "number" === typeof type || "bigint" === typeof type) {
          serverPropNames = "";
          if ("string" === typeof clientProps || "number" === typeof clientProps || "bigint" === typeof clientProps)
            serverPropNames = "" + clientProps;
          content += describeTextDiff(serverPropNames, "" + type, indent + 1);
        } else if ("string" === typeof clientProps || "number" === typeof clientProps || "bigint" === typeof clientProps)
          content = null == type ? content + describeTextDiff("" + clientProps, null, indent + 1) : content + describeTextDiff("" + clientProps, void 0, indent + 1);
        return content;
      }
      function describeSiblingFiber(fiber, indent) {
        var type = describeFiberType(fiber);
        if (null === type) {
          type = "";
          for (fiber = fiber.child; fiber; )
            type += describeSiblingFiber(fiber, indent), fiber = fiber.sibling;
          return type;
        }
        return indentation(indent) + "<" + type + ">\n";
      }
      function describeNode(node, indent) {
        var skipToNode = findNotableNode(node, indent);
        if (skipToNode !== node && (1 !== node.children.length || node.children[0] !== skipToNode))
          return indentation(indent) + "...\n" + describeNode(skipToNode, indent + 1);
        skipToNode = "";
        var debugInfo = node.fiber._debugInfo;
        if (debugInfo)
          for (var i = 0; i < debugInfo.length; i++) {
            var serverComponentName = debugInfo[i].name;
            "string" === typeof serverComponentName && (skipToNode += indentation(indent) + "<" + serverComponentName + ">\n", indent++);
          }
        debugInfo = "";
        i = node.fiber.pendingProps;
        if (6 === node.fiber.tag)
          debugInfo = describeTextDiff(i, node.serverProps, indent), indent++;
        else if (serverComponentName = describeFiberType(node.fiber), null !== serverComponentName)
          if (void 0 === node.serverProps) {
            debugInfo = indent;
            var maxLength = 120 - 2 * debugInfo - serverComponentName.length - 2, content = "";
            for (propName in i)
              if (i.hasOwnProperty(propName) && "children" !== propName) {
                var propValue = describePropValue(i[propName], 15);
                maxLength -= propName.length + propValue.length + 2;
                if (0 > maxLength) {
                  content += " ...";
                  break;
                }
                content += " " + propName + "=" + propValue;
              }
            debugInfo = indentation(debugInfo) + "<" + serverComponentName + content + ">\n";
            indent++;
          } else
            null === node.serverProps ? (debugInfo = describeExpandedElement(
              serverComponentName,
              i,
              added(indent)
            ), indent++) : "string" === typeof node.serverProps ? console.error(
              "Should not have matched a non HostText fiber to a Text node. This is a bug in React."
            ) : (debugInfo = describeElementDiff(
              serverComponentName,
              i,
              node.serverProps,
              indent
            ), indent++);
        var propName = "";
        i = node.fiber.child;
        for (serverComponentName = 0; i && serverComponentName < node.children.length; )
          maxLength = node.children[serverComponentName], maxLength.fiber === i ? (propName += describeNode(maxLength, indent), serverComponentName++) : propName += describeSiblingFiber(i, indent), i = i.sibling;
        i && 0 < node.children.length && (propName += indentation(indent) + "...\n");
        i = node.serverTail;
        null === node.serverProps && indent--;
        for (node = 0; node < i.length; node++)
          serverComponentName = i[node], propName = "string" === typeof serverComponentName ? propName + (removed(indent) + describeTextNode(serverComponentName, 120 - 2 * indent) + "\n") : propName + describeExpandedElement(
            serverComponentName.type,
            serverComponentName.props,
            removed(indent)
          );
        return skipToNode + debugInfo + propName;
      }
      function describeDiff(rootNode) {
        try {
          return "\n\n" + describeNode(rootNode, 0);
        } catch (x5) {
          return "";
        }
      }
      function describeAncestors(ancestor, child, props) {
        for (var fiber = child, node = null, distanceFromLeaf = 0; fiber; )
          fiber === ancestor && (distanceFromLeaf = 0), node = {
            fiber,
            children: null !== node ? [node] : [],
            serverProps: fiber === child ? props : fiber === ancestor ? null : void 0,
            serverTail: [],
            distanceFromLeaf
          }, distanceFromLeaf++, fiber = fiber.return;
        return null !== node ? describeDiff(node).replaceAll(/^[+-]/gm, ">") : "";
      }
      function updatedAncestorInfoDev(oldInfo, tag) {
        var ancestorInfo = assign({}, oldInfo || emptyAncestorInfoDev), info = { tag };
        -1 !== inScopeTags.indexOf(tag) && (ancestorInfo.aTagInScope = null, ancestorInfo.buttonTagInScope = null, ancestorInfo.nobrTagInScope = null);
        -1 !== buttonScopeTags.indexOf(tag) && (ancestorInfo.pTagInButtonScope = null);
        -1 !== specialTags.indexOf(tag) && "address" !== tag && "div" !== tag && "p" !== tag && (ancestorInfo.listItemTagAutoclosing = null, ancestorInfo.dlItemTagAutoclosing = null);
        ancestorInfo.current = info;
        "form" === tag && (ancestorInfo.formTag = info);
        "a" === tag && (ancestorInfo.aTagInScope = info);
        "button" === tag && (ancestorInfo.buttonTagInScope = info);
        "nobr" === tag && (ancestorInfo.nobrTagInScope = info);
        "p" === tag && (ancestorInfo.pTagInButtonScope = info);
        "li" === tag && (ancestorInfo.listItemTagAutoclosing = info);
        if ("dd" === tag || "dt" === tag)
          ancestorInfo.dlItemTagAutoclosing = info;
        "#document" === tag || "html" === tag ? ancestorInfo.containerTagInScope = null : ancestorInfo.containerTagInScope || (ancestorInfo.containerTagInScope = info);
        null !== oldInfo || "#document" !== tag && "html" !== tag && "body" !== tag ? true === ancestorInfo.implicitRootScope && (ancestorInfo.implicitRootScope = false) : ancestorInfo.implicitRootScope = true;
        return ancestorInfo;
      }
      function isTagValidWithParent(tag, parentTag, implicitRootScope) {
        switch (parentTag) {
          case "select":
            return "hr" === tag || "option" === tag || "optgroup" === tag || "script" === tag || "template" === tag || "#text" === tag;
          case "optgroup":
            return "option" === tag || "#text" === tag;
          case "option":
            return "#text" === tag;
          case "tr":
            return "th" === tag || "td" === tag || "style" === tag || "script" === tag || "template" === tag;
          case "tbody":
          case "thead":
          case "tfoot":
            return "tr" === tag || "style" === tag || "script" === tag || "template" === tag;
          case "colgroup":
            return "col" === tag || "template" === tag;
          case "table":
            return "caption" === tag || "colgroup" === tag || "tbody" === tag || "tfoot" === tag || "thead" === tag || "style" === tag || "script" === tag || "template" === tag;
          case "head":
            return "base" === tag || "basefont" === tag || "bgsound" === tag || "link" === tag || "meta" === tag || "title" === tag || "noscript" === tag || "noframes" === tag || "style" === tag || "script" === tag || "template" === tag;
          case "html":
            if (implicitRootScope) break;
            return "head" === tag || "body" === tag || "frameset" === tag;
          case "frameset":
            return "frame" === tag;
          case "#document":
            if (!implicitRootScope) return "html" === tag;
        }
        switch (tag) {
          case "h1":
          case "h2":
          case "h3":
          case "h4":
          case "h5":
          case "h6":
            return "h1" !== parentTag && "h2" !== parentTag && "h3" !== parentTag && "h4" !== parentTag && "h5" !== parentTag && "h6" !== parentTag;
          case "rp":
          case "rt":
            return -1 === impliedEndTags.indexOf(parentTag);
          case "caption":
          case "col":
          case "colgroup":
          case "frameset":
          case "frame":
          case "tbody":
          case "td":
          case "tfoot":
          case "th":
          case "thead":
          case "tr":
            return null == parentTag;
          case "head":
            return implicitRootScope || null === parentTag;
          case "html":
            return implicitRootScope && "#document" === parentTag || null === parentTag;
          case "body":
            return implicitRootScope && ("#document" === parentTag || "html" === parentTag) || null === parentTag;
        }
        return true;
      }
      function findInvalidAncestorForTag(tag, ancestorInfo) {
        switch (tag) {
          case "address":
          case "article":
          case "aside":
          case "blockquote":
          case "center":
          case "details":
          case "dialog":
          case "dir":
          case "div":
          case "dl":
          case "fieldset":
          case "figcaption":
          case "figure":
          case "footer":
          case "header":
          case "hgroup":
          case "main":
          case "menu":
          case "nav":
          case "ol":
          case "p":
          case "section":
          case "summary":
          case "ul":
          case "pre":
          case "listing":
          case "table":
          case "hr":
          case "xmp":
          case "h1":
          case "h2":
          case "h3":
          case "h4":
          case "h5":
          case "h6":
            return ancestorInfo.pTagInButtonScope;
          case "form":
            return ancestorInfo.formTag || ancestorInfo.pTagInButtonScope;
          case "li":
            return ancestorInfo.listItemTagAutoclosing;
          case "dd":
          case "dt":
            return ancestorInfo.dlItemTagAutoclosing;
          case "button":
            return ancestorInfo.buttonTagInScope;
          case "a":
            return ancestorInfo.aTagInScope;
          case "nobr":
            return ancestorInfo.nobrTagInScope;
        }
        return null;
      }
      function findAncestor(parent, tagName) {
        for (; parent; ) {
          switch (parent.tag) {
            case 5:
            case 26:
            case 27:
              if (parent.type === tagName) return parent;
          }
          parent = parent.return;
        }
        return null;
      }
      function validateDOMNesting(childTag, ancestorInfo) {
        ancestorInfo = ancestorInfo || emptyAncestorInfoDev;
        var parentInfo = ancestorInfo.current;
        ancestorInfo = (parentInfo = isTagValidWithParent(
          childTag,
          parentInfo && parentInfo.tag,
          ancestorInfo.implicitRootScope
        ) ? null : parentInfo) ? null : findInvalidAncestorForTag(childTag, ancestorInfo);
        ancestorInfo = parentInfo || ancestorInfo;
        if (!ancestorInfo) return true;
        var ancestorTag = ancestorInfo.tag;
        ancestorInfo = String(!!parentInfo) + "|" + childTag + "|" + ancestorTag;
        if (didWarn[ancestorInfo]) return false;
        didWarn[ancestorInfo] = true;
        var ancestor = (ancestorInfo = current) ? findAncestor(ancestorInfo.return, ancestorTag) : null, ancestorDescription = null !== ancestorInfo && null !== ancestor ? describeAncestors(ancestor, ancestorInfo, null) : "", tagDisplayName = "<" + childTag + ">";
        parentInfo ? (parentInfo = "", "table" === ancestorTag && "tr" === childTag && (parentInfo += " Add a <tbody>, <thead> or <tfoot> to your code to match the DOM tree generated by the browser."), console.error(
          "In HTML, %s cannot be a child of <%s>.%s\nThis will cause a hydration error.%s",
          tagDisplayName,
          ancestorTag,
          parentInfo,
          ancestorDescription
        )) : console.error(
          "In HTML, %s cannot be a descendant of <%s>.\nThis will cause a hydration error.%s",
          tagDisplayName,
          ancestorTag,
          ancestorDescription
        );
        ancestorInfo && (childTag = ancestorInfo.return, null === ancestor || null === childTag || ancestor === childTag && childTag._debugOwner === ancestorInfo._debugOwner || runWithFiberInDEV(ancestor, function() {
          console.error(
            "<%s> cannot contain a nested %s.\nSee this log for the ancestor stack trace.",
            ancestorTag,
            tagDisplayName
          );
        }));
        return false;
      }
      function validateTextNesting(childText, parentTag, implicitRootScope) {
        if (implicitRootScope || isTagValidWithParent("#text", parentTag, false))
          return true;
        implicitRootScope = "#text|" + parentTag;
        if (didWarn[implicitRootScope]) return false;
        didWarn[implicitRootScope] = true;
        var ancestor = (implicitRootScope = current) ? findAncestor(implicitRootScope, parentTag) : null;
        implicitRootScope = null !== implicitRootScope && null !== ancestor ? describeAncestors(
          ancestor,
          implicitRootScope,
          6 !== implicitRootScope.tag ? { children: null } : null
        ) : "";
        /\S/.test(childText) ? console.error(
          "In HTML, text nodes cannot be a child of <%s>.\nThis will cause a hydration error.%s",
          parentTag,
          implicitRootScope
        ) : console.error(
          "In HTML, whitespace text nodes cannot be a child of <%s>. Make sure you don't have any extra whitespace between tags on each line of your source code.\nThis will cause a hydration error.%s",
          parentTag,
          implicitRootScope
        );
        return false;
      }
      function setTextContent(node, text5) {
        if (text5) {
          var firstChild = node.firstChild;
          if (firstChild && firstChild === node.lastChild && 3 === firstChild.nodeType) {
            firstChild.nodeValue = text5;
            return;
          }
        }
        node.textContent = text5;
      }
      function camelize(string) {
        return string.replace(hyphenPattern, function(_10, character) {
          return character.toUpperCase();
        });
      }
      function setValueForStyle(style3, styleName, value) {
        var isCustomProperty = 0 === styleName.indexOf("--");
        isCustomProperty || (-1 < styleName.indexOf("-") ? warnedStyleNames.hasOwnProperty(styleName) && warnedStyleNames[styleName] || (warnedStyleNames[styleName] = true, console.error(
          "Unsupported style property %s. Did you mean %s?",
          styleName,
          camelize(styleName.replace(msPattern, "ms-"))
        )) : badVendoredStyleNamePattern.test(styleName) ? warnedStyleNames.hasOwnProperty(styleName) && warnedStyleNames[styleName] || (warnedStyleNames[styleName] = true, console.error(
          "Unsupported vendor-prefixed style property %s. Did you mean %s?",
          styleName,
          styleName.charAt(0).toUpperCase() + styleName.slice(1)
        )) : !badStyleValueWithSemicolonPattern.test(value) || warnedStyleValues.hasOwnProperty(value) && warnedStyleValues[value] || (warnedStyleValues[value] = true, console.error(
          `Style property values shouldn't contain a semicolon. Try "%s: %s" instead.`,
          styleName,
          value.replace(badStyleValueWithSemicolonPattern, "")
        )), "number" === typeof value && (isNaN(value) ? warnedForNaNValue || (warnedForNaNValue = true, console.error(
          "`NaN` is an invalid value for the `%s` css style property.",
          styleName
        )) : isFinite(value) || warnedForInfinityValue || (warnedForInfinityValue = true, console.error(
          "`Infinity` is an invalid value for the `%s` css style property.",
          styleName
        ))));
        null == value || "boolean" === typeof value || "" === value ? isCustomProperty ? style3.setProperty(styleName, "") : "float" === styleName ? style3.cssFloat = "" : style3[styleName] = "" : isCustomProperty ? style3.setProperty(styleName, value) : "number" !== typeof value || 0 === value || unitlessNumbers.has(styleName) ? "float" === styleName ? style3.cssFloat = value : (checkCSSPropertyStringCoercion(value, styleName), style3[styleName] = ("" + value).trim()) : style3[styleName] = value + "px";
      }
      function setValueForStyles(node, styles2, prevStyles) {
        if (null != styles2 && "object" !== typeof styles2)
          throw Error(
            "The `style` prop expects a mapping from style properties to values, not a string. For example, style={{marginRight: spacing + 'em'}} when using JSX."
          );
        styles2 && Object.freeze(styles2);
        node = node.style;
        if (null != prevStyles) {
          if (styles2) {
            var expandedUpdates = {};
            if (prevStyles) {
              for (var key in prevStyles)
                if (prevStyles.hasOwnProperty(key) && !styles2.hasOwnProperty(key))
                  for (var longhands = shorthandToLonghand[key] || [key], i = 0; i < longhands.length; i++)
                    expandedUpdates[longhands[i]] = key;
            }
            for (var _key in styles2)
              if (styles2.hasOwnProperty(_key) && (!prevStyles || prevStyles[_key] !== styles2[_key]))
                for (key = shorthandToLonghand[_key] || [_key], longhands = 0; longhands < key.length; longhands++)
                  expandedUpdates[key[longhands]] = _key;
            _key = {};
            for (var key$jscomp$0 in styles2)
              for (key = shorthandToLonghand[key$jscomp$0] || [key$jscomp$0], longhands = 0; longhands < key.length; longhands++)
                _key[key[longhands]] = key$jscomp$0;
            key$jscomp$0 = {};
            for (var _key2 in expandedUpdates)
              if (key = expandedUpdates[_key2], (longhands = _key[_key2]) && key !== longhands && (i = key + "," + longhands, !key$jscomp$0[i])) {
                key$jscomp$0[i] = true;
                i = console;
                var value = styles2[key];
                i.error.call(
                  i,
                  "%s a style property during rerender (%s) when a conflicting property is set (%s) can lead to styling bugs. To avoid this, don't mix shorthand and non-shorthand properties for the same value; instead, replace the shorthand with separate values.",
                  null == value || "boolean" === typeof value || "" === value ? "Removing" : "Updating",
                  key,
                  longhands
                );
              }
          }
          for (var styleName in prevStyles)
            !prevStyles.hasOwnProperty(styleName) || null != styles2 && styles2.hasOwnProperty(styleName) || (0 === styleName.indexOf("--") ? node.setProperty(styleName, "") : "float" === styleName ? node.cssFloat = "" : node[styleName] = "");
          for (var _styleName in styles2)
            _key2 = styles2[_styleName], styles2.hasOwnProperty(_styleName) && prevStyles[_styleName] !== _key2 && setValueForStyle(node, _styleName, _key2);
        } else
          for (expandedUpdates in styles2)
            styles2.hasOwnProperty(expandedUpdates) && setValueForStyle(node, expandedUpdates, styles2[expandedUpdates]);
      }
      function isCustomElement(tagName) {
        if (-1 === tagName.indexOf("-")) return false;
        switch (tagName) {
          case "annotation-xml":
          case "color-profile":
          case "font-face":
          case "font-face-src":
          case "font-face-uri":
          case "font-face-format":
          case "font-face-name":
          case "missing-glyph":
            return false;
          default:
            return true;
        }
      }
      function getAttributeAlias(name) {
        return aliases.get(name) || name;
      }
      function validateProperty$1(tagName, name) {
        if (hasOwnProperty2.call(warnedProperties$1, name) && warnedProperties$1[name])
          return true;
        if (rARIACamel$1.test(name)) {
          tagName = "aria-" + name.slice(4).toLowerCase();
          tagName = ariaProperties.hasOwnProperty(tagName) ? tagName : null;
          if (null == tagName)
            return console.error(
              "Invalid ARIA attribute `%s`. ARIA attributes follow the pattern aria-* and must be lowercase.",
              name
            ), warnedProperties$1[name] = true;
          if (name !== tagName)
            return console.error(
              "Invalid ARIA attribute `%s`. Did you mean `%s`?",
              name,
              tagName
            ), warnedProperties$1[name] = true;
        }
        if (rARIA$1.test(name)) {
          tagName = name.toLowerCase();
          tagName = ariaProperties.hasOwnProperty(tagName) ? tagName : null;
          if (null == tagName) return warnedProperties$1[name] = true, false;
          name !== tagName && (console.error(
            "Unknown ARIA attribute `%s`. Did you mean `%s`?",
            name,
            tagName
          ), warnedProperties$1[name] = true);
        }
        return true;
      }
      function validateProperties$2(type, props) {
        var invalidProps = [], key;
        for (key in props)
          validateProperty$1(type, key) || invalidProps.push(key);
        props = invalidProps.map(function(prop) {
          return "`" + prop + "`";
        }).join(", ");
        1 === invalidProps.length ? console.error(
          "Invalid aria prop %s on <%s> tag. For details, see https://react.dev/link/invalid-aria-props",
          props,
          type
        ) : 1 < invalidProps.length && console.error(
          "Invalid aria props %s on <%s> tag. For details, see https://react.dev/link/invalid-aria-props",
          props,
          type
        );
      }
      function validateProperty(tagName, name, value, eventRegistry) {
        if (hasOwnProperty2.call(warnedProperties, name) && warnedProperties[name])
          return true;
        var lowerCasedName = name.toLowerCase();
        if ("onfocusin" === lowerCasedName || "onfocusout" === lowerCasedName)
          return console.error(
            "React uses onFocus and onBlur instead of onFocusIn and onFocusOut. All React events are normalized to bubble, so onFocusIn and onFocusOut are not needed/supported by React."
          ), warnedProperties[name] = true;
        if ("function" === typeof value && ("form" === tagName && "action" === name || "input" === tagName && "formAction" === name || "button" === tagName && "formAction" === name))
          return true;
        if (null != eventRegistry) {
          tagName = eventRegistry.possibleRegistrationNames;
          if (eventRegistry.registrationNameDependencies.hasOwnProperty(name))
            return true;
          eventRegistry = tagName.hasOwnProperty(lowerCasedName) ? tagName[lowerCasedName] : null;
          if (null != eventRegistry)
            return console.error(
              "Invalid event handler property `%s`. Did you mean `%s`?",
              name,
              eventRegistry
            ), warnedProperties[name] = true;
          if (EVENT_NAME_REGEX.test(name))
            return console.error(
              "Unknown event handler property `%s`. It will be ignored.",
              name
            ), warnedProperties[name] = true;
        } else if (EVENT_NAME_REGEX.test(name))
          return INVALID_EVENT_NAME_REGEX.test(name) && console.error(
            "Invalid event handler property `%s`. React events use the camelCase naming convention, for example `onClick`.",
            name
          ), warnedProperties[name] = true;
        if (rARIA.test(name) || rARIACamel.test(name)) return true;
        if ("innerhtml" === lowerCasedName)
          return console.error(
            "Directly setting property `innerHTML` is not permitted. For more information, lookup documentation on `dangerouslySetInnerHTML`."
          ), warnedProperties[name] = true;
        if ("aria" === lowerCasedName)
          return console.error(
            "The `aria` attribute is reserved for future use in React. Pass individual `aria-` attributes instead."
          ), warnedProperties[name] = true;
        if ("is" === lowerCasedName && null !== value && void 0 !== value && "string" !== typeof value)
          return console.error(
            "Received a `%s` for a string attribute `is`. If this is expected, cast the value to a string.",
            typeof value
          ), warnedProperties[name] = true;
        if ("number" === typeof value && isNaN(value))
          return console.error(
            "Received NaN for the `%s` attribute. If this is expected, cast the value to a string.",
            name
          ), warnedProperties[name] = true;
        if (possibleStandardNames.hasOwnProperty(lowerCasedName)) {
          if (lowerCasedName = possibleStandardNames[lowerCasedName], lowerCasedName !== name)
            return console.error(
              "Invalid DOM property `%s`. Did you mean `%s`?",
              name,
              lowerCasedName
            ), warnedProperties[name] = true;
        } else if (name !== lowerCasedName)
          return console.error(
            "React does not recognize the `%s` prop on a DOM element. If you intentionally want it to appear in the DOM as a custom attribute, spell it as lowercase `%s` instead. If you accidentally passed it from a parent component, remove it from the DOM element.",
            name,
            lowerCasedName
          ), warnedProperties[name] = true;
        switch (name) {
          case "dangerouslySetInnerHTML":
          case "children":
          case "style":
          case "suppressContentEditableWarning":
          case "suppressHydrationWarning":
          case "defaultValue":
          case "defaultChecked":
          case "innerHTML":
          case "ref":
            return true;
          case "innerText":
          case "textContent":
            return true;
        }
        switch (typeof value) {
          case "boolean":
            switch (name) {
              case "autoFocus":
              case "checked":
              case "multiple":
              case "muted":
              case "selected":
              case "contentEditable":
              case "spellCheck":
              case "draggable":
              case "value":
              case "autoReverse":
              case "externalResourcesRequired":
              case "focusable":
              case "preserveAlpha":
              case "allowFullScreen":
              case "async":
              case "autoPlay":
              case "controls":
              case "default":
              case "defer":
              case "disabled":
              case "disablePictureInPicture":
              case "disableRemotePlayback":
              case "formNoValidate":
              case "hidden":
              case "loop":
              case "noModule":
              case "noValidate":
              case "open":
              case "playsInline":
              case "readOnly":
              case "required":
              case "reversed":
              case "scoped":
              case "seamless":
              case "itemScope":
              case "capture":
              case "download":
              case "inert":
                return true;
              default:
                lowerCasedName = name.toLowerCase().slice(0, 5);
                if ("data-" === lowerCasedName || "aria-" === lowerCasedName)
                  return true;
                value ? console.error(
                  'Received `%s` for a non-boolean attribute `%s`.\n\nIf you want to write it to the DOM, pass a string instead: %s="%s" or %s={value.toString()}.',
                  value,
                  name,
                  name,
                  value,
                  name
                ) : console.error(
                  'Received `%s` for a non-boolean attribute `%s`.\n\nIf you want to write it to the DOM, pass a string instead: %s="%s" or %s={value.toString()}.\n\nIf you used to conditionally omit it with %s={condition && value}, pass %s={condition ? value : undefined} instead.',
                  value,
                  name,
                  name,
                  value,
                  name,
                  name,
                  name
                );
                return warnedProperties[name] = true;
            }
          case "function":
          case "symbol":
            return warnedProperties[name] = true, false;
          case "string":
            if ("false" === value || "true" === value) {
              switch (name) {
                case "checked":
                case "selected":
                case "multiple":
                case "muted":
                case "allowFullScreen":
                case "async":
                case "autoPlay":
                case "controls":
                case "default":
                case "defer":
                case "disabled":
                case "disablePictureInPicture":
                case "disableRemotePlayback":
                case "formNoValidate":
                case "hidden":
                case "loop":
                case "noModule":
                case "noValidate":
                case "open":
                case "playsInline":
                case "readOnly":
                case "required":
                case "reversed":
                case "scoped":
                case "seamless":
                case "itemScope":
                case "inert":
                  break;
                default:
                  return true;
              }
              console.error(
                "Received the string `%s` for the boolean attribute `%s`. %s Did you mean %s={%s}?",
                value,
                name,
                "false" === value ? "The browser will interpret it as a truthy value." : 'Although this works, it will not work as expected if you pass the string "false".',
                name,
                value
              );
              warnedProperties[name] = true;
            }
        }
        return true;
      }
      function warnUnknownProperties(type, props, eventRegistry) {
        var unknownProps = [], key;
        for (key in props)
          validateProperty(type, key, props[key], eventRegistry) || unknownProps.push(key);
        props = unknownProps.map(function(prop) {
          return "`" + prop + "`";
        }).join(", ");
        1 === unknownProps.length ? console.error(
          "Invalid value for prop %s on <%s> tag. Either remove it from the element, or pass a string or number value to keep it in the DOM. For details, see https://react.dev/link/attribute-behavior ",
          props,
          type
        ) : 1 < unknownProps.length && console.error(
          "Invalid values for props %s on <%s> tag. Either remove them from the element, or pass a string or number value to keep them in the DOM. For details, see https://react.dev/link/attribute-behavior ",
          props,
          type
        );
      }
      function sanitizeURL(url) {
        return isJavaScriptProtocol.test("" + url) ? "javascript:throw new Error('React has blocked a javascript: URL as a security precaution.')" : url;
      }
      function noop$1() {
      }
      function getEventTarget(nativeEvent) {
        nativeEvent = nativeEvent.target || nativeEvent.srcElement || window;
        nativeEvent.correspondingUseElement && (nativeEvent = nativeEvent.correspondingUseElement);
        return 3 === nativeEvent.nodeType ? nativeEvent.parentNode : nativeEvent;
      }
      function restoreStateOfTarget(target2) {
        var internalInstance = getInstanceFromNode(target2);
        if (internalInstance && (target2 = internalInstance.stateNode)) {
          var props = target2[internalPropsKey] || null;
          a: switch (target2 = internalInstance.stateNode, internalInstance.type) {
            case "input":
              updateInput(
                target2,
                props.value,
                props.defaultValue,
                props.defaultValue,
                props.checked,
                props.defaultChecked,
                props.type,
                props.name
              );
              internalInstance = props.name;
              if ("radio" === props.type && null != internalInstance) {
                for (props = target2; props.parentNode; ) props = props.parentNode;
                checkAttributeStringCoercion(internalInstance, "name");
                props = props.querySelectorAll(
                  'input[name="' + escapeSelectorAttributeValueInsideDoubleQuotes(
                    "" + internalInstance
                  ) + '"][type="radio"]'
                );
                for (internalInstance = 0; internalInstance < props.length; internalInstance++) {
                  var otherNode = props[internalInstance];
                  if (otherNode !== target2 && otherNode.form === target2.form) {
                    var otherProps = otherNode[internalPropsKey] || null;
                    if (!otherProps)
                      throw Error(
                        "ReactDOMInput: Mixing React and non-React radio inputs with the same `name` is not supported."
                      );
                    updateInput(
                      otherNode,
                      otherProps.value,
                      otherProps.defaultValue,
                      otherProps.defaultValue,
                      otherProps.checked,
                      otherProps.defaultChecked,
                      otherProps.type,
                      otherProps.name
                    );
                  }
                }
                for (internalInstance = 0; internalInstance < props.length; internalInstance++)
                  otherNode = props[internalInstance], otherNode.form === target2.form && updateValueIfChanged(otherNode);
              }
              break a;
            case "textarea":
              updateTextarea(target2, props.value, props.defaultValue);
              break a;
            case "select":
              internalInstance = props.value, null != internalInstance && updateOptions(target2, !!props.multiple, internalInstance, false);
          }
        }
      }
      function batchedUpdates$1(fn, a2, b2) {
        if (isInsideEventHandler) return fn(a2, b2);
        isInsideEventHandler = true;
        try {
          var JSCompiler_inline_result = fn(a2);
          return JSCompiler_inline_result;
        } finally {
          if (isInsideEventHandler = false, null !== restoreTarget || null !== restoreQueue) {
            if (flushSyncWork$1(), restoreTarget && (a2 = restoreTarget, fn = restoreQueue, restoreQueue = restoreTarget = null, restoreStateOfTarget(a2), fn))
              for (a2 = 0; a2 < fn.length; a2++) restoreStateOfTarget(fn[a2]);
          }
        }
      }
      function getListener(inst, registrationName) {
        var stateNode = inst.stateNode;
        if (null === stateNode) return null;
        var props = stateNode[internalPropsKey] || null;
        if (null === props) return null;
        stateNode = props[registrationName];
        a: switch (registrationName) {
          case "onClick":
          case "onClickCapture":
          case "onDoubleClick":
          case "onDoubleClickCapture":
          case "onMouseDown":
          case "onMouseDownCapture":
          case "onMouseMove":
          case "onMouseMoveCapture":
          case "onMouseUp":
          case "onMouseUpCapture":
          case "onMouseEnter":
            (props = !props.disabled) || (inst = inst.type, props = !("button" === inst || "input" === inst || "select" === inst || "textarea" === inst));
            inst = !props;
            break a;
          default:
            inst = false;
        }
        if (inst) return null;
        if (stateNode && "function" !== typeof stateNode)
          throw Error(
            "Expected `" + registrationName + "` listener to be a function, instead got a value of `" + typeof stateNode + "` type."
          );
        return stateNode;
      }
      function getData() {
        if (fallbackText) return fallbackText;
        var start, startValue = startText, startLength = startValue.length, end, endValue = "value" in root ? root.value : root.textContent, endLength = endValue.length;
        for (start = 0; start < startLength && startValue[start] === endValue[start]; start++) ;
        var minEnd = startLength - start;
        for (end = 1; end <= minEnd && startValue[startLength - end] === endValue[endLength - end]; end++) ;
        return fallbackText = endValue.slice(start, 1 < end ? 1 - end : void 0);
      }
      function getEventCharCode(nativeEvent) {
        var keyCode = nativeEvent.keyCode;
        "charCode" in nativeEvent ? (nativeEvent = nativeEvent.charCode, 0 === nativeEvent && 13 === keyCode && (nativeEvent = 13)) : nativeEvent = keyCode;
        10 === nativeEvent && (nativeEvent = 13);
        return 32 <= nativeEvent || 13 === nativeEvent ? nativeEvent : 0;
      }
      function functionThatReturnsTrue() {
        return true;
      }
      function functionThatReturnsFalse() {
        return false;
      }
      function createSyntheticEvent(Interface) {
        function SyntheticBaseEvent(reactName, reactEventType, targetInst, nativeEvent, nativeEventTarget) {
          this._reactName = reactName;
          this._targetInst = targetInst;
          this.type = reactEventType;
          this.nativeEvent = nativeEvent;
          this.target = nativeEventTarget;
          this.currentTarget = null;
          for (var propName in Interface)
            Interface.hasOwnProperty(propName) && (reactName = Interface[propName], this[propName] = reactName ? reactName(nativeEvent) : nativeEvent[propName]);
          this.isDefaultPrevented = (null != nativeEvent.defaultPrevented ? nativeEvent.defaultPrevented : false === nativeEvent.returnValue) ? functionThatReturnsTrue : functionThatReturnsFalse;
          this.isPropagationStopped = functionThatReturnsFalse;
          return this;
        }
        assign(SyntheticBaseEvent.prototype, {
          preventDefault: function() {
            this.defaultPrevented = true;
            var event = this.nativeEvent;
            event && (event.preventDefault ? event.preventDefault() : "unknown" !== typeof event.returnValue && (event.returnValue = false), this.isDefaultPrevented = functionThatReturnsTrue);
          },
          stopPropagation: function() {
            var event = this.nativeEvent;
            event && (event.stopPropagation ? event.stopPropagation() : "unknown" !== typeof event.cancelBubble && (event.cancelBubble = true), this.isPropagationStopped = functionThatReturnsTrue);
          },
          persist: function() {
          },
          isPersistent: functionThatReturnsTrue
        });
        return SyntheticBaseEvent;
      }
      function modifierStateGetter(keyArg) {
        var nativeEvent = this.nativeEvent;
        return nativeEvent.getModifierState ? nativeEvent.getModifierState(keyArg) : (keyArg = modifierKeyToProp[keyArg]) ? !!nativeEvent[keyArg] : false;
      }
      function getEventModifierState() {
        return modifierStateGetter;
      }
      function isFallbackCompositionEnd(domEventName, nativeEvent) {
        switch (domEventName) {
          case "keyup":
            return -1 !== END_KEYCODES.indexOf(nativeEvent.keyCode);
          case "keydown":
            return nativeEvent.keyCode !== START_KEYCODE;
          case "keypress":
          case "mousedown":
          case "focusout":
            return true;
          default:
            return false;
        }
      }
      function getDataFromCustomEvent(nativeEvent) {
        nativeEvent = nativeEvent.detail;
        return "object" === typeof nativeEvent && "data" in nativeEvent ? nativeEvent.data : null;
      }
      function getNativeBeforeInputChars(domEventName, nativeEvent) {
        switch (domEventName) {
          case "compositionend":
            return getDataFromCustomEvent(nativeEvent);
          case "keypress":
            if (nativeEvent.which !== SPACEBAR_CODE) return null;
            hasSpaceKeypress = true;
            return SPACEBAR_CHAR;
          case "textInput":
            return domEventName = nativeEvent.data, domEventName === SPACEBAR_CHAR && hasSpaceKeypress ? null : domEventName;
          default:
            return null;
        }
      }
      function getFallbackBeforeInputChars(domEventName, nativeEvent) {
        if (isComposing)
          return "compositionend" === domEventName || !canUseCompositionEvent && isFallbackCompositionEnd(domEventName, nativeEvent) ? (domEventName = getData(), fallbackText = startText = root = null, isComposing = false, domEventName) : null;
        switch (domEventName) {
          case "paste":
            return null;
          case "keypress":
            if (!(nativeEvent.ctrlKey || nativeEvent.altKey || nativeEvent.metaKey) || nativeEvent.ctrlKey && nativeEvent.altKey) {
              if (nativeEvent.char && 1 < nativeEvent.char.length)
                return nativeEvent.char;
              if (nativeEvent.which)
                return String.fromCharCode(nativeEvent.which);
            }
            return null;
          case "compositionend":
            return useFallbackCompositionData && "ko" !== nativeEvent.locale ? null : nativeEvent.data;
          default:
            return null;
        }
      }
      function isTextInputElement(elem) {
        var nodeName = elem && elem.nodeName && elem.nodeName.toLowerCase();
        return "input" === nodeName ? !!supportedInputTypes[elem.type] : "textarea" === nodeName ? true : false;
      }
      function isEventSupported(eventNameSuffix) {
        if (!canUseDOM) return false;
        eventNameSuffix = "on" + eventNameSuffix;
        var isSupported = eventNameSuffix in document;
        isSupported || (isSupported = document.createElement("div"), isSupported.setAttribute(eventNameSuffix, "return;"), isSupported = "function" === typeof isSupported[eventNameSuffix]);
        return isSupported;
      }
      function createAndAccumulateChangeEvent(dispatchQueue, inst, nativeEvent, target2) {
        restoreTarget ? restoreQueue ? restoreQueue.push(target2) : restoreQueue = [target2] : restoreTarget = target2;
        inst = accumulateTwoPhaseListeners(inst, "onChange");
        0 < inst.length && (nativeEvent = new SyntheticEvent(
          "onChange",
          "change",
          null,
          nativeEvent,
          target2
        ), dispatchQueue.push({ event: nativeEvent, listeners: inst }));
      }
      function runEventInBatch(dispatchQueue) {
        processDispatchQueue(dispatchQueue, 0);
      }
      function getInstIfValueChanged(targetInst) {
        var targetNode = getNodeFromInstance(targetInst);
        if (updateValueIfChanged(targetNode)) return targetInst;
      }
      function getTargetInstForChangeEvent(domEventName, targetInst) {
        if ("change" === domEventName) return targetInst;
      }
      function stopWatchingForValueChange() {
        activeElement$1 && (activeElement$1.detachEvent("onpropertychange", handlePropertyChange), activeElementInst$1 = activeElement$1 = null);
      }
      function handlePropertyChange(nativeEvent) {
        if ("value" === nativeEvent.propertyName && getInstIfValueChanged(activeElementInst$1)) {
          var dispatchQueue = [];
          createAndAccumulateChangeEvent(
            dispatchQueue,
            activeElementInst$1,
            nativeEvent,
            getEventTarget(nativeEvent)
          );
          batchedUpdates$1(runEventInBatch, dispatchQueue);
        }
      }
      function handleEventsForInputEventPolyfill(domEventName, target2, targetInst) {
        "focusin" === domEventName ? (stopWatchingForValueChange(), activeElement$1 = target2, activeElementInst$1 = targetInst, activeElement$1.attachEvent("onpropertychange", handlePropertyChange)) : "focusout" === domEventName && stopWatchingForValueChange();
      }
      function getTargetInstForInputEventPolyfill(domEventName) {
        if ("selectionchange" === domEventName || "keyup" === domEventName || "keydown" === domEventName)
          return getInstIfValueChanged(activeElementInst$1);
      }
      function getTargetInstForClickEvent(domEventName, targetInst) {
        if ("click" === domEventName) return getInstIfValueChanged(targetInst);
      }
      function getTargetInstForInputOrChangeEvent(domEventName, targetInst) {
        if ("input" === domEventName || "change" === domEventName)
          return getInstIfValueChanged(targetInst);
      }
      function is(x5, y) {
        return x5 === y && (0 !== x5 || 1 / x5 === 1 / y) || x5 !== x5 && y !== y;
      }
      function shallowEqual2(objA, objB) {
        if (objectIs(objA, objB)) return true;
        if ("object" !== typeof objA || null === objA || "object" !== typeof objB || null === objB)
          return false;
        var keysA = Object.keys(objA), keysB = Object.keys(objB);
        if (keysA.length !== keysB.length) return false;
        for (keysB = 0; keysB < keysA.length; keysB++) {
          var currentKey = keysA[keysB];
          if (!hasOwnProperty2.call(objB, currentKey) || !objectIs(objA[currentKey], objB[currentKey]))
            return false;
        }
        return true;
      }
      function getLeafNode(node) {
        for (; node && node.firstChild; ) node = node.firstChild;
        return node;
      }
      function getNodeForCharacterOffset(root2, offset) {
        var node = getLeafNode(root2);
        root2 = 0;
        for (var nodeEnd; node; ) {
          if (3 === node.nodeType) {
            nodeEnd = root2 + node.textContent.length;
            if (root2 <= offset && nodeEnd >= offset)
              return { node, offset: offset - root2 };
            root2 = nodeEnd;
          }
          a: {
            for (; node; ) {
              if (node.nextSibling) {
                node = node.nextSibling;
                break a;
              }
              node = node.parentNode;
            }
            node = void 0;
          }
          node = getLeafNode(node);
        }
      }
      function containsNode(outerNode, innerNode) {
        return outerNode && innerNode ? outerNode === innerNode ? true : outerNode && 3 === outerNode.nodeType ? false : innerNode && 3 === innerNode.nodeType ? containsNode(outerNode, innerNode.parentNode) : "contains" in outerNode ? outerNode.contains(innerNode) : outerNode.compareDocumentPosition ? !!(outerNode.compareDocumentPosition(innerNode) & 16) : false : false;
      }
      function getActiveElementDeep(containerInfo) {
        containerInfo = null != containerInfo && null != containerInfo.ownerDocument && null != containerInfo.ownerDocument.defaultView ? containerInfo.ownerDocument.defaultView : window;
        for (var element = getActiveElement(containerInfo.document); element instanceof containerInfo.HTMLIFrameElement; ) {
          try {
            var JSCompiler_inline_result = "string" === typeof element.contentWindow.location.href;
          } catch (err) {
            JSCompiler_inline_result = false;
          }
          if (JSCompiler_inline_result) containerInfo = element.contentWindow;
          else break;
          element = getActiveElement(containerInfo.document);
        }
        return element;
      }
      function hasSelectionCapabilities(elem) {
        var nodeName = elem && elem.nodeName && elem.nodeName.toLowerCase();
        return nodeName && ("input" === nodeName && ("text" === elem.type || "search" === elem.type || "tel" === elem.type || "url" === elem.type || "password" === elem.type) || "textarea" === nodeName || "true" === elem.contentEditable);
      }
      function constructSelectEvent(dispatchQueue, nativeEvent, nativeEventTarget) {
        var doc3 = nativeEventTarget.window === nativeEventTarget ? nativeEventTarget.document : 9 === nativeEventTarget.nodeType ? nativeEventTarget : nativeEventTarget.ownerDocument;
        mouseDown || null == activeElement || activeElement !== getActiveElement(doc3) || (doc3 = activeElement, "selectionStart" in doc3 && hasSelectionCapabilities(doc3) ? doc3 = { start: doc3.selectionStart, end: doc3.selectionEnd } : (doc3 = (doc3.ownerDocument && doc3.ownerDocument.defaultView || window).getSelection(), doc3 = {
          anchorNode: doc3.anchorNode,
          anchorOffset: doc3.anchorOffset,
          focusNode: doc3.focusNode,
          focusOffset: doc3.focusOffset
        }), lastSelection && shallowEqual2(lastSelection, doc3) || (lastSelection = doc3, doc3 = accumulateTwoPhaseListeners(activeElementInst, "onSelect"), 0 < doc3.length && (nativeEvent = new SyntheticEvent(
          "onSelect",
          "select",
          null,
          nativeEvent,
          nativeEventTarget
        ), dispatchQueue.push({ event: nativeEvent, listeners: doc3 }), nativeEvent.target = activeElement)));
      }
      function makePrefixMap(styleProp, eventName) {
        var prefixes = {};
        prefixes[styleProp.toLowerCase()] = eventName.toLowerCase();
        prefixes["Webkit" + styleProp] = "webkit" + eventName;
        prefixes["Moz" + styleProp] = "moz" + eventName;
        return prefixes;
      }
      function getVendorPrefixedEventName(eventName) {
        if (prefixedEventNames[eventName]) return prefixedEventNames[eventName];
        if (!vendorPrefixes[eventName]) return eventName;
        var prefixMap = vendorPrefixes[eventName], styleProp;
        for (styleProp in prefixMap)
          if (prefixMap.hasOwnProperty(styleProp) && styleProp in style2)
            return prefixedEventNames[eventName] = prefixMap[styleProp];
        return eventName;
      }
      function registerSimpleEvent(domEventName, reactName) {
        topLevelEventsToReactNames.set(domEventName, reactName);
        registerTwoPhaseEvent(reactName, [domEventName]);
      }
      function getArrayKind(array) {
        for (var kind = EMPTY_ARRAY, i = 0; i < array.length; i++) {
          var value = array[i];
          if ("object" === typeof value && null !== value)
            if (isArrayImpl(value) && 2 === value.length && "string" === typeof value[0]) {
              if (kind !== EMPTY_ARRAY && kind !== ENTRIES_ARRAY)
                return COMPLEX_ARRAY;
              kind = ENTRIES_ARRAY;
            } else return COMPLEX_ARRAY;
          else {
            if ("function" === typeof value || "string" === typeof value && 50 < value.length || kind !== EMPTY_ARRAY && kind !== PRIMITIVE_ARRAY)
              return COMPLEX_ARRAY;
            kind = PRIMITIVE_ARRAY;
          }
        }
        return kind;
      }
      function addObjectToProperties(object, properties, indent, prefix2) {
        for (var key in object)
          hasOwnProperty2.call(object, key) && "_" !== key[0] && addValueToProperties(key, object[key], properties, indent, prefix2);
      }
      function addValueToProperties(propertyName, value, properties, indent, prefix2) {
        switch (typeof value) {
          case "object":
            if (null === value) {
              value = "null";
              break;
            } else {
              if (value.$$typeof === REACT_ELEMENT_TYPE) {
                var typeName2 = getComponentNameFromType(value.type) || "\u2026", key = value.key;
                value = value.props;
                var propsKeys = Object.keys(value), propsLength = propsKeys.length;
                if (null == key && 0 === propsLength) {
                  value = "<" + typeName2 + " />";
                  break;
                }
                if (3 > indent || 1 === propsLength && "children" === propsKeys[0] && null == key) {
                  value = "<" + typeName2 + " \u2026 />";
                  break;
                }
                properties.push([
                  prefix2 + "\xA0\xA0".repeat(indent) + propertyName,
                  "<" + typeName2
                ]);
                null !== key && addValueToProperties(
                  "key",
                  key,
                  properties,
                  indent + 1,
                  prefix2
                );
                propertyName = false;
                for (var propKey in value)
                  "children" === propKey ? null != value.children && (!isArrayImpl(value.children) || 0 < value.children.length) && (propertyName = true) : hasOwnProperty2.call(value, propKey) && "_" !== propKey[0] && addValueToProperties(
                    propKey,
                    value[propKey],
                    properties,
                    indent + 1,
                    prefix2
                  );
                properties.push([
                  "",
                  propertyName ? ">\u2026</" + typeName2 + ">" : "/>"
                ]);
                return;
              }
              typeName2 = Object.prototype.toString.call(value);
              typeName2 = typeName2.slice(8, typeName2.length - 1);
              if ("Array" === typeName2) {
                if (propKey = getArrayKind(value), propKey === PRIMITIVE_ARRAY || propKey === EMPTY_ARRAY) {
                  value = JSON.stringify(value);
                  break;
                } else if (propKey === ENTRIES_ARRAY) {
                  properties.push([
                    prefix2 + "\xA0\xA0".repeat(indent) + propertyName,
                    ""
                  ]);
                  for (propertyName = 0; propertyName < value.length; propertyName++)
                    typeName2 = value[propertyName], addValueToProperties(
                      typeName2[0],
                      typeName2[1],
                      properties,
                      indent + 1,
                      prefix2
                    );
                  return;
                }
              }
              if ("Promise" === typeName2) {
                if ("fulfilled" === value.status) {
                  if (typeName2 = properties.length, addValueToProperties(
                    propertyName,
                    value.value,
                    properties,
                    indent,
                    prefix2
                  ), properties.length > typeName2) {
                    properties = properties[typeName2];
                    properties[1] = "Promise<" + (properties[1] || "Object") + ">";
                    return;
                  }
                } else if ("rejected" === value.status && (typeName2 = properties.length, addValueToProperties(
                  propertyName,
                  value.reason,
                  properties,
                  indent,
                  prefix2
                ), properties.length > typeName2)) {
                  properties = properties[typeName2];
                  properties[1] = "Rejected Promise<" + properties[1] + ">";
                  return;
                }
                properties.push([
                  "\xA0\xA0".repeat(indent) + propertyName,
                  "Promise"
                ]);
                return;
              }
              "Object" === typeName2 && (propKey = Object.getPrototypeOf(value)) && "function" === typeof propKey.constructor && (typeName2 = propKey.constructor.name);
              properties.push([
                prefix2 + "\xA0\xA0".repeat(indent) + propertyName,
                "Object" === typeName2 ? 3 > indent ? "" : "\u2026" : typeName2
              ]);
              3 > indent && addObjectToProperties(value, properties, indent + 1, prefix2);
              return;
            }
          case "function":
            value = "" === value.name ? "() => {}" : value.name + "() {}";
            break;
          case "string":
            value = value === OMITTED_PROP_ERROR ? "\u2026" : JSON.stringify(value);
            break;
          case "undefined":
            value = "undefined";
            break;
          case "boolean":
            value = value ? "true" : "false";
            break;
          default:
            value = String(value);
        }
        properties.push([
          prefix2 + "\xA0\xA0".repeat(indent) + propertyName,
          value
        ]);
      }
      function addObjectDiffToProperties(prev, next, properties, indent) {
        var isDeeplyEqual = true;
        for (key in prev)
          key in next || (properties.push([
            REMOVED + "\xA0\xA0".repeat(indent) + key,
            "\u2026"
          ]), isDeeplyEqual = false);
        for (var _key in next)
          if (_key in prev) {
            var key = prev[_key];
            var nextValue = next[_key];
            if (key !== nextValue) {
              if (0 === indent && "children" === _key)
                isDeeplyEqual = "\xA0\xA0".repeat(indent) + _key, properties.push(
                  [REMOVED + isDeeplyEqual, "\u2026"],
                  [ADDED + isDeeplyEqual, "\u2026"]
                );
              else {
                if (!(3 <= indent)) {
                  if ("object" === typeof key && "object" === typeof nextValue && null !== key && null !== nextValue && key.$$typeof === nextValue.$$typeof)
                    if (nextValue.$$typeof === REACT_ELEMENT_TYPE) {
                      if (key.type === nextValue.type && key.key === nextValue.key) {
                        key = getComponentNameFromType(nextValue.type) || "\u2026";
                        isDeeplyEqual = "\xA0\xA0".repeat(indent) + _key;
                        key = "<" + key + " \u2026 />";
                        properties.push(
                          [REMOVED + isDeeplyEqual, key],
                          [ADDED + isDeeplyEqual, key]
                        );
                        isDeeplyEqual = false;
                        continue;
                      }
                    } else {
                      var prevKind = Object.prototype.toString.call(key), nextKind = Object.prototype.toString.call(nextValue);
                      if (prevKind === nextKind && ("[object Object]" === nextKind || "[object Array]" === nextKind)) {
                        prevKind = [
                          UNCHANGED + "\xA0\xA0".repeat(indent) + _key,
                          "[object Array]" === nextKind ? "Array" : ""
                        ];
                        properties.push(prevKind);
                        nextKind = properties.length;
                        addObjectDiffToProperties(
                          key,
                          nextValue,
                          properties,
                          indent + 1
                        ) ? nextKind === properties.length && (prevKind[1] = "Referentially unequal but deeply equal objects. Consider memoization.") : isDeeplyEqual = false;
                        continue;
                      }
                    }
                  else if ("function" === typeof key && "function" === typeof nextValue && key.name === nextValue.name && key.length === nextValue.length && (prevKind = Function.prototype.toString.call(key), nextKind = Function.prototype.toString.call(nextValue), prevKind === nextKind)) {
                    key = "" === nextValue.name ? "() => {}" : nextValue.name + "() {}";
                    properties.push([
                      UNCHANGED + "\xA0\xA0".repeat(indent) + _key,
                      key + " Referentially unequal function closure. Consider memoization."
                    ]);
                    continue;
                  }
                }
                addValueToProperties(_key, key, properties, indent, REMOVED);
                addValueToProperties(_key, nextValue, properties, indent, ADDED);
              }
              isDeeplyEqual = false;
            }
          } else
            properties.push([
              ADDED + "\xA0\xA0".repeat(indent) + _key,
              "\u2026"
            ]), isDeeplyEqual = false;
        return isDeeplyEqual;
      }
      function setCurrentTrackFromLanes(lanes) {
        currentTrack = lanes & 63 ? "Blocking" : lanes & 64 ? "Gesture" : lanes & 4194176 ? "Transition" : lanes & 62914560 ? "Suspense" : lanes & 2080374784 ? "Idle" : "Other";
      }
      function logComponentTrigger(fiber, startTime, endTime, trigger) {
        supportsUserTiming && (reusableComponentOptions.start = startTime, reusableComponentOptions.end = endTime, reusableComponentDevToolDetails.color = "warning", reusableComponentDevToolDetails.tooltipText = trigger, reusableComponentDevToolDetails.properties = null, (fiber = fiber._debugTask) ? fiber.run(
          performance.measure.bind(
            performance,
            trigger,
            reusableComponentOptions
          )
        ) : performance.measure(trigger, reusableComponentOptions));
      }
      function logComponentReappeared(fiber, startTime, endTime) {
        logComponentTrigger(fiber, startTime, endTime, "Reconnect");
      }
      function logComponentRender(fiber, startTime, endTime, wasHydrated, committedLanes) {
        var name = getComponentNameFromFiber(fiber);
        if (null !== name && supportsUserTiming) {
          var alternate = fiber.alternate, selfTime = fiber.actualDuration;
          if (null === alternate || alternate.child !== fiber.child)
            for (var child = fiber.child; null !== child; child = child.sibling)
              selfTime -= child.actualDuration;
          wasHydrated = 0.5 > selfTime ? wasHydrated ? "tertiary-light" : "primary-light" : 10 > selfTime ? wasHydrated ? "tertiary" : "primary" : 100 > selfTime ? wasHydrated ? "tertiary-dark" : "primary-dark" : "error";
          var props = fiber.memoizedProps;
          selfTime = fiber._debugTask;
          null !== props && null !== alternate && alternate.memoizedProps !== props ? (child = [resuableChangedPropsEntry], props = addObjectDiffToProperties(
            alternate.memoizedProps,
            props,
            child,
            0
          ), 1 < child.length && (props && !alreadyWarnedForDeepEquality && 0 === (alternate.lanes & committedLanes) && 100 < fiber.actualDuration ? (alreadyWarnedForDeepEquality = true, child[0] = reusableDeeplyEqualPropsEntry, reusableComponentDevToolDetails.color = "warning", reusableComponentDevToolDetails.tooltipText = DEEP_EQUALITY_WARNING) : (reusableComponentDevToolDetails.color = wasHydrated, reusableComponentDevToolDetails.tooltipText = name), reusableComponentDevToolDetails.properties = child, reusableComponentOptions.start = startTime, reusableComponentOptions.end = endTime, null != selfTime ? selfTime.run(
            performance.measure.bind(
              performance,
              "\u200B" + name,
              reusableComponentOptions
            )
          ) : performance.measure(
            "\u200B" + name,
            reusableComponentOptions
          ))) : null != selfTime ? selfTime.run(
            console.timeStamp.bind(
              console,
              name,
              startTime,
              endTime,
              COMPONENTS_TRACK,
              void 0,
              wasHydrated
            )
          ) : console.timeStamp(
            name,
            startTime,
            endTime,
            COMPONENTS_TRACK,
            void 0,
            wasHydrated
          );
        }
      }
      function logComponentErrored(fiber, startTime, endTime, errors) {
        if (supportsUserTiming) {
          var name = getComponentNameFromFiber(fiber);
          if (null !== name) {
            for (var debugTask = null, properties = [], i = 0; i < errors.length; i++) {
              var capturedValue = errors[i];
              null == debugTask && null !== capturedValue.source && (debugTask = capturedValue.source._debugTask);
              capturedValue = capturedValue.value;
              properties.push([
                "Error",
                "object" === typeof capturedValue && null !== capturedValue && "string" === typeof capturedValue.message ? String(capturedValue.message) : String(capturedValue)
              ]);
            }
            null !== fiber.key && addValueToProperties("key", fiber.key, properties, 0, "");
            null !== fiber.memoizedProps && addObjectToProperties(fiber.memoizedProps, properties, 0, "");
            null == debugTask && (debugTask = fiber._debugTask);
            fiber = {
              start: startTime,
              end: endTime,
              detail: {
                devtools: {
                  color: "error",
                  track: COMPONENTS_TRACK,
                  tooltipText: 13 === fiber.tag ? "Hydration failed" : "Error boundary caught an error",
                  properties
                }
              }
            };
            debugTask ? debugTask.run(
              performance.measure.bind(performance, "\u200B" + name, fiber)
            ) : performance.measure("\u200B" + name, fiber);
          }
        }
      }
      function logComponentEffect(fiber, startTime, endTime, selfTime, errors) {
        if (null !== errors) {
          if (supportsUserTiming) {
            var name = getComponentNameFromFiber(fiber);
            if (null !== name) {
              selfTime = [];
              for (var i = 0; i < errors.length; i++) {
                var error = errors[i].value;
                selfTime.push([
                  "Error",
                  "object" === typeof error && null !== error && "string" === typeof error.message ? String(error.message) : String(error)
                ]);
              }
              null !== fiber.key && addValueToProperties("key", fiber.key, selfTime, 0, "");
              null !== fiber.memoizedProps && addObjectToProperties(fiber.memoizedProps, selfTime, 0, "");
              startTime = {
                start: startTime,
                end: endTime,
                detail: {
                  devtools: {
                    color: "error",
                    track: COMPONENTS_TRACK,
                    tooltipText: "A lifecycle or effect errored",
                    properties: selfTime
                  }
                }
              };
              (fiber = fiber._debugTask) ? fiber.run(
                performance.measure.bind(
                  performance,
                  "\u200B" + name,
                  startTime
                )
              ) : performance.measure("\u200B" + name, startTime);
            }
          }
        } else
          name = getComponentNameFromFiber(fiber), null !== name && supportsUserTiming && (errors = 1 > selfTime ? "secondary-light" : 100 > selfTime ? "secondary" : 500 > selfTime ? "secondary-dark" : "error", (fiber = fiber._debugTask) ? fiber.run(
            console.timeStamp.bind(
              console,
              name,
              startTime,
              endTime,
              COMPONENTS_TRACK,
              void 0,
              errors
            )
          ) : console.timeStamp(
            name,
            startTime,
            endTime,
            COMPONENTS_TRACK,
            void 0,
            errors
          ));
      }
      function logRenderPhase(startTime, endTime, lanes, debugTask) {
        if (supportsUserTiming && !(endTime <= startTime)) {
          var color = (lanes & 738197653) === lanes ? "tertiary-dark" : "primary-dark";
          lanes = (lanes & 536870912) === lanes ? "Prepared" : (lanes & 201326741) === lanes ? "Hydrated" : "Render";
          debugTask ? debugTask.run(
            console.timeStamp.bind(
              console,
              lanes,
              startTime,
              endTime,
              currentTrack,
              LANES_TRACK_GROUP,
              color
            )
          ) : console.timeStamp(
            lanes,
            startTime,
            endTime,
            currentTrack,
            LANES_TRACK_GROUP,
            color
          );
        }
      }
      function logSuspendedRenderPhase(startTime, endTime, lanes, debugTask) {
        !supportsUserTiming || endTime <= startTime || (lanes = (lanes & 738197653) === lanes ? "tertiary-dark" : "primary-dark", debugTask ? debugTask.run(
          console.timeStamp.bind(
            console,
            "Prewarm",
            startTime,
            endTime,
            currentTrack,
            LANES_TRACK_GROUP,
            lanes
          )
        ) : console.timeStamp(
          "Prewarm",
          startTime,
          endTime,
          currentTrack,
          LANES_TRACK_GROUP,
          lanes
        ));
      }
      function logSuspendedWithDelayPhase(startTime, endTime, lanes, debugTask) {
        !supportsUserTiming || endTime <= startTime || (lanes = (lanes & 738197653) === lanes ? "tertiary-dark" : "primary-dark", debugTask ? debugTask.run(
          console.timeStamp.bind(
            console,
            "Suspended",
            startTime,
            endTime,
            currentTrack,
            LANES_TRACK_GROUP,
            lanes
          )
        ) : console.timeStamp(
          "Suspended",
          startTime,
          endTime,
          currentTrack,
          LANES_TRACK_GROUP,
          lanes
        ));
      }
      function logRecoveredRenderPhase(startTime, endTime, lanes, recoverableErrors, hydrationFailed, debugTask) {
        if (supportsUserTiming && !(endTime <= startTime)) {
          lanes = [];
          for (var i = 0; i < recoverableErrors.length; i++) {
            var error = recoverableErrors[i].value;
            lanes.push([
              "Recoverable Error",
              "object" === typeof error && null !== error && "string" === typeof error.message ? String(error.message) : String(error)
            ]);
          }
          startTime = {
            start: startTime,
            end: endTime,
            detail: {
              devtools: {
                color: "primary-dark",
                track: currentTrack,
                trackGroup: LANES_TRACK_GROUP,
                tooltipText: hydrationFailed ? "Hydration Failed" : "Recovered after Error",
                properties: lanes
              }
            }
          };
          debugTask ? debugTask.run(
            performance.measure.bind(performance, "Recovered", startTime)
          ) : performance.measure("Recovered", startTime);
        }
      }
      function logErroredRenderPhase(startTime, endTime, lanes, debugTask) {
        !supportsUserTiming || endTime <= startTime || (debugTask ? debugTask.run(
          console.timeStamp.bind(
            console,
            "Errored",
            startTime,
            endTime,
            currentTrack,
            LANES_TRACK_GROUP,
            "error"
          )
        ) : console.timeStamp(
          "Errored",
          startTime,
          endTime,
          currentTrack,
          LANES_TRACK_GROUP,
          "error"
        ));
      }
      function logSuspendedCommitPhase(startTime, endTime, reason, debugTask) {
        !supportsUserTiming || endTime <= startTime || (debugTask ? debugTask.run(
          console.timeStamp.bind(
            console,
            reason,
            startTime,
            endTime,
            currentTrack,
            LANES_TRACK_GROUP,
            "secondary-light"
          )
        ) : console.timeStamp(
          reason,
          startTime,
          endTime,
          currentTrack,
          LANES_TRACK_GROUP,
          "secondary-light"
        ));
      }
      function logCommitErrored(startTime, endTime, errors, passive, debugTask) {
        if (supportsUserTiming && !(endTime <= startTime)) {
          for (var properties = [], i = 0; i < errors.length; i++) {
            var error = errors[i].value;
            properties.push([
              "Error",
              "object" === typeof error && null !== error && "string" === typeof error.message ? String(error.message) : String(error)
            ]);
          }
          startTime = {
            start: startTime,
            end: endTime,
            detail: {
              devtools: {
                color: "error",
                track: currentTrack,
                trackGroup: LANES_TRACK_GROUP,
                tooltipText: passive ? "Remaining Effects Errored" : "Commit Errored",
                properties
              }
            }
          };
          debugTask ? debugTask.run(
            performance.measure.bind(performance, "Errored", startTime)
          ) : performance.measure("Errored", startTime);
        }
      }
      function logAnimatingPhase(startTime, endTime, debugTask) {
        !supportsUserTiming || endTime <= startTime || (debugTask ? debugTask.run(
          console.timeStamp.bind(
            console,
            "Animating",
            startTime,
            endTime,
            currentTrack,
            LANES_TRACK_GROUP,
            "secondary-dark"
          )
        ) : console.timeStamp(
          "Animating",
          startTime,
          endTime,
          currentTrack,
          LANES_TRACK_GROUP,
          "secondary-dark"
        ));
      }
      function finishQueueingConcurrentUpdates() {
        for (var endIndex = concurrentQueuesIndex, i = concurrentlyUpdatedLanes = concurrentQueuesIndex = 0; i < endIndex; ) {
          var fiber = concurrentQueues[i];
          concurrentQueues[i++] = null;
          var queue = concurrentQueues[i];
          concurrentQueues[i++] = null;
          var update = concurrentQueues[i];
          concurrentQueues[i++] = null;
          var lane = concurrentQueues[i];
          concurrentQueues[i++] = null;
          if (null !== queue && null !== update) {
            var pending = queue.pending;
            null === pending ? update.next = update : (update.next = pending.next, pending.next = update);
            queue.pending = update;
          }
          0 !== lane && markUpdateLaneFromFiberToRoot(fiber, update, lane);
        }
      }
      function enqueueUpdate$1(fiber, queue, update, lane) {
        concurrentQueues[concurrentQueuesIndex++] = fiber;
        concurrentQueues[concurrentQueuesIndex++] = queue;
        concurrentQueues[concurrentQueuesIndex++] = update;
        concurrentQueues[concurrentQueuesIndex++] = lane;
        concurrentlyUpdatedLanes |= lane;
        fiber.lanes |= lane;
        fiber = fiber.alternate;
        null !== fiber && (fiber.lanes |= lane);
      }
      function enqueueConcurrentHookUpdate(fiber, queue, update, lane) {
        enqueueUpdate$1(fiber, queue, update, lane);
        return getRootForUpdatedFiber(fiber);
      }
      function enqueueConcurrentRenderForLane(fiber, lane) {
        enqueueUpdate$1(fiber, null, null, lane);
        return getRootForUpdatedFiber(fiber);
      }
      function markUpdateLaneFromFiberToRoot(sourceFiber, update, lane) {
        sourceFiber.lanes |= lane;
        var alternate = sourceFiber.alternate;
        null !== alternate && (alternate.lanes |= lane);
        for (var isHidden = false, parent = sourceFiber.return; null !== parent; )
          parent.childLanes |= lane, alternate = parent.alternate, null !== alternate && (alternate.childLanes |= lane), 22 === parent.tag && (sourceFiber = parent.stateNode, null === sourceFiber || sourceFiber._visibility & OffscreenVisible || (isHidden = true)), sourceFiber = parent, parent = parent.return;
        return 3 === sourceFiber.tag ? (parent = sourceFiber.stateNode, isHidden && null !== update && (isHidden = 31 - clz32(lane), sourceFiber = parent.hiddenUpdates, alternate = sourceFiber[isHidden], null === alternate ? sourceFiber[isHidden] = [update] : alternate.push(update), update.lane = lane | 536870912), parent) : null;
      }
      function getRootForUpdatedFiber(sourceFiber) {
        if (nestedUpdateCount > NESTED_UPDATE_LIMIT)
          throw nestedPassiveUpdateCount = nestedUpdateCount = 0, rootWithPassiveNestedUpdates = rootWithNestedUpdates = null, Error(
            "Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops."
          );
        nestedPassiveUpdateCount > NESTED_PASSIVE_UPDATE_LIMIT && (nestedPassiveUpdateCount = 0, rootWithPassiveNestedUpdates = null, console.error(
          "Maximum update depth exceeded. This can happen when a component calls setState inside useEffect, but useEffect either doesn't have a dependency array, or one of the dependencies changes on every render."
        ));
        null === sourceFiber.alternate && 0 !== (sourceFiber.flags & 4098) && warnAboutUpdateOnNotYetMountedFiberInDEV(sourceFiber);
        for (var node = sourceFiber, parent = node.return; null !== parent; )
          null === node.alternate && 0 !== (node.flags & 4098) && warnAboutUpdateOnNotYetMountedFiberInDEV(sourceFiber), node = parent, parent = node.return;
        return 3 === node.tag ? node.stateNode : null;
      }
      function resolveFunctionForHotReloading(type) {
        if (null === resolveFamily) return type;
        var family = resolveFamily(type);
        return void 0 === family ? type : family.current;
      }
      function resolveForwardRefForHotReloading(type) {
        if (null === resolveFamily) return type;
        var family = resolveFamily(type);
        return void 0 === family ? null !== type && void 0 !== type && "function" === typeof type.render && (family = resolveFunctionForHotReloading(type.render), type.render !== family) ? (family = { $$typeof: REACT_FORWARD_REF_TYPE, render: family }, void 0 !== type.displayName && (family.displayName = type.displayName), family) : type : family.current;
      }
      function isCompatibleFamilyForHotReloading(fiber, element) {
        if (null === resolveFamily) return false;
        var prevType = fiber.elementType;
        element = element.type;
        var needsCompareFamilies = false, $$typeofNextType = "object" === typeof element && null !== element ? element.$$typeof : null;
        switch (fiber.tag) {
          case 1:
            "function" === typeof element && (needsCompareFamilies = true);
            break;
          case 0:
            "function" === typeof element ? needsCompareFamilies = true : $$typeofNextType === REACT_LAZY_TYPE && (needsCompareFamilies = true);
            break;
          case 11:
            $$typeofNextType === REACT_FORWARD_REF_TYPE ? needsCompareFamilies = true : $$typeofNextType === REACT_LAZY_TYPE && (needsCompareFamilies = true);
            break;
          case 14:
          case 15:
            $$typeofNextType === REACT_MEMO_TYPE ? needsCompareFamilies = true : $$typeofNextType === REACT_LAZY_TYPE && (needsCompareFamilies = true);
            break;
          default:
            return false;
        }
        return needsCompareFamilies && (fiber = resolveFamily(prevType), void 0 !== fiber && fiber === resolveFamily(element)) ? true : false;
      }
      function markFailedErrorBoundaryForHotReloading(fiber) {
        null !== resolveFamily && "function" === typeof WeakSet && (null === failedBoundaries && (failedBoundaries = /* @__PURE__ */ new WeakSet()), failedBoundaries.add(fiber));
      }
      function scheduleFibersWithFamiliesRecursively(fiber, updatedFamilies, staleFamilies) {
        do {
          var _fiber = fiber, alternate = _fiber.alternate, child = _fiber.child, sibling = _fiber.sibling, tag = _fiber.tag;
          _fiber = _fiber.type;
          var candidateType = null;
          switch (tag) {
            case 0:
            case 15:
            case 1:
              candidateType = _fiber;
              break;
            case 11:
              candidateType = _fiber.render;
          }
          if (null === resolveFamily)
            throw Error("Expected resolveFamily to be set during hot reload.");
          var needsRender = false;
          _fiber = false;
          null !== candidateType && (candidateType = resolveFamily(candidateType), void 0 !== candidateType && (staleFamilies.has(candidateType) ? _fiber = true : updatedFamilies.has(candidateType) && (1 === tag ? _fiber = true : needsRender = true)));
          null !== failedBoundaries && (failedBoundaries.has(fiber) || null !== alternate && failedBoundaries.has(alternate)) && (_fiber = true);
          _fiber && (fiber._debugNeedsRemount = true);
          if (_fiber || needsRender)
            alternate = enqueueConcurrentRenderForLane(fiber, 2), null !== alternate && scheduleUpdateOnFiber(alternate, fiber, 2);
          null === child || _fiber || scheduleFibersWithFamiliesRecursively(
            child,
            updatedFamilies,
            staleFamilies
          );
          if (null === sibling) break;
          fiber = sibling;
        } while (1);
      }
      function FiberNode(tag, pendingProps, key, mode) {
        this.tag = tag;
        this.key = key;
        this.sibling = this.child = this.return = this.stateNode = this.type = this.elementType = null;
        this.index = 0;
        this.refCleanup = this.ref = null;
        this.pendingProps = pendingProps;
        this.dependencies = this.memoizedState = this.updateQueue = this.memoizedProps = null;
        this.mode = mode;
        this.subtreeFlags = this.flags = 0;
        this.deletions = null;
        this.childLanes = this.lanes = 0;
        this.alternate = null;
        this.actualDuration = -0;
        this.actualStartTime = -1.1;
        this.treeBaseDuration = this.selfBaseDuration = -0;
        this._debugTask = this._debugStack = this._debugOwner = this._debugInfo = null;
        this._debugNeedsRemount = false;
        this._debugHookTypes = null;
        hasBadMapPolyfill || "function" !== typeof Object.preventExtensions || Object.preventExtensions(this);
      }
      function shouldConstruct(Component) {
        Component = Component.prototype;
        return !(!Component || !Component.isReactComponent);
      }
      function createWorkInProgress(current2, pendingProps) {
        var workInProgress2 = current2.alternate;
        null === workInProgress2 ? (workInProgress2 = createFiber(
          current2.tag,
          pendingProps,
          current2.key,
          current2.mode
        ), workInProgress2.elementType = current2.elementType, workInProgress2.type = current2.type, workInProgress2.stateNode = current2.stateNode, workInProgress2._debugOwner = current2._debugOwner, workInProgress2._debugStack = current2._debugStack, workInProgress2._debugTask = current2._debugTask, workInProgress2._debugHookTypes = current2._debugHookTypes, workInProgress2.alternate = current2, current2.alternate = workInProgress2) : (workInProgress2.pendingProps = pendingProps, workInProgress2.type = current2.type, workInProgress2.flags = 0, workInProgress2.subtreeFlags = 0, workInProgress2.deletions = null, workInProgress2.actualDuration = -0, workInProgress2.actualStartTime = -1.1);
        workInProgress2.flags = current2.flags & 65011712;
        workInProgress2.childLanes = current2.childLanes;
        workInProgress2.lanes = current2.lanes;
        workInProgress2.child = current2.child;
        workInProgress2.memoizedProps = current2.memoizedProps;
        workInProgress2.memoizedState = current2.memoizedState;
        workInProgress2.updateQueue = current2.updateQueue;
        pendingProps = current2.dependencies;
        workInProgress2.dependencies = null === pendingProps ? null : {
          lanes: pendingProps.lanes,
          firstContext: pendingProps.firstContext,
          _debugThenableState: pendingProps._debugThenableState
        };
        workInProgress2.sibling = current2.sibling;
        workInProgress2.index = current2.index;
        workInProgress2.ref = current2.ref;
        workInProgress2.refCleanup = current2.refCleanup;
        workInProgress2.selfBaseDuration = current2.selfBaseDuration;
        workInProgress2.treeBaseDuration = current2.treeBaseDuration;
        workInProgress2._debugInfo = current2._debugInfo;
        workInProgress2._debugNeedsRemount = current2._debugNeedsRemount;
        switch (workInProgress2.tag) {
          case 0:
          case 15:
            workInProgress2.type = resolveFunctionForHotReloading(current2.type);
            break;
          case 1:
            workInProgress2.type = resolveFunctionForHotReloading(current2.type);
            break;
          case 11:
            workInProgress2.type = resolveForwardRefForHotReloading(current2.type);
        }
        return workInProgress2;
      }
      function resetWorkInProgress(workInProgress2, renderLanes2) {
        workInProgress2.flags &= 65011714;
        var current2 = workInProgress2.alternate;
        null === current2 ? (workInProgress2.childLanes = 0, workInProgress2.lanes = renderLanes2, workInProgress2.child = null, workInProgress2.subtreeFlags = 0, workInProgress2.memoizedProps = null, workInProgress2.memoizedState = null, workInProgress2.updateQueue = null, workInProgress2.dependencies = null, workInProgress2.stateNode = null, workInProgress2.selfBaseDuration = 0, workInProgress2.treeBaseDuration = 0) : (workInProgress2.childLanes = current2.childLanes, workInProgress2.lanes = current2.lanes, workInProgress2.child = current2.child, workInProgress2.subtreeFlags = 0, workInProgress2.deletions = null, workInProgress2.memoizedProps = current2.memoizedProps, workInProgress2.memoizedState = current2.memoizedState, workInProgress2.updateQueue = current2.updateQueue, workInProgress2.type = current2.type, renderLanes2 = current2.dependencies, workInProgress2.dependencies = null === renderLanes2 ? null : {
          lanes: renderLanes2.lanes,
          firstContext: renderLanes2.firstContext,
          _debugThenableState: renderLanes2._debugThenableState
        }, workInProgress2.selfBaseDuration = current2.selfBaseDuration, workInProgress2.treeBaseDuration = current2.treeBaseDuration);
        return workInProgress2;
      }
      function createFiberFromTypeAndProps(type, key, pendingProps, owner, mode, lanes) {
        var fiberTag = 0, resolvedType = type;
        if ("function" === typeof type)
          shouldConstruct(type) && (fiberTag = 1), resolvedType = resolveFunctionForHotReloading(resolvedType);
        else if ("string" === typeof type)
          fiberTag = getHostContext(), fiberTag = isHostHoistableType(type, pendingProps, fiberTag) ? 26 : "html" === type || "head" === type || "body" === type ? 27 : 5;
        else
          a: switch (type) {
            case REACT_ACTIVITY_TYPE:
              return key = createFiber(31, pendingProps, key, mode), key.elementType = REACT_ACTIVITY_TYPE, key.lanes = lanes, key;
            case REACT_FRAGMENT_TYPE:
              return createFiberFromFragment(
                pendingProps.children,
                mode,
                lanes,
                key
              );
            case REACT_STRICT_MODE_TYPE:
              fiberTag = 8;
              mode |= StrictLegacyMode;
              mode |= StrictEffectsMode;
              break;
            case REACT_PROFILER_TYPE:
              return type = pendingProps, owner = mode, "string" !== typeof type.id && console.error(
                'Profiler must specify an "id" of type `string` as a prop. Received the type `%s` instead.',
                typeof type.id
              ), key = createFiber(12, type, key, owner | ProfileMode), key.elementType = REACT_PROFILER_TYPE, key.lanes = lanes, key.stateNode = { effectDuration: 0, passiveEffectDuration: 0 }, key;
            case REACT_SUSPENSE_TYPE:
              return key = createFiber(13, pendingProps, key, mode), key.elementType = REACT_SUSPENSE_TYPE, key.lanes = lanes, key;
            case REACT_SUSPENSE_LIST_TYPE:
              return key = createFiber(19, pendingProps, key, mode), key.elementType = REACT_SUSPENSE_LIST_TYPE, key.lanes = lanes, key;
            default:
              if ("object" === typeof type && null !== type)
                switch (type.$$typeof) {
                  case REACT_CONTEXT_TYPE:
                    fiberTag = 10;
                    break a;
                  case REACT_CONSUMER_TYPE:
                    fiberTag = 9;
                    break a;
                  case REACT_FORWARD_REF_TYPE:
                    fiberTag = 11;
                    resolvedType = resolveForwardRefForHotReloading(resolvedType);
                    break a;
                  case REACT_MEMO_TYPE:
                    fiberTag = 14;
                    break a;
                  case REACT_LAZY_TYPE:
                    fiberTag = 16;
                    resolvedType = null;
                    break a;
                }
              resolvedType = "";
              if (void 0 === type || "object" === typeof type && null !== type && 0 === Object.keys(type).length)
                resolvedType += " You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.";
              null === type ? pendingProps = "null" : isArrayImpl(type) ? pendingProps = "array" : void 0 !== type && type.$$typeof === REACT_ELEMENT_TYPE ? (pendingProps = "<" + (getComponentNameFromType(type.type) || "Unknown") + " />", resolvedType = " Did you accidentally export a JSX literal instead of a component?") : pendingProps = typeof type;
              (fiberTag = owner ? getComponentNameFromOwner(owner) : null) && (resolvedType += "\n\nCheck the render method of `" + fiberTag + "`.");
              fiberTag = 29;
              pendingProps = Error(
                "Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: " + (pendingProps + "." + resolvedType)
              );
              resolvedType = null;
          }
        key = createFiber(fiberTag, pendingProps, key, mode);
        key.elementType = type;
        key.type = resolvedType;
        key.lanes = lanes;
        key._debugOwner = owner;
        return key;
      }
      function createFiberFromElement(element, mode, lanes) {
        mode = createFiberFromTypeAndProps(
          element.type,
          element.key,
          element.props,
          element._owner,
          mode,
          lanes
        );
        mode._debugOwner = element._owner;
        mode._debugStack = element._debugStack;
        mode._debugTask = element._debugTask;
        return mode;
      }
      function createFiberFromFragment(elements, mode, lanes, key) {
        elements = createFiber(7, elements, key, mode);
        elements.lanes = lanes;
        return elements;
      }
      function createFiberFromText(content, mode, lanes) {
        content = createFiber(6, content, null, mode);
        content.lanes = lanes;
        return content;
      }
      function createFiberFromDehydratedFragment(dehydratedNode) {
        var fiber = createFiber(18, null, null, NoMode);
        fiber.stateNode = dehydratedNode;
        return fiber;
      }
      function createFiberFromPortal(portal, mode, lanes) {
        mode = createFiber(
          4,
          null !== portal.children ? portal.children : [],
          portal.key,
          mode
        );
        mode.lanes = lanes;
        mode.stateNode = {
          containerInfo: portal.containerInfo,
          pendingChildren: null,
          implementation: portal.implementation
        };
        return mode;
      }
      function createCapturedValueAtFiber(value, source) {
        if ("object" === typeof value && null !== value) {
          var existing = CapturedStacks.get(value);
          if (void 0 !== existing) return existing;
          source = {
            value,
            source,
            stack: getStackByFiberInDevAndProd(source)
          };
          CapturedStacks.set(value, source);
          return source;
        }
        return {
          value,
          source,
          stack: getStackByFiberInDevAndProd(source)
        };
      }
      function pushTreeFork(workInProgress2, totalChildren) {
        warnIfNotHydrating();
        forkStack[forkStackIndex++] = treeForkCount;
        forkStack[forkStackIndex++] = treeForkProvider;
        treeForkProvider = workInProgress2;
        treeForkCount = totalChildren;
      }
      function pushTreeId(workInProgress2, totalChildren, index) {
        warnIfNotHydrating();
        idStack[idStackIndex++] = treeContextId;
        idStack[idStackIndex++] = treeContextOverflow;
        idStack[idStackIndex++] = treeContextProvider;
        treeContextProvider = workInProgress2;
        var baseIdWithLeadingBit = treeContextId;
        workInProgress2 = treeContextOverflow;
        var baseLength = 32 - clz32(baseIdWithLeadingBit) - 1;
        baseIdWithLeadingBit &= ~(1 << baseLength);
        index += 1;
        var length = 32 - clz32(totalChildren) + baseLength;
        if (30 < length) {
          var numberOfOverflowBits = baseLength - baseLength % 5;
          length = (baseIdWithLeadingBit & (1 << numberOfOverflowBits) - 1).toString(32);
          baseIdWithLeadingBit >>= numberOfOverflowBits;
          baseLength -= numberOfOverflowBits;
          treeContextId = 1 << 32 - clz32(totalChildren) + baseLength | index << baseLength | baseIdWithLeadingBit;
          treeContextOverflow = length + workInProgress2;
        } else
          treeContextId = 1 << length | index << baseLength | baseIdWithLeadingBit, treeContextOverflow = workInProgress2;
      }
      function pushMaterializedTreeId(workInProgress2) {
        warnIfNotHydrating();
        null !== workInProgress2.return && (pushTreeFork(workInProgress2, 1), pushTreeId(workInProgress2, 1, 0));
      }
      function popTreeContext(workInProgress2) {
        for (; workInProgress2 === treeForkProvider; )
          treeForkProvider = forkStack[--forkStackIndex], forkStack[forkStackIndex] = null, treeForkCount = forkStack[--forkStackIndex], forkStack[forkStackIndex] = null;
        for (; workInProgress2 === treeContextProvider; )
          treeContextProvider = idStack[--idStackIndex], idStack[idStackIndex] = null, treeContextOverflow = idStack[--idStackIndex], idStack[idStackIndex] = null, treeContextId = idStack[--idStackIndex], idStack[idStackIndex] = null;
      }
      function getSuspendedTreeContext() {
        warnIfNotHydrating();
        return null !== treeContextProvider ? { id: treeContextId, overflow: treeContextOverflow } : null;
      }
      function restoreSuspendedTreeContext(workInProgress2, suspendedContext) {
        warnIfNotHydrating();
        idStack[idStackIndex++] = treeContextId;
        idStack[idStackIndex++] = treeContextOverflow;
        idStack[idStackIndex++] = treeContextProvider;
        treeContextId = suspendedContext.id;
        treeContextOverflow = suspendedContext.overflow;
        treeContextProvider = workInProgress2;
      }
      function warnIfNotHydrating() {
        isHydrating || console.error(
          "Expected to be hydrating. This is a bug in React. Please file an issue."
        );
      }
      function buildHydrationDiffNode(fiber, distanceFromLeaf) {
        if (null === fiber.return) {
          if (null === hydrationDiffRootDEV)
            hydrationDiffRootDEV = {
              fiber,
              children: [],
              serverProps: void 0,
              serverTail: [],
              distanceFromLeaf
            };
          else {
            if (hydrationDiffRootDEV.fiber !== fiber)
              throw Error(
                "Saw multiple hydration diff roots in a pass. This is a bug in React."
              );
            hydrationDiffRootDEV.distanceFromLeaf > distanceFromLeaf && (hydrationDiffRootDEV.distanceFromLeaf = distanceFromLeaf);
          }
          return hydrationDiffRootDEV;
        }
        var siblings = buildHydrationDiffNode(
          fiber.return,
          distanceFromLeaf + 1
        ).children;
        if (0 < siblings.length && siblings[siblings.length - 1].fiber === fiber)
          return siblings = siblings[siblings.length - 1], siblings.distanceFromLeaf > distanceFromLeaf && (siblings.distanceFromLeaf = distanceFromLeaf), siblings;
        distanceFromLeaf = {
          fiber,
          children: [],
          serverProps: void 0,
          serverTail: [],
          distanceFromLeaf
        };
        siblings.push(distanceFromLeaf);
        return distanceFromLeaf;
      }
      function warnIfHydrating() {
        isHydrating && console.error(
          "We should not be hydrating here. This is a bug in React. Please file a bug."
        );
      }
      function warnNonHydratedInstance(fiber, rejectedCandidate) {
        didSuspendOrErrorDEV || (fiber = buildHydrationDiffNode(fiber, 0), fiber.serverProps = null, null !== rejectedCandidate && (rejectedCandidate = describeHydratableInstanceForDevWarnings(rejectedCandidate), fiber.serverTail.push(rejectedCandidate)));
      }
      function throwOnHydrationMismatch(fiber) {
        var fromText = 1 < arguments.length && void 0 !== arguments[1] ? arguments[1] : false, diff = "", diffRoot = hydrationDiffRootDEV;
        null !== diffRoot && (hydrationDiffRootDEV = null, diff = describeDiff(diffRoot));
        queueHydrationError(
          createCapturedValueAtFiber(
            Error(
              "Hydration failed because the server rendered " + (fromText ? "text" : "HTML") + " didn't match the client. As a result this tree will be regenerated on the client. This can happen if a SSR-ed Client Component used:\n\n- A server/client branch `if (typeof window !== 'undefined')`.\n- Variable input such as `Date.now()` or `Math.random()` which changes each time it's called.\n- Date formatting in a user's locale which doesn't match the server.\n- External changing data without sending a snapshot of it along with the HTML.\n- Invalid HTML tag nesting.\n\nIt can also happen if the client has a browser extension installed which messes with the HTML before React loaded.\n\nhttps://react.dev/link/hydration-mismatch" + diff
            ),
            fiber
          )
        );
        throw HydrationMismatchException;
      }
      function prepareToHydrateHostInstance(fiber) {
        var didHydrate = fiber.stateNode;
        var type = fiber.type, props = fiber.memoizedProps;
        didHydrate[internalInstanceKey] = fiber;
        didHydrate[internalPropsKey] = props;
        validatePropertiesInDevelopment(type, props);
        switch (type) {
          case "dialog":
            listenToNonDelegatedEvent("cancel", didHydrate);
            listenToNonDelegatedEvent("close", didHydrate);
            break;
          case "iframe":
          case "object":
          case "embed":
            listenToNonDelegatedEvent("load", didHydrate);
            break;
          case "video":
          case "audio":
            for (type = 0; type < mediaEventTypes.length; type++)
              listenToNonDelegatedEvent(mediaEventTypes[type], didHydrate);
            break;
          case "source":
            listenToNonDelegatedEvent("error", didHydrate);
            break;
          case "img":
          case "image":
          case "link":
            listenToNonDelegatedEvent("error", didHydrate);
            listenToNonDelegatedEvent("load", didHydrate);
            break;
          case "details":
            listenToNonDelegatedEvent("toggle", didHydrate);
            break;
          case "input":
            checkControlledValueProps("input", props);
            listenToNonDelegatedEvent("invalid", didHydrate);
            validateInputProps(didHydrate, props);
            initInput2(
              didHydrate,
              props.value,
              props.defaultValue,
              props.checked,
              props.defaultChecked,
              props.type,
              props.name,
              true
            );
            break;
          case "option":
            validateOptionProps(didHydrate, props);
            break;
          case "select":
            checkControlledValueProps("select", props);
            listenToNonDelegatedEvent("invalid", didHydrate);
            validateSelectProps(didHydrate, props);
            break;
          case "textarea":
            checkControlledValueProps("textarea", props), listenToNonDelegatedEvent("invalid", didHydrate), validateTextareaProps(didHydrate, props), initTextarea(
              didHydrate,
              props.value,
              props.defaultValue,
              props.children
            );
        }
        type = props.children;
        "string" !== typeof type && "number" !== typeof type && "bigint" !== typeof type || didHydrate.textContent === "" + type || true === props.suppressHydrationWarning || checkForUnmatchedText(didHydrate.textContent, type) ? (null != props.popover && (listenToNonDelegatedEvent("beforetoggle", didHydrate), listenToNonDelegatedEvent("toggle", didHydrate)), null != props.onScroll && listenToNonDelegatedEvent("scroll", didHydrate), null != props.onScrollEnd && listenToNonDelegatedEvent("scrollend", didHydrate), null != props.onClick && (didHydrate.onclick = noop$1), didHydrate = true) : didHydrate = false;
        didHydrate || throwOnHydrationMismatch(fiber, true);
      }
      function popToNextHostParent(fiber) {
        for (hydrationParentFiber = fiber.return; hydrationParentFiber; )
          switch (hydrationParentFiber.tag) {
            case 5:
            case 31:
            case 13:
              rootOrSingletonContext = false;
              return;
            case 27:
            case 3:
              rootOrSingletonContext = true;
              return;
            default:
              hydrationParentFiber = hydrationParentFiber.return;
          }
      }
      function popHydrationState(fiber) {
        if (fiber !== hydrationParentFiber) return false;
        if (!isHydrating)
          return popToNextHostParent(fiber), isHydrating = true, false;
        var tag = fiber.tag, JSCompiler_temp;
        if (JSCompiler_temp = 3 !== tag && 27 !== tag) {
          if (JSCompiler_temp = 5 === tag)
            JSCompiler_temp = fiber.type, JSCompiler_temp = !("form" !== JSCompiler_temp && "button" !== JSCompiler_temp) || shouldSetTextContent(fiber.type, fiber.memoizedProps);
          JSCompiler_temp = !JSCompiler_temp;
        }
        if (JSCompiler_temp && nextHydratableInstance) {
          for (JSCompiler_temp = nextHydratableInstance; JSCompiler_temp; ) {
            var diffNode = buildHydrationDiffNode(fiber, 0), description = describeHydratableInstanceForDevWarnings(JSCompiler_temp);
            diffNode.serverTail.push(description);
            JSCompiler_temp = "Suspense" === description.type ? getNextHydratableInstanceAfterHydrationBoundary(JSCompiler_temp) : getNextHydratable(JSCompiler_temp.nextSibling);
          }
          throwOnHydrationMismatch(fiber);
        }
        popToNextHostParent(fiber);
        if (13 === tag) {
          fiber = fiber.memoizedState;
          fiber = null !== fiber ? fiber.dehydrated : null;
          if (!fiber)
            throw Error(
              "Expected to have a hydrated suspense instance. This error is likely caused by a bug in React. Please file an issue."
            );
          nextHydratableInstance = getNextHydratableInstanceAfterHydrationBoundary(fiber);
        } else if (31 === tag) {
          fiber = fiber.memoizedState;
          fiber = null !== fiber ? fiber.dehydrated : null;
          if (!fiber)
            throw Error(
              "Expected to have a hydrated suspense instance. This error is likely caused by a bug in React. Please file an issue."
            );
          nextHydratableInstance = getNextHydratableInstanceAfterHydrationBoundary(fiber);
        } else
          27 === tag ? (tag = nextHydratableInstance, isSingletonScope(fiber.type) ? (fiber = previousHydratableOnEnteringScopedSingleton, previousHydratableOnEnteringScopedSingleton = null, nextHydratableInstance = fiber) : nextHydratableInstance = tag) : nextHydratableInstance = hydrationParentFiber ? getNextHydratable(fiber.stateNode.nextSibling) : null;
        return true;
      }
      function resetHydrationState() {
        nextHydratableInstance = hydrationParentFiber = null;
        didSuspendOrErrorDEV = isHydrating = false;
      }
      function upgradeHydrationErrorsToRecoverable() {
        var queuedErrors = hydrationErrors;
        null !== queuedErrors && (null === workInProgressRootRecoverableErrors ? workInProgressRootRecoverableErrors = queuedErrors : workInProgressRootRecoverableErrors.push.apply(
          workInProgressRootRecoverableErrors,
          queuedErrors
        ), hydrationErrors = null);
        return queuedErrors;
      }
      function queueHydrationError(error) {
        null === hydrationErrors ? hydrationErrors = [error] : hydrationErrors.push(error);
      }
      function emitPendingHydrationWarnings() {
        var diffRoot = hydrationDiffRootDEV;
        if (null !== diffRoot) {
          hydrationDiffRootDEV = null;
          for (var diff = describeDiff(diffRoot); 0 < diffRoot.children.length; )
            diffRoot = diffRoot.children[0];
          runWithFiberInDEV(diffRoot.fiber, function() {
            console.error(
              "A tree hydrated but some attributes of the server rendered HTML didn't match the client properties. This won't be patched up. This can happen if a SSR-ed Client Component used:\n\n- A server/client branch `if (typeof window !== 'undefined')`.\n- Variable input such as `Date.now()` or `Math.random()` which changes each time it's called.\n- Date formatting in a user's locale which doesn't match the server.\n- External changing data without sending a snapshot of it along with the HTML.\n- Invalid HTML tag nesting.\n\nIt can also happen if the client has a browser extension installed which messes with the HTML before React loaded.\n\n%s%s",
              "https://react.dev/link/hydration-mismatch",
              diff
            );
          });
        }
      }
      function resetContextDependencies() {
        lastContextDependency = currentlyRenderingFiber$1 = null;
        isDisallowedContextReadInDEV = false;
      }
      function pushProvider(providerFiber, context, nextValue) {
        push(valueCursor, context._currentValue, providerFiber);
        context._currentValue = nextValue;
        push(rendererCursorDEV, context._currentRenderer, providerFiber);
        void 0 !== context._currentRenderer && null !== context._currentRenderer && context._currentRenderer !== rendererSigil && console.error(
          "Detected multiple renderers concurrently rendering the same context provider. This is currently unsupported."
        );
        context._currentRenderer = rendererSigil;
      }
      function popProvider(context, providerFiber) {
        context._currentValue = valueCursor.current;
        var currentRenderer = rendererCursorDEV.current;
        pop(rendererCursorDEV, providerFiber);
        context._currentRenderer = currentRenderer;
        pop(valueCursor, providerFiber);
      }
      function scheduleContextWorkOnParentPath(parent, renderLanes2, propagationRoot) {
        for (; null !== parent; ) {
          var alternate = parent.alternate;
          (parent.childLanes & renderLanes2) !== renderLanes2 ? (parent.childLanes |= renderLanes2, null !== alternate && (alternate.childLanes |= renderLanes2)) : null !== alternate && (alternate.childLanes & renderLanes2) !== renderLanes2 && (alternate.childLanes |= renderLanes2);
          if (parent === propagationRoot) break;
          parent = parent.return;
        }
        parent !== propagationRoot && console.error(
          "Expected to find the propagation root when scheduling context work. This error is likely caused by a bug in React. Please file an issue."
        );
      }
      function propagateContextChanges(workInProgress2, contexts, renderLanes2, forcePropagateEntireTree) {
        var fiber = workInProgress2.child;
        null !== fiber && (fiber.return = workInProgress2);
        for (; null !== fiber; ) {
          var list = fiber.dependencies;
          if (null !== list) {
            var nextFiber = fiber.child;
            list = list.firstContext;
            a: for (; null !== list; ) {
              var dependency = list;
              list = fiber;
              for (var i = 0; i < contexts.length; i++)
                if (dependency.context === contexts[i]) {
                  list.lanes |= renderLanes2;
                  dependency = list.alternate;
                  null !== dependency && (dependency.lanes |= renderLanes2);
                  scheduleContextWorkOnParentPath(
                    list.return,
                    renderLanes2,
                    workInProgress2
                  );
                  forcePropagateEntireTree || (nextFiber = null);
                  break a;
                }
              list = dependency.next;
            }
          } else if (18 === fiber.tag) {
            nextFiber = fiber.return;
            if (null === nextFiber)
              throw Error(
                "We just came from a parent so we must have had a parent. This is a bug in React."
              );
            nextFiber.lanes |= renderLanes2;
            list = nextFiber.alternate;
            null !== list && (list.lanes |= renderLanes2);
            scheduleContextWorkOnParentPath(
              nextFiber,
              renderLanes2,
              workInProgress2
            );
            nextFiber = null;
          } else nextFiber = fiber.child;
          if (null !== nextFiber) nextFiber.return = fiber;
          else
            for (nextFiber = fiber; null !== nextFiber; ) {
              if (nextFiber === workInProgress2) {
                nextFiber = null;
                break;
              }
              fiber = nextFiber.sibling;
              if (null !== fiber) {
                fiber.return = nextFiber.return;
                nextFiber = fiber;
                break;
              }
              nextFiber = nextFiber.return;
            }
          fiber = nextFiber;
        }
      }
      function propagateParentContextChanges(current2, workInProgress2, renderLanes2, forcePropagateEntireTree) {
        current2 = null;
        for (var parent = workInProgress2, isInsidePropagationBailout = false; null !== parent; ) {
          if (!isInsidePropagationBailout) {
            if (0 !== (parent.flags & 524288)) isInsidePropagationBailout = true;
            else if (0 !== (parent.flags & 262144)) break;
          }
          if (10 === parent.tag) {
            var currentParent = parent.alternate;
            if (null === currentParent)
              throw Error("Should have a current fiber. This is a bug in React.");
            currentParent = currentParent.memoizedProps;
            if (null !== currentParent) {
              var context = parent.type;
              objectIs(parent.pendingProps.value, currentParent.value) || (null !== current2 ? current2.push(context) : current2 = [context]);
            }
          } else if (parent === hostTransitionProviderCursor.current) {
            currentParent = parent.alternate;
            if (null === currentParent)
              throw Error("Should have a current fiber. This is a bug in React.");
            currentParent.memoizedState.memoizedState !== parent.memoizedState.memoizedState && (null !== current2 ? current2.push(HostTransitionContext) : current2 = [HostTransitionContext]);
          }
          parent = parent.return;
        }
        null !== current2 && propagateContextChanges(
          workInProgress2,
          current2,
          renderLanes2,
          forcePropagateEntireTree
        );
        workInProgress2.flags |= 262144;
      }
      function checkIfContextChanged(currentDependencies) {
        for (currentDependencies = currentDependencies.firstContext; null !== currentDependencies; ) {
          if (!objectIs(
            currentDependencies.context._currentValue,
            currentDependencies.memoizedValue
          ))
            return true;
          currentDependencies = currentDependencies.next;
        }
        return false;
      }
      function prepareToReadContext(workInProgress2) {
        currentlyRenderingFiber$1 = workInProgress2;
        lastContextDependency = null;
        workInProgress2 = workInProgress2.dependencies;
        null !== workInProgress2 && (workInProgress2.firstContext = null);
      }
      function readContext(context) {
        isDisallowedContextReadInDEV && console.error(
          "Context can only be read while React is rendering. In classes, you can read it in the render method or getDerivedStateFromProps. In function components, you can read it directly in the function body, but not inside Hooks like useReducer() or useMemo()."
        );
        return readContextForConsumer(currentlyRenderingFiber$1, context);
      }
      function readContextDuringReconciliation(consumer, context) {
        null === currentlyRenderingFiber$1 && prepareToReadContext(consumer);
        return readContextForConsumer(consumer, context);
      }
      function readContextForConsumer(consumer, context) {
        var value = context._currentValue;
        context = { context, memoizedValue: value, next: null };
        if (null === lastContextDependency) {
          if (null === consumer)
            throw Error(
              "Context can only be read while React is rendering. In classes, you can read it in the render method or getDerivedStateFromProps. In function components, you can read it directly in the function body, but not inside Hooks like useReducer() or useMemo()."
            );
          lastContextDependency = context;
          consumer.dependencies = {
            lanes: 0,
            firstContext: context,
            _debugThenableState: null
          };
          consumer.flags |= 524288;
        } else lastContextDependency = lastContextDependency.next = context;
        return value;
      }
      function createCache() {
        return {
          controller: new AbortControllerLocal(),
          data: /* @__PURE__ */ new Map(),
          refCount: 0
        };
      }
      function retainCache(cache) {
        cache.controller.signal.aborted && console.warn(
          "A cache instance was retained after it was already freed. This likely indicates a bug in React."
        );
        cache.refCount++;
      }
      function releaseCache(cache) {
        cache.refCount--;
        0 > cache.refCount && console.warn(
          "A cache instance was released after it was already freed. This likely indicates a bug in React."
        );
        0 === cache.refCount && scheduleCallback$2(NormalPriority, function() {
          cache.controller.abort();
        });
      }
      function startUpdateTimerByLane(lane, method, fiber) {
        if (0 !== (lane & 127))
          0 > blockingUpdateTime && (blockingUpdateTime = now(), blockingUpdateTask = createTask(method), blockingUpdateMethodName = method, null != fiber && (blockingUpdateComponentName = getComponentNameFromFiber(fiber)), (executionContext & (RenderContext | CommitContext)) !== NoContext && (componentEffectSpawnedUpdate = true, blockingUpdateType = SPAWNED_UPDATE), lane = resolveEventTimeStamp(), method = resolveEventType(), lane !== blockingEventRepeatTime || method !== blockingEventType ? blockingEventRepeatTime = -1.1 : null !== method && (blockingUpdateType = SPAWNED_UPDATE), blockingEventTime = lane, blockingEventType = method);
        else if (0 !== (lane & 4194048) && 0 > transitionUpdateTime && (transitionUpdateTime = now(), transitionUpdateTask = createTask(method), transitionUpdateMethodName = method, null != fiber && (transitionUpdateComponentName = getComponentNameFromFiber(fiber)), 0 > transitionStartTime)) {
          lane = resolveEventTimeStamp();
          method = resolveEventType();
          if (lane !== transitionEventRepeatTime || method !== transitionEventType)
            transitionEventRepeatTime = -1.1;
          transitionEventTime = lane;
          transitionEventType = method;
        }
      }
      function startHostActionTimer(fiber) {
        if (0 > blockingUpdateTime) {
          blockingUpdateTime = now();
          blockingUpdateTask = null != fiber._debugTask ? fiber._debugTask : null;
          (executionContext & (RenderContext | CommitContext)) !== NoContext && (blockingUpdateType = SPAWNED_UPDATE);
          var newEventTime = resolveEventTimeStamp(), newEventType = resolveEventType();
          newEventTime !== blockingEventRepeatTime || newEventType !== blockingEventType ? blockingEventRepeatTime = -1.1 : null !== newEventType && (blockingUpdateType = SPAWNED_UPDATE);
          blockingEventTime = newEventTime;
          blockingEventType = newEventType;
        }
        if (0 > transitionUpdateTime && (transitionUpdateTime = now(), transitionUpdateTask = null != fiber._debugTask ? fiber._debugTask : null, 0 > transitionStartTime)) {
          fiber = resolveEventTimeStamp();
          newEventTime = resolveEventType();
          if (fiber !== transitionEventRepeatTime || newEventTime !== transitionEventType)
            transitionEventRepeatTime = -1.1;
          transitionEventTime = fiber;
          transitionEventType = newEventTime;
        }
      }
      function pushNestedEffectDurations() {
        var prevEffectDuration = profilerEffectDuration;
        profilerEffectDuration = 0;
        return prevEffectDuration;
      }
      function popNestedEffectDurations(prevEffectDuration) {
        var elapsedTime = profilerEffectDuration;
        profilerEffectDuration = prevEffectDuration;
        return elapsedTime;
      }
      function bubbleNestedEffectDurations(prevEffectDuration) {
        var elapsedTime = profilerEffectDuration;
        profilerEffectDuration += prevEffectDuration;
        return elapsedTime;
      }
      function resetComponentEffectTimers() {
        componentEffectEndTime = componentEffectStartTime = -1.1;
      }
      function pushComponentEffectStart() {
        var prevEffectStart = componentEffectStartTime;
        componentEffectStartTime = -1.1;
        return prevEffectStart;
      }
      function popComponentEffectStart(prevEffectStart) {
        0 <= prevEffectStart && (componentEffectStartTime = prevEffectStart);
      }
      function pushComponentEffectDuration() {
        var prevEffectDuration = componentEffectDuration;
        componentEffectDuration = -0;
        return prevEffectDuration;
      }
      function popComponentEffectDuration(prevEffectDuration) {
        0 <= prevEffectDuration && (componentEffectDuration = prevEffectDuration);
      }
      function pushComponentEffectErrors() {
        var prevErrors = componentEffectErrors;
        componentEffectErrors = null;
        return prevErrors;
      }
      function pushComponentEffectDidSpawnUpdate() {
        var prev = componentEffectSpawnedUpdate;
        componentEffectSpawnedUpdate = false;
        return prev;
      }
      function startProfilerTimer(fiber) {
        profilerStartTime = now();
        0 > fiber.actualStartTime && (fiber.actualStartTime = profilerStartTime);
      }
      function stopProfilerTimerIfRunningAndRecordDuration(fiber) {
        if (0 <= profilerStartTime) {
          var elapsedTime = now() - profilerStartTime;
          fiber.actualDuration += elapsedTime;
          fiber.selfBaseDuration = elapsedTime;
          profilerStartTime = -1;
        }
      }
      function stopProfilerTimerIfRunningAndRecordIncompleteDuration(fiber) {
        if (0 <= profilerStartTime) {
          var elapsedTime = now() - profilerStartTime;
          fiber.actualDuration += elapsedTime;
          profilerStartTime = -1;
        }
      }
      function recordEffectDuration() {
        if (0 <= profilerStartTime) {
          var endTime = now(), elapsedTime = endTime - profilerStartTime;
          profilerStartTime = -1;
          profilerEffectDuration += elapsedTime;
          componentEffectDuration += elapsedTime;
          componentEffectEndTime = endTime;
        }
      }
      function recordEffectError(errorInfo) {
        null === componentEffectErrors && (componentEffectErrors = []);
        componentEffectErrors.push(errorInfo);
        null === commitErrors && (commitErrors = []);
        commitErrors.push(errorInfo);
      }
      function startEffectTimer() {
        profilerStartTime = now();
        0 > componentEffectStartTime && (componentEffectStartTime = profilerStartTime);
      }
      function transferActualDuration(fiber) {
        for (var child = fiber.child; child; )
          fiber.actualDuration += child.actualDuration, child = child.sibling;
      }
      function entangleAsyncAction(transition, thenable) {
        if (null === currentEntangledListeners) {
          var entangledListeners = currentEntangledListeners = [];
          currentEntangledPendingCount = 0;
          currentEntangledLane = requestTransitionLane();
          currentEntangledActionThenable = {
            status: "pending",
            value: void 0,
            then: function(resolve) {
              entangledListeners.push(resolve);
            }
          };
        }
        currentEntangledPendingCount++;
        thenable.then(pingEngtangledActionScope, pingEngtangledActionScope);
        return thenable;
      }
      function pingEngtangledActionScope() {
        if (0 === --currentEntangledPendingCount && (-1 < transitionUpdateTime || (transitionStartTime = -1.1), null !== currentEntangledListeners)) {
          null !== currentEntangledActionThenable && (currentEntangledActionThenable.status = "fulfilled");
          var listeners2 = currentEntangledListeners;
          currentEntangledListeners = null;
          currentEntangledLane = 0;
          currentEntangledActionThenable = null;
          for (var i = 0; i < listeners2.length; i++) (0, listeners2[i])();
        }
      }
      function chainThenableValue(thenable, result) {
        var listeners2 = [], thenableWithOverride = {
          status: "pending",
          value: null,
          reason: null,
          then: function(resolve) {
            listeners2.push(resolve);
          }
        };
        thenable.then(
          function() {
            thenableWithOverride.status = "fulfilled";
            thenableWithOverride.value = result;
            for (var i = 0; i < listeners2.length; i++) (0, listeners2[i])(result);
          },
          function(error) {
            thenableWithOverride.status = "rejected";
            thenableWithOverride.reason = error;
            for (error = 0; error < listeners2.length; error++)
              (0, listeners2[error])(void 0);
          }
        );
        return thenableWithOverride;
      }
      function peekCacheFromPool() {
        var cacheResumedFromPreviousRender = resumedCache.current;
        return null !== cacheResumedFromPreviousRender ? cacheResumedFromPreviousRender : workInProgressRoot.pooledCache;
      }
      function pushTransition(offscreenWorkInProgress, prevCachePool) {
        null === prevCachePool ? push(resumedCache, resumedCache.current, offscreenWorkInProgress) : push(resumedCache, prevCachePool.pool, offscreenWorkInProgress);
      }
      function getSuspendedCache() {
        var cacheFromPool = peekCacheFromPool();
        return null === cacheFromPool ? null : { parent: CacheContext._currentValue, pool: cacheFromPool };
      }
      function createThenableState() {
        return { didWarnAboutUncachedPromise: false, thenables: [] };
      }
      function isThenableResolved(thenable) {
        thenable = thenable.status;
        return "fulfilled" === thenable || "rejected" === thenable;
      }
      function trackUsedThenable(thenableState2, thenable, index) {
        null !== ReactSharedInternals.actQueue && (ReactSharedInternals.didUsePromise = true);
        var trackedThenables = thenableState2.thenables;
        index = trackedThenables[index];
        void 0 === index ? trackedThenables.push(thenable) : index !== thenable && (thenableState2.didWarnAboutUncachedPromise || (thenableState2.didWarnAboutUncachedPromise = true, console.error(
          "A component was suspended by an uncached promise. Creating promises inside a Client Component or hook is not yet supported, except via a Suspense-compatible library or framework."
        )), thenable.then(noop$1, noop$1), thenable = index);
        if (void 0 === thenable._debugInfo) {
          thenableState2 = performance.now();
          trackedThenables = thenable.displayName;
          var ioInfo = {
            name: "string" === typeof trackedThenables ? trackedThenables : "Promise",
            start: thenableState2,
            end: thenableState2,
            value: thenable
          };
          thenable._debugInfo = [{ awaited: ioInfo }];
          "fulfilled" !== thenable.status && "rejected" !== thenable.status && (thenableState2 = function() {
            ioInfo.end = performance.now();
          }, thenable.then(thenableState2, thenableState2));
        }
        switch (thenable.status) {
          case "fulfilled":
            return thenable.value;
          case "rejected":
            throw thenableState2 = thenable.reason, checkIfUseWrappedInAsyncCatch(thenableState2), thenableState2;
          default:
            if ("string" === typeof thenable.status)
              thenable.then(noop$1, noop$1);
            else {
              thenableState2 = workInProgressRoot;
              if (null !== thenableState2 && 100 < thenableState2.shellSuspendCounter)
                throw Error(
                  "An unknown Component is an async Client Component. Only Server Components can be async at the moment. This error is often caused by accidentally adding `'use client'` to a module that was originally written for the server."
                );
              thenableState2 = thenable;
              thenableState2.status = "pending";
              thenableState2.then(
                function(fulfilledValue) {
                  if ("pending" === thenable.status) {
                    var fulfilledThenable = thenable;
                    fulfilledThenable.status = "fulfilled";
                    fulfilledThenable.value = fulfilledValue;
                  }
                },
                function(error) {
                  if ("pending" === thenable.status) {
                    var rejectedThenable = thenable;
                    rejectedThenable.status = "rejected";
                    rejectedThenable.reason = error;
                  }
                }
              );
            }
            switch (thenable.status) {
              case "fulfilled":
                return thenable.value;
              case "rejected":
                throw thenableState2 = thenable.reason, checkIfUseWrappedInAsyncCatch(thenableState2), thenableState2;
            }
            suspendedThenable = thenable;
            needsToResetSuspendedThenableDEV = true;
            throw SuspenseException;
        }
      }
      function resolveLazy(lazyType) {
        try {
          return callLazyInitInDEV(lazyType);
        } catch (x5) {
          if (null !== x5 && "object" === typeof x5 && "function" === typeof x5.then)
            throw suspendedThenable = x5, needsToResetSuspendedThenableDEV = true, SuspenseException;
          throw x5;
        }
      }
      function getSuspendedThenable() {
        if (null === suspendedThenable)
          throw Error(
            "Expected a suspended thenable. This is a bug in React. Please file an issue."
          );
        var thenable = suspendedThenable;
        suspendedThenable = null;
        needsToResetSuspendedThenableDEV = false;
        return thenable;
      }
      function checkIfUseWrappedInAsyncCatch(rejectedReason) {
        if (rejectedReason === SuspenseException || rejectedReason === SuspenseActionException)
          throw Error(
            "Hooks are not supported inside an async component. This error is often caused by accidentally adding `'use client'` to a module that was originally written for the server."
          );
      }
      function pushDebugInfo(debugInfo) {
        var previousDebugInfo = currentDebugInfo;
        null != debugInfo && (currentDebugInfo = null === previousDebugInfo ? debugInfo : previousDebugInfo.concat(debugInfo));
        return previousDebugInfo;
      }
      function getCurrentDebugTask() {
        var debugInfo = currentDebugInfo;
        if (null != debugInfo) {
          for (var i = debugInfo.length - 1; 0 <= i; i--)
            if (null != debugInfo[i].name) {
              var debugTask = debugInfo[i].debugTask;
              if (null != debugTask) return debugTask;
            }
        }
        return null;
      }
      function validateFragmentProps(element, fiber, returnFiber) {
        for (var keys3 = Object.keys(element.props), i = 0; i < keys3.length; i++) {
          var key = keys3[i];
          if ("children" !== key && "key" !== key) {
            null === fiber && (fiber = createFiberFromElement(element, returnFiber.mode, 0), fiber._debugInfo = currentDebugInfo, fiber.return = returnFiber);
            runWithFiberInDEV(
              fiber,
              function(erroredKey) {
                console.error(
                  "Invalid prop `%s` supplied to `React.Fragment`. React.Fragment can only have `key` and `children` props.",
                  erroredKey
                );
              },
              key
            );
            break;
          }
        }
      }
      function unwrapThenable(thenable) {
        var index = thenableIndexCounter$1;
        thenableIndexCounter$1 += 1;
        null === thenableState$1 && (thenableState$1 = createThenableState());
        return trackUsedThenable(thenableState$1, thenable, index);
      }
      function coerceRef(workInProgress2, element) {
        element = element.props.ref;
        workInProgress2.ref = void 0 !== element ? element : null;
      }
      function throwOnInvalidObjectTypeImpl(returnFiber, newChild) {
        if (newChild.$$typeof === REACT_LEGACY_ELEMENT_TYPE)
          throw Error(
            'A React Element from an older version of React was rendered. This is not supported. It can happen if:\n- Multiple copies of the "react" package is used.\n- A library pre-bundled an old copy of "react" or "react/jsx-runtime".\n- A compiler tries to "inline" JSX instead of using the runtime.'
          );
        returnFiber = Object.prototype.toString.call(newChild);
        throw Error(
          "Objects are not valid as a React child (found: " + ("[object Object]" === returnFiber ? "object with keys {" + Object.keys(newChild).join(", ") + "}" : returnFiber) + "). If you meant to render a collection of children, use an array instead."
        );
      }
      function throwOnInvalidObjectType(returnFiber, newChild) {
        var debugTask = getCurrentDebugTask();
        null !== debugTask ? debugTask.run(
          throwOnInvalidObjectTypeImpl.bind(null, returnFiber, newChild)
        ) : throwOnInvalidObjectTypeImpl(returnFiber, newChild);
      }
      function warnOnFunctionTypeImpl(returnFiber, invalidChild) {
        var parentName = getComponentNameFromFiber(returnFiber) || "Component";
        ownerHasFunctionTypeWarning[parentName] || (ownerHasFunctionTypeWarning[parentName] = true, invalidChild = invalidChild.displayName || invalidChild.name || "Component", 3 === returnFiber.tag ? console.error(
          "Functions are not valid as a React child. This may happen if you return %s instead of <%s /> from render. Or maybe you meant to call this function rather than return it.\n  root.render(%s)",
          invalidChild,
          invalidChild,
          invalidChild
        ) : console.error(
          "Functions are not valid as a React child. This may happen if you return %s instead of <%s /> from render. Or maybe you meant to call this function rather than return it.\n  <%s>{%s}</%s>",
          invalidChild,
          invalidChild,
          parentName,
          invalidChild,
          parentName
        ));
      }
      function warnOnFunctionType(returnFiber, invalidChild) {
        var debugTask = getCurrentDebugTask();
        null !== debugTask ? debugTask.run(
          warnOnFunctionTypeImpl.bind(null, returnFiber, invalidChild)
        ) : warnOnFunctionTypeImpl(returnFiber, invalidChild);
      }
      function warnOnSymbolTypeImpl(returnFiber, invalidChild) {
        var parentName = getComponentNameFromFiber(returnFiber) || "Component";
        ownerHasSymbolTypeWarning[parentName] || (ownerHasSymbolTypeWarning[parentName] = true, invalidChild = String(invalidChild), 3 === returnFiber.tag ? console.error(
          "Symbols are not valid as a React child.\n  root.render(%s)",
          invalidChild
        ) : console.error(
          "Symbols are not valid as a React child.\n  <%s>%s</%s>",
          parentName,
          invalidChild,
          parentName
        ));
      }
      function warnOnSymbolType(returnFiber, invalidChild) {
        var debugTask = getCurrentDebugTask();
        null !== debugTask ? debugTask.run(
          warnOnSymbolTypeImpl.bind(null, returnFiber, invalidChild)
        ) : warnOnSymbolTypeImpl(returnFiber, invalidChild);
      }
      function createChildReconciler(shouldTrackSideEffects) {
        function deleteChild(returnFiber, childToDelete) {
          if (shouldTrackSideEffects) {
            var deletions = returnFiber.deletions;
            null === deletions ? (returnFiber.deletions = [childToDelete], returnFiber.flags |= 16) : deletions.push(childToDelete);
          }
        }
        function deleteRemainingChildren(returnFiber, currentFirstChild) {
          if (!shouldTrackSideEffects) return null;
          for (; null !== currentFirstChild; )
            deleteChild(returnFiber, currentFirstChild), currentFirstChild = currentFirstChild.sibling;
          return null;
        }
        function mapRemainingChildren(currentFirstChild) {
          for (var existingChildren = /* @__PURE__ */ new Map(); null !== currentFirstChild; )
            null !== currentFirstChild.key ? existingChildren.set(currentFirstChild.key, currentFirstChild) : existingChildren.set(currentFirstChild.index, currentFirstChild), currentFirstChild = currentFirstChild.sibling;
          return existingChildren;
        }
        function useFiber(fiber, pendingProps) {
          fiber = createWorkInProgress(fiber, pendingProps);
          fiber.index = 0;
          fiber.sibling = null;
          return fiber;
        }
        function placeChild(newFiber, lastPlacedIndex, newIndex) {
          newFiber.index = newIndex;
          if (!shouldTrackSideEffects)
            return newFiber.flags |= 1048576, lastPlacedIndex;
          newIndex = newFiber.alternate;
          if (null !== newIndex)
            return newIndex = newIndex.index, newIndex < lastPlacedIndex ? (newFiber.flags |= 67108866, lastPlacedIndex) : newIndex;
          newFiber.flags |= 67108866;
          return lastPlacedIndex;
        }
        function placeSingleChild(newFiber) {
          shouldTrackSideEffects && null === newFiber.alternate && (newFiber.flags |= 67108866);
          return newFiber;
        }
        function updateTextNode(returnFiber, current2, textContent, lanes) {
          if (null === current2 || 6 !== current2.tag)
            return current2 = createFiberFromText(
              textContent,
              returnFiber.mode,
              lanes
            ), current2.return = returnFiber, current2._debugOwner = returnFiber, current2._debugTask = returnFiber._debugTask, current2._debugInfo = currentDebugInfo, current2;
          current2 = useFiber(current2, textContent);
          current2.return = returnFiber;
          current2._debugInfo = currentDebugInfo;
          return current2;
        }
        function updateElement(returnFiber, current2, element, lanes) {
          var elementType = element.type;
          if (elementType === REACT_FRAGMENT_TYPE)
            return current2 = updateFragment(
              returnFiber,
              current2,
              element.props.children,
              lanes,
              element.key
            ), validateFragmentProps(element, current2, returnFiber), current2;
          if (null !== current2 && (current2.elementType === elementType || isCompatibleFamilyForHotReloading(current2, element) || "object" === typeof elementType && null !== elementType && elementType.$$typeof === REACT_LAZY_TYPE && resolveLazy(elementType) === current2.type))
            return current2 = useFiber(current2, element.props), coerceRef(current2, element), current2.return = returnFiber, current2._debugOwner = element._owner, current2._debugInfo = currentDebugInfo, current2;
          current2 = createFiberFromElement(element, returnFiber.mode, lanes);
          coerceRef(current2, element);
          current2.return = returnFiber;
          current2._debugInfo = currentDebugInfo;
          return current2;
        }
        function updatePortal(returnFiber, current2, portal, lanes) {
          if (null === current2 || 4 !== current2.tag || current2.stateNode.containerInfo !== portal.containerInfo || current2.stateNode.implementation !== portal.implementation)
            return current2 = createFiberFromPortal(portal, returnFiber.mode, lanes), current2.return = returnFiber, current2._debugInfo = currentDebugInfo, current2;
          current2 = useFiber(current2, portal.children || []);
          current2.return = returnFiber;
          current2._debugInfo = currentDebugInfo;
          return current2;
        }
        function updateFragment(returnFiber, current2, fragment, lanes, key) {
          if (null === current2 || 7 !== current2.tag)
            return current2 = createFiberFromFragment(
              fragment,
              returnFiber.mode,
              lanes,
              key
            ), current2.return = returnFiber, current2._debugOwner = returnFiber, current2._debugTask = returnFiber._debugTask, current2._debugInfo = currentDebugInfo, current2;
          current2 = useFiber(current2, fragment);
          current2.return = returnFiber;
          current2._debugInfo = currentDebugInfo;
          return current2;
        }
        function createChild(returnFiber, newChild, lanes) {
          if ("string" === typeof newChild && "" !== newChild || "number" === typeof newChild || "bigint" === typeof newChild)
            return newChild = createFiberFromText(
              "" + newChild,
              returnFiber.mode,
              lanes
            ), newChild.return = returnFiber, newChild._debugOwner = returnFiber, newChild._debugTask = returnFiber._debugTask, newChild._debugInfo = currentDebugInfo, newChild;
          if ("object" === typeof newChild && null !== newChild) {
            switch (newChild.$$typeof) {
              case REACT_ELEMENT_TYPE:
                return lanes = createFiberFromElement(
                  newChild,
                  returnFiber.mode,
                  lanes
                ), coerceRef(lanes, newChild), lanes.return = returnFiber, returnFiber = pushDebugInfo(newChild._debugInfo), lanes._debugInfo = currentDebugInfo, currentDebugInfo = returnFiber, lanes;
              case REACT_PORTAL_TYPE:
                return newChild = createFiberFromPortal(
                  newChild,
                  returnFiber.mode,
                  lanes
                ), newChild.return = returnFiber, newChild._debugInfo = currentDebugInfo, newChild;
              case REACT_LAZY_TYPE:
                var _prevDebugInfo = pushDebugInfo(newChild._debugInfo);
                newChild = resolveLazy(newChild);
                returnFiber = createChild(returnFiber, newChild, lanes);
                currentDebugInfo = _prevDebugInfo;
                return returnFiber;
            }
            if (isArrayImpl(newChild) || getIteratorFn(newChild))
              return lanes = createFiberFromFragment(
                newChild,
                returnFiber.mode,
                lanes,
                null
              ), lanes.return = returnFiber, lanes._debugOwner = returnFiber, lanes._debugTask = returnFiber._debugTask, returnFiber = pushDebugInfo(newChild._debugInfo), lanes._debugInfo = currentDebugInfo, currentDebugInfo = returnFiber, lanes;
            if ("function" === typeof newChild.then)
              return _prevDebugInfo = pushDebugInfo(newChild._debugInfo), returnFiber = createChild(
                returnFiber,
                unwrapThenable(newChild),
                lanes
              ), currentDebugInfo = _prevDebugInfo, returnFiber;
            if (newChild.$$typeof === REACT_CONTEXT_TYPE)
              return createChild(
                returnFiber,
                readContextDuringReconciliation(returnFiber, newChild),
                lanes
              );
            throwOnInvalidObjectType(returnFiber, newChild);
          }
          "function" === typeof newChild && warnOnFunctionType(returnFiber, newChild);
          "symbol" === typeof newChild && warnOnSymbolType(returnFiber, newChild);
          return null;
        }
        function updateSlot(returnFiber, oldFiber, newChild, lanes) {
          var key = null !== oldFiber ? oldFiber.key : null;
          if ("string" === typeof newChild && "" !== newChild || "number" === typeof newChild || "bigint" === typeof newChild)
            return null !== key ? null : updateTextNode(returnFiber, oldFiber, "" + newChild, lanes);
          if ("object" === typeof newChild && null !== newChild) {
            switch (newChild.$$typeof) {
              case REACT_ELEMENT_TYPE:
                return newChild.key === key ? (key = pushDebugInfo(newChild._debugInfo), returnFiber = updateElement(
                  returnFiber,
                  oldFiber,
                  newChild,
                  lanes
                ), currentDebugInfo = key, returnFiber) : null;
              case REACT_PORTAL_TYPE:
                return newChild.key === key ? updatePortal(returnFiber, oldFiber, newChild, lanes) : null;
              case REACT_LAZY_TYPE:
                return key = pushDebugInfo(newChild._debugInfo), newChild = resolveLazy(newChild), returnFiber = updateSlot(
                  returnFiber,
                  oldFiber,
                  newChild,
                  lanes
                ), currentDebugInfo = key, returnFiber;
            }
            if (isArrayImpl(newChild) || getIteratorFn(newChild)) {
              if (null !== key) return null;
              key = pushDebugInfo(newChild._debugInfo);
              returnFiber = updateFragment(
                returnFiber,
                oldFiber,
                newChild,
                lanes,
                null
              );
              currentDebugInfo = key;
              return returnFiber;
            }
            if ("function" === typeof newChild.then)
              return key = pushDebugInfo(newChild._debugInfo), returnFiber = updateSlot(
                returnFiber,
                oldFiber,
                unwrapThenable(newChild),
                lanes
              ), currentDebugInfo = key, returnFiber;
            if (newChild.$$typeof === REACT_CONTEXT_TYPE)
              return updateSlot(
                returnFiber,
                oldFiber,
                readContextDuringReconciliation(returnFiber, newChild),
                lanes
              );
            throwOnInvalidObjectType(returnFiber, newChild);
          }
          "function" === typeof newChild && warnOnFunctionType(returnFiber, newChild);
          "symbol" === typeof newChild && warnOnSymbolType(returnFiber, newChild);
          return null;
        }
        function updateFromMap(existingChildren, returnFiber, newIdx, newChild, lanes) {
          if ("string" === typeof newChild && "" !== newChild || "number" === typeof newChild || "bigint" === typeof newChild)
            return existingChildren = existingChildren.get(newIdx) || null, updateTextNode(returnFiber, existingChildren, "" + newChild, lanes);
          if ("object" === typeof newChild && null !== newChild) {
            switch (newChild.$$typeof) {
              case REACT_ELEMENT_TYPE:
                return newIdx = existingChildren.get(
                  null === newChild.key ? newIdx : newChild.key
                ) || null, existingChildren = pushDebugInfo(newChild._debugInfo), returnFiber = updateElement(
                  returnFiber,
                  newIdx,
                  newChild,
                  lanes
                ), currentDebugInfo = existingChildren, returnFiber;
              case REACT_PORTAL_TYPE:
                return existingChildren = existingChildren.get(
                  null === newChild.key ? newIdx : newChild.key
                ) || null, updatePortal(returnFiber, existingChildren, newChild, lanes);
              case REACT_LAZY_TYPE:
                var _prevDebugInfo7 = pushDebugInfo(newChild._debugInfo);
                newChild = resolveLazy(newChild);
                returnFiber = updateFromMap(
                  existingChildren,
                  returnFiber,
                  newIdx,
                  newChild,
                  lanes
                );
                currentDebugInfo = _prevDebugInfo7;
                return returnFiber;
            }
            if (isArrayImpl(newChild) || getIteratorFn(newChild))
              return newIdx = existingChildren.get(newIdx) || null, existingChildren = pushDebugInfo(newChild._debugInfo), returnFiber = updateFragment(
                returnFiber,
                newIdx,
                newChild,
                lanes,
                null
              ), currentDebugInfo = existingChildren, returnFiber;
            if ("function" === typeof newChild.then)
              return _prevDebugInfo7 = pushDebugInfo(newChild._debugInfo), returnFiber = updateFromMap(
                existingChildren,
                returnFiber,
                newIdx,
                unwrapThenable(newChild),
                lanes
              ), currentDebugInfo = _prevDebugInfo7, returnFiber;
            if (newChild.$$typeof === REACT_CONTEXT_TYPE)
              return updateFromMap(
                existingChildren,
                returnFiber,
                newIdx,
                readContextDuringReconciliation(returnFiber, newChild),
                lanes
              );
            throwOnInvalidObjectType(returnFiber, newChild);
          }
          "function" === typeof newChild && warnOnFunctionType(returnFiber, newChild);
          "symbol" === typeof newChild && warnOnSymbolType(returnFiber, newChild);
          return null;
        }
        function warnOnInvalidKey(returnFiber, workInProgress2, child, knownKeys) {
          if ("object" !== typeof child || null === child) return knownKeys;
          switch (child.$$typeof) {
            case REACT_ELEMENT_TYPE:
            case REACT_PORTAL_TYPE:
              warnForMissingKey(returnFiber, workInProgress2, child);
              var key = child.key;
              if ("string" !== typeof key) break;
              if (null === knownKeys) {
                knownKeys = /* @__PURE__ */ new Set();
                knownKeys.add(key);
                break;
              }
              if (!knownKeys.has(key)) {
                knownKeys.add(key);
                break;
              }
              runWithFiberInDEV(workInProgress2, function() {
                console.error(
                  "Encountered two children with the same key, `%s`. Keys should be unique so that components maintain their identity across updates. Non-unique keys may cause children to be duplicated and/or omitted \u2014 the behavior is unsupported and could change in a future version.",
                  key
                );
              });
              break;
            case REACT_LAZY_TYPE:
              child = resolveLazy(child), warnOnInvalidKey(returnFiber, workInProgress2, child, knownKeys);
          }
          return knownKeys;
        }
        function reconcileChildrenArray(returnFiber, currentFirstChild, newChildren, lanes) {
          for (var knownKeys = null, resultingFirstChild = null, previousNewFiber = null, oldFiber = currentFirstChild, newIdx = currentFirstChild = 0, nextOldFiber = null; null !== oldFiber && newIdx < newChildren.length; newIdx++) {
            oldFiber.index > newIdx ? (nextOldFiber = oldFiber, oldFiber = null) : nextOldFiber = oldFiber.sibling;
            var newFiber = updateSlot(
              returnFiber,
              oldFiber,
              newChildren[newIdx],
              lanes
            );
            if (null === newFiber) {
              null === oldFiber && (oldFiber = nextOldFiber);
              break;
            }
            knownKeys = warnOnInvalidKey(
              returnFiber,
              newFiber,
              newChildren[newIdx],
              knownKeys
            );
            shouldTrackSideEffects && oldFiber && null === newFiber.alternate && deleteChild(returnFiber, oldFiber);
            currentFirstChild = placeChild(newFiber, currentFirstChild, newIdx);
            null === previousNewFiber ? resultingFirstChild = newFiber : previousNewFiber.sibling = newFiber;
            previousNewFiber = newFiber;
            oldFiber = nextOldFiber;
          }
          if (newIdx === newChildren.length)
            return deleteRemainingChildren(returnFiber, oldFiber), isHydrating && pushTreeFork(returnFiber, newIdx), resultingFirstChild;
          if (null === oldFiber) {
            for (; newIdx < newChildren.length; newIdx++)
              oldFiber = createChild(returnFiber, newChildren[newIdx], lanes), null !== oldFiber && (knownKeys = warnOnInvalidKey(
                returnFiber,
                oldFiber,
                newChildren[newIdx],
                knownKeys
              ), currentFirstChild = placeChild(
                oldFiber,
                currentFirstChild,
                newIdx
              ), null === previousNewFiber ? resultingFirstChild = oldFiber : previousNewFiber.sibling = oldFiber, previousNewFiber = oldFiber);
            isHydrating && pushTreeFork(returnFiber, newIdx);
            return resultingFirstChild;
          }
          for (oldFiber = mapRemainingChildren(oldFiber); newIdx < newChildren.length; newIdx++)
            nextOldFiber = updateFromMap(
              oldFiber,
              returnFiber,
              newIdx,
              newChildren[newIdx],
              lanes
            ), null !== nextOldFiber && (knownKeys = warnOnInvalidKey(
              returnFiber,
              nextOldFiber,
              newChildren[newIdx],
              knownKeys
            ), shouldTrackSideEffects && null !== nextOldFiber.alternate && oldFiber.delete(
              null === nextOldFiber.key ? newIdx : nextOldFiber.key
            ), currentFirstChild = placeChild(
              nextOldFiber,
              currentFirstChild,
              newIdx
            ), null === previousNewFiber ? resultingFirstChild = nextOldFiber : previousNewFiber.sibling = nextOldFiber, previousNewFiber = nextOldFiber);
          shouldTrackSideEffects && oldFiber.forEach(function(child) {
            return deleteChild(returnFiber, child);
          });
          isHydrating && pushTreeFork(returnFiber, newIdx);
          return resultingFirstChild;
        }
        function reconcileChildrenIterator(returnFiber, currentFirstChild, newChildren, lanes) {
          if (null == newChildren)
            throw Error("An iterable object provided no iterator.");
          for (var resultingFirstChild = null, previousNewFiber = null, oldFiber = currentFirstChild, newIdx = currentFirstChild = 0, nextOldFiber = null, knownKeys = null, step = newChildren.next(); null !== oldFiber && !step.done; newIdx++, step = newChildren.next()) {
            oldFiber.index > newIdx ? (nextOldFiber = oldFiber, oldFiber = null) : nextOldFiber = oldFiber.sibling;
            var newFiber = updateSlot(returnFiber, oldFiber, step.value, lanes);
            if (null === newFiber) {
              null === oldFiber && (oldFiber = nextOldFiber);
              break;
            }
            knownKeys = warnOnInvalidKey(
              returnFiber,
              newFiber,
              step.value,
              knownKeys
            );
            shouldTrackSideEffects && oldFiber && null === newFiber.alternate && deleteChild(returnFiber, oldFiber);
            currentFirstChild = placeChild(newFiber, currentFirstChild, newIdx);
            null === previousNewFiber ? resultingFirstChild = newFiber : previousNewFiber.sibling = newFiber;
            previousNewFiber = newFiber;
            oldFiber = nextOldFiber;
          }
          if (step.done)
            return deleteRemainingChildren(returnFiber, oldFiber), isHydrating && pushTreeFork(returnFiber, newIdx), resultingFirstChild;
          if (null === oldFiber) {
            for (; !step.done; newIdx++, step = newChildren.next())
              oldFiber = createChild(returnFiber, step.value, lanes), null !== oldFiber && (knownKeys = warnOnInvalidKey(
                returnFiber,
                oldFiber,
                step.value,
                knownKeys
              ), currentFirstChild = placeChild(
                oldFiber,
                currentFirstChild,
                newIdx
              ), null === previousNewFiber ? resultingFirstChild = oldFiber : previousNewFiber.sibling = oldFiber, previousNewFiber = oldFiber);
            isHydrating && pushTreeFork(returnFiber, newIdx);
            return resultingFirstChild;
          }
          for (oldFiber = mapRemainingChildren(oldFiber); !step.done; newIdx++, step = newChildren.next())
            nextOldFiber = updateFromMap(
              oldFiber,
              returnFiber,
              newIdx,
              step.value,
              lanes
            ), null !== nextOldFiber && (knownKeys = warnOnInvalidKey(
              returnFiber,
              nextOldFiber,
              step.value,
              knownKeys
            ), shouldTrackSideEffects && null !== nextOldFiber.alternate && oldFiber.delete(
              null === nextOldFiber.key ? newIdx : nextOldFiber.key
            ), currentFirstChild = placeChild(
              nextOldFiber,
              currentFirstChild,
              newIdx
            ), null === previousNewFiber ? resultingFirstChild = nextOldFiber : previousNewFiber.sibling = nextOldFiber, previousNewFiber = nextOldFiber);
          shouldTrackSideEffects && oldFiber.forEach(function(child) {
            return deleteChild(returnFiber, child);
          });
          isHydrating && pushTreeFork(returnFiber, newIdx);
          return resultingFirstChild;
        }
        function reconcileChildFibersImpl(returnFiber, currentFirstChild, newChild, lanes) {
          "object" === typeof newChild && null !== newChild && newChild.type === REACT_FRAGMENT_TYPE && null === newChild.key && (validateFragmentProps(newChild, null, returnFiber), newChild = newChild.props.children);
          if ("object" === typeof newChild && null !== newChild) {
            switch (newChild.$$typeof) {
              case REACT_ELEMENT_TYPE:
                var prevDebugInfo = pushDebugInfo(newChild._debugInfo);
                a: {
                  for (var key = newChild.key; null !== currentFirstChild; ) {
                    if (currentFirstChild.key === key) {
                      key = newChild.type;
                      if (key === REACT_FRAGMENT_TYPE) {
                        if (7 === currentFirstChild.tag) {
                          deleteRemainingChildren(
                            returnFiber,
                            currentFirstChild.sibling
                          );
                          lanes = useFiber(
                            currentFirstChild,
                            newChild.props.children
                          );
                          lanes.return = returnFiber;
                          lanes._debugOwner = newChild._owner;
                          lanes._debugInfo = currentDebugInfo;
                          validateFragmentProps(newChild, lanes, returnFiber);
                          returnFiber = lanes;
                          break a;
                        }
                      } else if (currentFirstChild.elementType === key || isCompatibleFamilyForHotReloading(
                        currentFirstChild,
                        newChild
                      ) || "object" === typeof key && null !== key && key.$$typeof === REACT_LAZY_TYPE && resolveLazy(key) === currentFirstChild.type) {
                        deleteRemainingChildren(
                          returnFiber,
                          currentFirstChild.sibling
                        );
                        lanes = useFiber(currentFirstChild, newChild.props);
                        coerceRef(lanes, newChild);
                        lanes.return = returnFiber;
                        lanes._debugOwner = newChild._owner;
                        lanes._debugInfo = currentDebugInfo;
                        returnFiber = lanes;
                        break a;
                      }
                      deleteRemainingChildren(returnFiber, currentFirstChild);
                      break;
                    } else deleteChild(returnFiber, currentFirstChild);
                    currentFirstChild = currentFirstChild.sibling;
                  }
                  newChild.type === REACT_FRAGMENT_TYPE ? (lanes = createFiberFromFragment(
                    newChild.props.children,
                    returnFiber.mode,
                    lanes,
                    newChild.key
                  ), lanes.return = returnFiber, lanes._debugOwner = returnFiber, lanes._debugTask = returnFiber._debugTask, lanes._debugInfo = currentDebugInfo, validateFragmentProps(newChild, lanes, returnFiber), returnFiber = lanes) : (lanes = createFiberFromElement(
                    newChild,
                    returnFiber.mode,
                    lanes
                  ), coerceRef(lanes, newChild), lanes.return = returnFiber, lanes._debugInfo = currentDebugInfo, returnFiber = lanes);
                }
                returnFiber = placeSingleChild(returnFiber);
                currentDebugInfo = prevDebugInfo;
                return returnFiber;
              case REACT_PORTAL_TYPE:
                a: {
                  prevDebugInfo = newChild;
                  for (newChild = prevDebugInfo.key; null !== currentFirstChild; ) {
                    if (currentFirstChild.key === newChild)
                      if (4 === currentFirstChild.tag && currentFirstChild.stateNode.containerInfo === prevDebugInfo.containerInfo && currentFirstChild.stateNode.implementation === prevDebugInfo.implementation) {
                        deleteRemainingChildren(
                          returnFiber,
                          currentFirstChild.sibling
                        );
                        lanes = useFiber(
                          currentFirstChild,
                          prevDebugInfo.children || []
                        );
                        lanes.return = returnFiber;
                        returnFiber = lanes;
                        break a;
                      } else {
                        deleteRemainingChildren(returnFiber, currentFirstChild);
                        break;
                      }
                    else deleteChild(returnFiber, currentFirstChild);
                    currentFirstChild = currentFirstChild.sibling;
                  }
                  lanes = createFiberFromPortal(
                    prevDebugInfo,
                    returnFiber.mode,
                    lanes
                  );
                  lanes.return = returnFiber;
                  returnFiber = lanes;
                }
                return placeSingleChild(returnFiber);
              case REACT_LAZY_TYPE:
                return prevDebugInfo = pushDebugInfo(newChild._debugInfo), newChild = resolveLazy(newChild), returnFiber = reconcileChildFibersImpl(
                  returnFiber,
                  currentFirstChild,
                  newChild,
                  lanes
                ), currentDebugInfo = prevDebugInfo, returnFiber;
            }
            if (isArrayImpl(newChild))
              return prevDebugInfo = pushDebugInfo(newChild._debugInfo), returnFiber = reconcileChildrenArray(
                returnFiber,
                currentFirstChild,
                newChild,
                lanes
              ), currentDebugInfo = prevDebugInfo, returnFiber;
            if (getIteratorFn(newChild)) {
              prevDebugInfo = pushDebugInfo(newChild._debugInfo);
              key = getIteratorFn(newChild);
              if ("function" !== typeof key)
                throw Error(
                  "An object is not an iterable. This error is likely caused by a bug in React. Please file an issue."
                );
              var newChildren = key.call(newChild);
              if (newChildren === newChild) {
                if (0 !== returnFiber.tag || "[object GeneratorFunction]" !== Object.prototype.toString.call(returnFiber.type) || "[object Generator]" !== Object.prototype.toString.call(newChildren))
                  didWarnAboutGenerators || console.error(
                    "Using Iterators as children is unsupported and will likely yield unexpected results because enumerating a generator mutates it. You may convert it to an array with `Array.from()` or the `[...spread]` operator before rendering. You can also use an Iterable that can iterate multiple times over the same items."
                  ), didWarnAboutGenerators = true;
              } else
                newChild.entries !== key || didWarnAboutMaps || (console.error(
                  "Using Maps as children is not supported. Use an array of keyed ReactElements instead."
                ), didWarnAboutMaps = true);
              returnFiber = reconcileChildrenIterator(
                returnFiber,
                currentFirstChild,
                newChildren,
                lanes
              );
              currentDebugInfo = prevDebugInfo;
              return returnFiber;
            }
            if ("function" === typeof newChild.then)
              return prevDebugInfo = pushDebugInfo(newChild._debugInfo), returnFiber = reconcileChildFibersImpl(
                returnFiber,
                currentFirstChild,
                unwrapThenable(newChild),
                lanes
              ), currentDebugInfo = prevDebugInfo, returnFiber;
            if (newChild.$$typeof === REACT_CONTEXT_TYPE)
              return reconcileChildFibersImpl(
                returnFiber,
                currentFirstChild,
                readContextDuringReconciliation(returnFiber, newChild),
                lanes
              );
            throwOnInvalidObjectType(returnFiber, newChild);
          }
          if ("string" === typeof newChild && "" !== newChild || "number" === typeof newChild || "bigint" === typeof newChild)
            return prevDebugInfo = "" + newChild, null !== currentFirstChild && 6 === currentFirstChild.tag ? (deleteRemainingChildren(
              returnFiber,
              currentFirstChild.sibling
            ), lanes = useFiber(currentFirstChild, prevDebugInfo), lanes.return = returnFiber, returnFiber = lanes) : (deleteRemainingChildren(returnFiber, currentFirstChild), lanes = createFiberFromText(
              prevDebugInfo,
              returnFiber.mode,
              lanes
            ), lanes.return = returnFiber, lanes._debugOwner = returnFiber, lanes._debugTask = returnFiber._debugTask, lanes._debugInfo = currentDebugInfo, returnFiber = lanes), placeSingleChild(returnFiber);
          "function" === typeof newChild && warnOnFunctionType(returnFiber, newChild);
          "symbol" === typeof newChild && warnOnSymbolType(returnFiber, newChild);
          return deleteRemainingChildren(returnFiber, currentFirstChild);
        }
        return function(returnFiber, currentFirstChild, newChild, lanes) {
          var prevDebugInfo = currentDebugInfo;
          currentDebugInfo = null;
          try {
            thenableIndexCounter$1 = 0;
            var firstChildFiber = reconcileChildFibersImpl(
              returnFiber,
              currentFirstChild,
              newChild,
              lanes
            );
            thenableState$1 = null;
            return firstChildFiber;
          } catch (x5) {
            if (x5 === SuspenseException || x5 === SuspenseActionException) throw x5;
            var fiber = createFiber(29, x5, null, returnFiber.mode);
            fiber.lanes = lanes;
            fiber.return = returnFiber;
            var debugInfo = fiber._debugInfo = currentDebugInfo;
            fiber._debugOwner = returnFiber._debugOwner;
            fiber._debugTask = returnFiber._debugTask;
            if (null != debugInfo) {
              for (var i = debugInfo.length - 1; 0 <= i; i--)
                if ("string" === typeof debugInfo[i].stack) {
                  fiber._debugOwner = debugInfo[i];
                  fiber._debugTask = debugInfo[i].debugTask;
                  break;
                }
            }
            return fiber;
          } finally {
            currentDebugInfo = prevDebugInfo;
          }
        };
      }
      function validateSuspenseListNestedChild(childSlot, index) {
        var isAnArray = isArrayImpl(childSlot);
        childSlot = !isAnArray && "function" === typeof getIteratorFn(childSlot);
        return isAnArray || childSlot ? (isAnArray = isAnArray ? "array" : "iterable", console.error(
          "A nested %s was passed to row #%s in <SuspenseList />. Wrap it in an additional SuspenseList to configure its revealOrder: <SuspenseList revealOrder=...> ... <SuspenseList revealOrder=...>{%s}</SuspenseList> ... </SuspenseList>",
          isAnArray,
          index,
          isAnArray
        ), false) : true;
      }
      function initializeUpdateQueue(fiber) {
        fiber.updateQueue = {
          baseState: fiber.memoizedState,
          firstBaseUpdate: null,
          lastBaseUpdate: null,
          shared: { pending: null, lanes: 0, hiddenCallbacks: null },
          callbacks: null
        };
      }
      function cloneUpdateQueue(current2, workInProgress2) {
        current2 = current2.updateQueue;
        workInProgress2.updateQueue === current2 && (workInProgress2.updateQueue = {
          baseState: current2.baseState,
          firstBaseUpdate: current2.firstBaseUpdate,
          lastBaseUpdate: current2.lastBaseUpdate,
          shared: current2.shared,
          callbacks: null
        });
      }
      function createUpdate(lane) {
        return {
          lane,
          tag: UpdateState,
          payload: null,
          callback: null,
          next: null
        };
      }
      function enqueueUpdate(fiber, update, lane) {
        var updateQueue = fiber.updateQueue;
        if (null === updateQueue) return null;
        updateQueue = updateQueue.shared;
        if (currentlyProcessingQueue === updateQueue && !didWarnUpdateInsideUpdate) {
          var componentName2 = getComponentNameFromFiber(fiber);
          console.error(
            "An update (setState, replaceState, or forceUpdate) was scheduled from inside an update function. Update functions should be pure, with zero side-effects. Consider using componentDidUpdate or a callback.\n\nPlease update the following component: %s",
            componentName2
          );
          didWarnUpdateInsideUpdate = true;
        }
        if ((executionContext & RenderContext) !== NoContext)
          return componentName2 = updateQueue.pending, null === componentName2 ? update.next = update : (update.next = componentName2.next, componentName2.next = update), updateQueue.pending = update, update = getRootForUpdatedFiber(fiber), markUpdateLaneFromFiberToRoot(fiber, null, lane), update;
        enqueueUpdate$1(fiber, updateQueue, update, lane);
        return getRootForUpdatedFiber(fiber);
      }
      function entangleTransitions(root2, fiber, lane) {
        fiber = fiber.updateQueue;
        if (null !== fiber && (fiber = fiber.shared, 0 !== (lane & 4194048))) {
          var queueLanes = fiber.lanes;
          queueLanes &= root2.pendingLanes;
          lane |= queueLanes;
          fiber.lanes = lane;
          markRootEntangled(root2, lane);
        }
      }
      function enqueueCapturedUpdate(workInProgress2, capturedUpdate) {
        var queue = workInProgress2.updateQueue, current2 = workInProgress2.alternate;
        if (null !== current2 && (current2 = current2.updateQueue, queue === current2)) {
          var newFirst = null, newLast = null;
          queue = queue.firstBaseUpdate;
          if (null !== queue) {
            do {
              var clone = {
                lane: queue.lane,
                tag: queue.tag,
                payload: queue.payload,
                callback: null,
                next: null
              };
              null === newLast ? newFirst = newLast = clone : newLast = newLast.next = clone;
              queue = queue.next;
            } while (null !== queue);
            null === newLast ? newFirst = newLast = capturedUpdate : newLast = newLast.next = capturedUpdate;
          } else newFirst = newLast = capturedUpdate;
          queue = {
            baseState: current2.baseState,
            firstBaseUpdate: newFirst,
            lastBaseUpdate: newLast,
            shared: current2.shared,
            callbacks: current2.callbacks
          };
          workInProgress2.updateQueue = queue;
          return;
        }
        workInProgress2 = queue.lastBaseUpdate;
        null === workInProgress2 ? queue.firstBaseUpdate = capturedUpdate : workInProgress2.next = capturedUpdate;
        queue.lastBaseUpdate = capturedUpdate;
      }
      function suspendIfUpdateReadFromEntangledAsyncAction() {
        if (didReadFromEntangledAsyncAction) {
          var entangledActionThenable = currentEntangledActionThenable;
          if (null !== entangledActionThenable) throw entangledActionThenable;
        }
      }
      function processUpdateQueue(workInProgress2, props, instance$jscomp$0, renderLanes2) {
        didReadFromEntangledAsyncAction = false;
        var queue = workInProgress2.updateQueue;
        hasForceUpdate = false;
        currentlyProcessingQueue = queue.shared;
        var firstBaseUpdate = queue.firstBaseUpdate, lastBaseUpdate = queue.lastBaseUpdate, pendingQueue = queue.shared.pending;
        if (null !== pendingQueue) {
          queue.shared.pending = null;
          var lastPendingUpdate = pendingQueue, firstPendingUpdate = lastPendingUpdate.next;
          lastPendingUpdate.next = null;
          null === lastBaseUpdate ? firstBaseUpdate = firstPendingUpdate : lastBaseUpdate.next = firstPendingUpdate;
          lastBaseUpdate = lastPendingUpdate;
          var current2 = workInProgress2.alternate;
          null !== current2 && (current2 = current2.updateQueue, pendingQueue = current2.lastBaseUpdate, pendingQueue !== lastBaseUpdate && (null === pendingQueue ? current2.firstBaseUpdate = firstPendingUpdate : pendingQueue.next = firstPendingUpdate, current2.lastBaseUpdate = lastPendingUpdate));
        }
        if (null !== firstBaseUpdate) {
          var newState = queue.baseState;
          lastBaseUpdate = 0;
          current2 = firstPendingUpdate = lastPendingUpdate = null;
          pendingQueue = firstBaseUpdate;
          do {
            var updateLane = pendingQueue.lane & -536870913, isHiddenUpdate = updateLane !== pendingQueue.lane;
            if (isHiddenUpdate ? (workInProgressRootRenderLanes & updateLane) === updateLane : (renderLanes2 & updateLane) === updateLane) {
              0 !== updateLane && updateLane === currentEntangledLane && (didReadFromEntangledAsyncAction = true);
              null !== current2 && (current2 = current2.next = {
                lane: 0,
                tag: pendingQueue.tag,
                payload: pendingQueue.payload,
                callback: null,
                next: null
              });
              a: {
                updateLane = workInProgress2;
                var partialState = pendingQueue;
                var nextProps = props, instance = instance$jscomp$0;
                switch (partialState.tag) {
                  case ReplaceState:
                    partialState = partialState.payload;
                    if ("function" === typeof partialState) {
                      isDisallowedContextReadInDEV = true;
                      var nextState = partialState.call(
                        instance,
                        newState,
                        nextProps
                      );
                      if (updateLane.mode & StrictLegacyMode) {
                        setIsStrictModeForDevtools(true);
                        try {
                          partialState.call(instance, newState, nextProps);
                        } finally {
                          setIsStrictModeForDevtools(false);
                        }
                      }
                      isDisallowedContextReadInDEV = false;
                      newState = nextState;
                      break a;
                    }
                    newState = partialState;
                    break a;
                  case CaptureUpdate:
                    updateLane.flags = updateLane.flags & -65537 | 128;
                  case UpdateState:
                    nextState = partialState.payload;
                    if ("function" === typeof nextState) {
                      isDisallowedContextReadInDEV = true;
                      partialState = nextState.call(
                        instance,
                        newState,
                        nextProps
                      );
                      if (updateLane.mode & StrictLegacyMode) {
                        setIsStrictModeForDevtools(true);
                        try {
                          nextState.call(instance, newState, nextProps);
                        } finally {
                          setIsStrictModeForDevtools(false);
                        }
                      }
                      isDisallowedContextReadInDEV = false;
                    } else partialState = nextState;
                    if (null === partialState || void 0 === partialState) break a;
                    newState = assign({}, newState, partialState);
                    break a;
                  case ForceUpdate:
                    hasForceUpdate = true;
                }
              }
              updateLane = pendingQueue.callback;
              null !== updateLane && (workInProgress2.flags |= 64, isHiddenUpdate && (workInProgress2.flags |= 8192), isHiddenUpdate = queue.callbacks, null === isHiddenUpdate ? queue.callbacks = [updateLane] : isHiddenUpdate.push(updateLane));
            } else
              isHiddenUpdate = {
                lane: updateLane,
                tag: pendingQueue.tag,
                payload: pendingQueue.payload,
                callback: pendingQueue.callback,
                next: null
              }, null === current2 ? (firstPendingUpdate = current2 = isHiddenUpdate, lastPendingUpdate = newState) : current2 = current2.next = isHiddenUpdate, lastBaseUpdate |= updateLane;
            pendingQueue = pendingQueue.next;
            if (null === pendingQueue)
              if (pendingQueue = queue.shared.pending, null === pendingQueue)
                break;
              else
                isHiddenUpdate = pendingQueue, pendingQueue = isHiddenUpdate.next, isHiddenUpdate.next = null, queue.lastBaseUpdate = isHiddenUpdate, queue.shared.pending = null;
          } while (1);
          null === current2 && (lastPendingUpdate = newState);
          queue.baseState = lastPendingUpdate;
          queue.firstBaseUpdate = firstPendingUpdate;
          queue.lastBaseUpdate = current2;
          null === firstBaseUpdate && (queue.shared.lanes = 0);
          workInProgressRootSkippedLanes |= lastBaseUpdate;
          workInProgress2.lanes = lastBaseUpdate;
          workInProgress2.memoizedState = newState;
        }
        currentlyProcessingQueue = null;
      }
      function callCallback(callback, context) {
        if ("function" !== typeof callback)
          throw Error(
            "Invalid argument passed as callback. Expected a function. Instead received: " + callback
          );
        callback.call(context);
      }
      function commitHiddenCallbacks(updateQueue, context) {
        var hiddenCallbacks = updateQueue.shared.hiddenCallbacks;
        if (null !== hiddenCallbacks)
          for (updateQueue.shared.hiddenCallbacks = null, updateQueue = 0; updateQueue < hiddenCallbacks.length; updateQueue++)
            callCallback(hiddenCallbacks[updateQueue], context);
      }
      function commitCallbacks(updateQueue, context) {
        var callbacks = updateQueue.callbacks;
        if (null !== callbacks)
          for (updateQueue.callbacks = null, updateQueue = 0; updateQueue < callbacks.length; updateQueue++)
            callCallback(callbacks[updateQueue], context);
      }
      function pushHiddenContext(fiber, context) {
        var prevEntangledRenderLanes = entangledRenderLanes;
        push(prevEntangledRenderLanesCursor, prevEntangledRenderLanes, fiber);
        push(currentTreeHiddenStackCursor, context, fiber);
        entangledRenderLanes = prevEntangledRenderLanes | context.baseLanes;
      }
      function reuseHiddenContextOnStack(fiber) {
        push(prevEntangledRenderLanesCursor, entangledRenderLanes, fiber);
        push(
          currentTreeHiddenStackCursor,
          currentTreeHiddenStackCursor.current,
          fiber
        );
      }
      function popHiddenContext(fiber) {
        entangledRenderLanes = prevEntangledRenderLanesCursor.current;
        pop(currentTreeHiddenStackCursor, fiber);
        pop(prevEntangledRenderLanesCursor, fiber);
      }
      function pushPrimaryTreeSuspenseHandler(handler) {
        var current2 = handler.alternate;
        push(
          suspenseStackCursor,
          suspenseStackCursor.current & SubtreeSuspenseContextMask,
          handler
        );
        push(suspenseHandlerStackCursor, handler, handler);
        null === shellBoundary && (null === current2 || null !== currentTreeHiddenStackCursor.current ? shellBoundary = handler : null !== current2.memoizedState && (shellBoundary = handler));
      }
      function pushDehydratedActivitySuspenseHandler(fiber) {
        push(suspenseStackCursor, suspenseStackCursor.current, fiber);
        push(suspenseHandlerStackCursor, fiber, fiber);
        null === shellBoundary && (shellBoundary = fiber);
      }
      function pushOffscreenSuspenseHandler(fiber) {
        22 === fiber.tag ? (push(suspenseStackCursor, suspenseStackCursor.current, fiber), push(suspenseHandlerStackCursor, fiber, fiber), null === shellBoundary && (shellBoundary = fiber)) : reuseSuspenseHandlerOnStack(fiber);
      }
      function reuseSuspenseHandlerOnStack(fiber) {
        push(suspenseStackCursor, suspenseStackCursor.current, fiber);
        push(
          suspenseHandlerStackCursor,
          suspenseHandlerStackCursor.current,
          fiber
        );
      }
      function popSuspenseHandler(fiber) {
        pop(suspenseHandlerStackCursor, fiber);
        shellBoundary === fiber && (shellBoundary = null);
        pop(suspenseStackCursor, fiber);
      }
      function findFirstSuspended(row) {
        for (var node = row; null !== node; ) {
          if (13 === node.tag) {
            var state = node.memoizedState;
            if (null !== state && (state = state.dehydrated, null === state || isSuspenseInstancePending(state) || isSuspenseInstanceFallback(state)))
              return node;
          } else if (19 === node.tag && ("forwards" === node.memoizedProps.revealOrder || "backwards" === node.memoizedProps.revealOrder || "unstable_legacy-backwards" === node.memoizedProps.revealOrder || "together" === node.memoizedProps.revealOrder)) {
            if (0 !== (node.flags & 128)) return node;
          } else if (null !== node.child) {
            node.child.return = node;
            node = node.child;
            continue;
          }
          if (node === row) break;
          for (; null === node.sibling; ) {
            if (null === node.return || node.return === row) return null;
            node = node.return;
          }
          node.sibling.return = node.return;
          node = node.sibling;
        }
        return null;
      }
      function mountHookTypesDev() {
        var hookName = currentHookNameInDev;
        null === hookTypesDev ? hookTypesDev = [hookName] : hookTypesDev.push(hookName);
      }
      function updateHookTypesDev() {
        var hookName = currentHookNameInDev;
        if (null !== hookTypesDev && (hookTypesUpdateIndexDev++, hookTypesDev[hookTypesUpdateIndexDev] !== hookName)) {
          var componentName2 = getComponentNameFromFiber(currentlyRenderingFiber);
          if (!didWarnAboutMismatchedHooksForComponent.has(componentName2) && (didWarnAboutMismatchedHooksForComponent.add(componentName2), null !== hookTypesDev)) {
            for (var table = "", i = 0; i <= hookTypesUpdateIndexDev; i++) {
              var oldHookName = hookTypesDev[i], newHookName = i === hookTypesUpdateIndexDev ? hookName : oldHookName;
              for (oldHookName = i + 1 + ". " + oldHookName; 30 > oldHookName.length; )
                oldHookName += " ";
              oldHookName += newHookName + "\n";
              table += oldHookName;
            }
            console.error(
              "React has detected a change in the order of Hooks called by %s. This will lead to bugs and errors if not fixed. For more information, read the Rules of Hooks: https://react.dev/link/rules-of-hooks\n\n   Previous render            Next render\n   ------------------------------------------------------\n%s   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n",
              componentName2,
              table
            );
          }
        }
      }
      function checkDepsAreArrayDev(deps) {
        void 0 === deps || null === deps || isArrayImpl(deps) || console.error(
          "%s received a final argument that is not an array (instead, received `%s`). When specified, the final argument must be an array.",
          currentHookNameInDev,
          typeof deps
        );
      }
      function warnOnUseFormStateInDev() {
        var componentName2 = getComponentNameFromFiber(currentlyRenderingFiber);
        didWarnAboutUseFormState.has(componentName2) || (didWarnAboutUseFormState.add(componentName2), console.error(
          "ReactDOM.useFormState has been renamed to React.useActionState. Please update %s to use React.useActionState.",
          componentName2
        ));
      }
      function throwInvalidHookError() {
        throw Error(
          "Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:\n1. You might have mismatching versions of React and the renderer (such as React DOM)\n2. You might be breaking the Rules of Hooks\n3. You might have more than one copy of React in the same app\nSee https://react.dev/link/invalid-hook-call for tips about how to debug and fix this problem."
        );
      }
      function areHookInputsEqual(nextDeps, prevDeps) {
        if (ignorePreviousDependencies) return false;
        if (null === prevDeps)
          return console.error(
            "%s received a final argument during this render, but not during the previous render. Even though the final argument is optional, its type cannot change between renders.",
            currentHookNameInDev
          ), false;
        nextDeps.length !== prevDeps.length && console.error(
          "The final argument passed to %s changed size between renders. The order and size of this array must remain constant.\n\nPrevious: %s\nIncoming: %s",
          currentHookNameInDev,
          "[" + prevDeps.join(", ") + "]",
          "[" + nextDeps.join(", ") + "]"
        );
        for (var i = 0; i < prevDeps.length && i < nextDeps.length; i++)
          if (!objectIs(nextDeps[i], prevDeps[i])) return false;
        return true;
      }
      function renderWithHooks(current2, workInProgress2, Component, props, secondArg, nextRenderLanes) {
        renderLanes = nextRenderLanes;
        currentlyRenderingFiber = workInProgress2;
        hookTypesDev = null !== current2 ? current2._debugHookTypes : null;
        hookTypesUpdateIndexDev = -1;
        ignorePreviousDependencies = null !== current2 && current2.type !== workInProgress2.type;
        if ("[object AsyncFunction]" === Object.prototype.toString.call(Component) || "[object AsyncGeneratorFunction]" === Object.prototype.toString.call(Component))
          nextRenderLanes = getComponentNameFromFiber(currentlyRenderingFiber), didWarnAboutAsyncClientComponent.has(nextRenderLanes) || (didWarnAboutAsyncClientComponent.add(nextRenderLanes), console.error(
            "%s is an async Client Component. Only Server Components can be async at the moment. This error is often caused by accidentally adding `'use client'` to a module that was originally written for the server.",
            null === nextRenderLanes ? "An unknown Component" : "<" + nextRenderLanes + ">"
          ));
        workInProgress2.memoizedState = null;
        workInProgress2.updateQueue = null;
        workInProgress2.lanes = 0;
        ReactSharedInternals.H = null !== current2 && null !== current2.memoizedState ? HooksDispatcherOnUpdateInDEV : null !== hookTypesDev ? HooksDispatcherOnMountWithHookTypesInDEV : HooksDispatcherOnMountInDEV;
        shouldDoubleInvokeUserFnsInHooksDEV = nextRenderLanes = (workInProgress2.mode & StrictLegacyMode) !== NoMode;
        var children = callComponentInDEV(Component, props, secondArg);
        shouldDoubleInvokeUserFnsInHooksDEV = false;
        didScheduleRenderPhaseUpdateDuringThisPass && (children = renderWithHooksAgain(
          workInProgress2,
          Component,
          props,
          secondArg
        ));
        if (nextRenderLanes) {
          setIsStrictModeForDevtools(true);
          try {
            children = renderWithHooksAgain(
              workInProgress2,
              Component,
              props,
              secondArg
            );
          } finally {
            setIsStrictModeForDevtools(false);
          }
        }
        finishRenderingHooks(current2, workInProgress2);
        return children;
      }
      function finishRenderingHooks(current2, workInProgress2) {
        workInProgress2._debugHookTypes = hookTypesDev;
        null === workInProgress2.dependencies ? null !== thenableState && (workInProgress2.dependencies = {
          lanes: 0,
          firstContext: null,
          _debugThenableState: thenableState
        }) : workInProgress2.dependencies._debugThenableState = thenableState;
        ReactSharedInternals.H = ContextOnlyDispatcher;
        var didRenderTooFewHooks = null !== currentHook && null !== currentHook.next;
        renderLanes = 0;
        hookTypesDev = currentHookNameInDev = workInProgressHook = currentHook = currentlyRenderingFiber = null;
        hookTypesUpdateIndexDev = -1;
        null !== current2 && (current2.flags & 65011712) !== (workInProgress2.flags & 65011712) && console.error(
          "Internal React error: Expected static flag was missing. Please notify the React team."
        );
        didScheduleRenderPhaseUpdate = false;
        thenableIndexCounter = 0;
        thenableState = null;
        if (didRenderTooFewHooks)
          throw Error(
            "Rendered fewer hooks than expected. This may be caused by an accidental early return statement."
          );
        null === current2 || didReceiveUpdate || (current2 = current2.dependencies, null !== current2 && checkIfContextChanged(current2) && (didReceiveUpdate = true));
        needsToResetSuspendedThenableDEV ? (needsToResetSuspendedThenableDEV = false, current2 = true) : current2 = false;
        current2 && (workInProgress2 = getComponentNameFromFiber(workInProgress2) || "Unknown", didWarnAboutUseWrappedInTryCatch.has(workInProgress2) || didWarnAboutAsyncClientComponent.has(workInProgress2) || (didWarnAboutUseWrappedInTryCatch.add(workInProgress2), console.error(
          "`use` was called from inside a try/catch block. This is not allowed and can lead to unexpected behavior. To handle errors triggered by `use`, wrap your component in a error boundary."
        )));
      }
      function renderWithHooksAgain(workInProgress2, Component, props, secondArg) {
        currentlyRenderingFiber = workInProgress2;
        var numberOfReRenders = 0;
        do {
          didScheduleRenderPhaseUpdateDuringThisPass && (thenableState = null);
          thenableIndexCounter = 0;
          didScheduleRenderPhaseUpdateDuringThisPass = false;
          if (numberOfReRenders >= RE_RENDER_LIMIT)
            throw Error(
              "Too many re-renders. React limits the number of renders to prevent an infinite loop."
            );
          numberOfReRenders += 1;
          ignorePreviousDependencies = false;
          workInProgressHook = currentHook = null;
          if (null != workInProgress2.updateQueue) {
            var children = workInProgress2.updateQueue;
            children.lastEffect = null;
            children.events = null;
            children.stores = null;
            null != children.memoCache && (children.memoCache.index = 0);
          }
          hookTypesUpdateIndexDev = -1;
          ReactSharedInternals.H = HooksDispatcherOnRerenderInDEV;
          children = callComponentInDEV(Component, props, secondArg);
        } while (didScheduleRenderPhaseUpdateDuringThisPass);
        return children;
      }
      function TransitionAwareHostComponent() {
        var dispatcher = ReactSharedInternals.H, maybeThenable = dispatcher.useState()[0];
        maybeThenable = "function" === typeof maybeThenable.then ? useThenable(maybeThenable) : maybeThenable;
        dispatcher = dispatcher.useState()[0];
        (null !== currentHook ? currentHook.memoizedState : null) !== dispatcher && (currentlyRenderingFiber.flags |= 1024);
        return maybeThenable;
      }
      function checkDidRenderIdHook() {
        var didRenderIdHook = 0 !== localIdCounter;
        localIdCounter = 0;
        return didRenderIdHook;
      }
      function bailoutHooks(current2, workInProgress2, lanes) {
        workInProgress2.updateQueue = current2.updateQueue;
        workInProgress2.flags = (workInProgress2.mode & StrictEffectsMode) !== NoMode ? workInProgress2.flags & -402655237 : workInProgress2.flags & -2053;
        current2.lanes &= ~lanes;
      }
      function resetHooksOnUnwind(workInProgress2) {
        if (didScheduleRenderPhaseUpdate) {
          for (workInProgress2 = workInProgress2.memoizedState; null !== workInProgress2; ) {
            var queue = workInProgress2.queue;
            null !== queue && (queue.pending = null);
            workInProgress2 = workInProgress2.next;
          }
          didScheduleRenderPhaseUpdate = false;
        }
        renderLanes = 0;
        hookTypesDev = workInProgressHook = currentHook = currentlyRenderingFiber = null;
        hookTypesUpdateIndexDev = -1;
        currentHookNameInDev = null;
        didScheduleRenderPhaseUpdateDuringThisPass = false;
        thenableIndexCounter = localIdCounter = 0;
        thenableState = null;
      }
      function mountWorkInProgressHook() {
        var hook = {
          memoizedState: null,
          baseState: null,
          baseQueue: null,
          queue: null,
          next: null
        };
        null === workInProgressHook ? currentlyRenderingFiber.memoizedState = workInProgressHook = hook : workInProgressHook = workInProgressHook.next = hook;
        return workInProgressHook;
      }
      function updateWorkInProgressHook() {
        if (null === currentHook) {
          var nextCurrentHook = currentlyRenderingFiber.alternate;
          nextCurrentHook = null !== nextCurrentHook ? nextCurrentHook.memoizedState : null;
        } else nextCurrentHook = currentHook.next;
        var nextWorkInProgressHook = null === workInProgressHook ? currentlyRenderingFiber.memoizedState : workInProgressHook.next;
        if (null !== nextWorkInProgressHook)
          workInProgressHook = nextWorkInProgressHook, currentHook = nextCurrentHook;
        else {
          if (null === nextCurrentHook) {
            if (null === currentlyRenderingFiber.alternate)
              throw Error(
                "Update hook called on initial render. This is likely a bug in React. Please file an issue."
              );
            throw Error("Rendered more hooks than during the previous render.");
          }
          currentHook = nextCurrentHook;
          nextCurrentHook = {
            memoizedState: currentHook.memoizedState,
            baseState: currentHook.baseState,
            baseQueue: currentHook.baseQueue,
            queue: currentHook.queue,
            next: null
          };
          null === workInProgressHook ? currentlyRenderingFiber.memoizedState = workInProgressHook = nextCurrentHook : workInProgressHook = workInProgressHook.next = nextCurrentHook;
        }
        return workInProgressHook;
      }
      function createFunctionComponentUpdateQueue() {
        return { lastEffect: null, events: null, stores: null, memoCache: null };
      }
      function useThenable(thenable) {
        var index = thenableIndexCounter;
        thenableIndexCounter += 1;
        null === thenableState && (thenableState = createThenableState());
        thenable = trackUsedThenable(thenableState, thenable, index);
        index = currentlyRenderingFiber;
        null === (null === workInProgressHook ? index.memoizedState : workInProgressHook.next) && (index = index.alternate, ReactSharedInternals.H = null !== index && null !== index.memoizedState ? HooksDispatcherOnUpdateInDEV : HooksDispatcherOnMountInDEV);
        return thenable;
      }
      function use(usable) {
        if (null !== usable && "object" === typeof usable) {
          if ("function" === typeof usable.then) return useThenable(usable);
          if (usable.$$typeof === REACT_CONTEXT_TYPE) return readContext(usable);
        }
        throw Error("An unsupported type was passed to use(): " + String(usable));
      }
      function useMemoCache(size) {
        var memoCache = null, updateQueue = currentlyRenderingFiber.updateQueue;
        null !== updateQueue && (memoCache = updateQueue.memoCache);
        if (null == memoCache) {
          var current2 = currentlyRenderingFiber.alternate;
          null !== current2 && (current2 = current2.updateQueue, null !== current2 && (current2 = current2.memoCache, null != current2 && (memoCache = {
            data: current2.data.map(function(array) {
              return array.slice();
            }),
            index: 0
          })));
        }
        null == memoCache && (memoCache = { data: [], index: 0 });
        null === updateQueue && (updateQueue = createFunctionComponentUpdateQueue(), currentlyRenderingFiber.updateQueue = updateQueue);
        updateQueue.memoCache = memoCache;
        updateQueue = memoCache.data[memoCache.index];
        if (void 0 === updateQueue || ignorePreviousDependencies)
          for (updateQueue = memoCache.data[memoCache.index] = Array(size), current2 = 0; current2 < size; current2++)
            updateQueue[current2] = REACT_MEMO_CACHE_SENTINEL;
        else
          updateQueue.length !== size && console.error(
            "Expected a constant size argument for each invocation of useMemoCache. The previous cache was allocated with size %s but size %s was requested.",
            updateQueue.length,
            size
          );
        memoCache.index++;
        return updateQueue;
      }
      function basicStateReducer(state, action) {
        return "function" === typeof action ? action(state) : action;
      }
      function mountReducer(reducer, initialArg, init2) {
        var hook = mountWorkInProgressHook();
        if (void 0 !== init2) {
          var initialState = init2(initialArg);
          if (shouldDoubleInvokeUserFnsInHooksDEV) {
            setIsStrictModeForDevtools(true);
            try {
              init2(initialArg);
            } finally {
              setIsStrictModeForDevtools(false);
            }
          }
        } else initialState = initialArg;
        hook.memoizedState = hook.baseState = initialState;
        reducer = {
          pending: null,
          lanes: 0,
          dispatch: null,
          lastRenderedReducer: reducer,
          lastRenderedState: initialState
        };
        hook.queue = reducer;
        reducer = reducer.dispatch = dispatchReducerAction.bind(
          null,
          currentlyRenderingFiber,
          reducer
        );
        return [hook.memoizedState, reducer];
      }
      function updateReducer(reducer) {
        var hook = updateWorkInProgressHook();
        return updateReducerImpl(hook, currentHook, reducer);
      }
      function updateReducerImpl(hook, current2, reducer) {
        var queue = hook.queue;
        if (null === queue)
          throw Error(
            "Should have a queue. You are likely calling Hooks conditionally, which is not allowed. (https://react.dev/link/invalid-hook-call)"
          );
        queue.lastRenderedReducer = reducer;
        var baseQueue = hook.baseQueue, pendingQueue = queue.pending;
        if (null !== pendingQueue) {
          if (null !== baseQueue) {
            var baseFirst = baseQueue.next;
            baseQueue.next = pendingQueue.next;
            pendingQueue.next = baseFirst;
          }
          current2.baseQueue !== baseQueue && console.error(
            "Internal error: Expected work-in-progress queue to be a clone. This is a bug in React."
          );
          current2.baseQueue = baseQueue = pendingQueue;
          queue.pending = null;
        }
        pendingQueue = hook.baseState;
        if (null === baseQueue) hook.memoizedState = pendingQueue;
        else {
          current2 = baseQueue.next;
          var newBaseQueueFirst = baseFirst = null, newBaseQueueLast = null, update = current2, didReadFromEntangledAsyncAction2 = false;
          do {
            var updateLane = update.lane & -536870913;
            if (updateLane !== update.lane ? (workInProgressRootRenderLanes & updateLane) === updateLane : (renderLanes & updateLane) === updateLane) {
              var revertLane = update.revertLane;
              if (0 === revertLane)
                null !== newBaseQueueLast && (newBaseQueueLast = newBaseQueueLast.next = {
                  lane: 0,
                  revertLane: 0,
                  gesture: null,
                  action: update.action,
                  hasEagerState: update.hasEagerState,
                  eagerState: update.eagerState,
                  next: null
                }), updateLane === currentEntangledLane && (didReadFromEntangledAsyncAction2 = true);
              else if ((renderLanes & revertLane) === revertLane) {
                update = update.next;
                revertLane === currentEntangledLane && (didReadFromEntangledAsyncAction2 = true);
                continue;
              } else
                updateLane = {
                  lane: 0,
                  revertLane: update.revertLane,
                  gesture: null,
                  action: update.action,
                  hasEagerState: update.hasEagerState,
                  eagerState: update.eagerState,
                  next: null
                }, null === newBaseQueueLast ? (newBaseQueueFirst = newBaseQueueLast = updateLane, baseFirst = pendingQueue) : newBaseQueueLast = newBaseQueueLast.next = updateLane, currentlyRenderingFiber.lanes |= revertLane, workInProgressRootSkippedLanes |= revertLane;
              updateLane = update.action;
              shouldDoubleInvokeUserFnsInHooksDEV && reducer(pendingQueue, updateLane);
              pendingQueue = update.hasEagerState ? update.eagerState : reducer(pendingQueue, updateLane);
            } else
              revertLane = {
                lane: updateLane,
                revertLane: update.revertLane,
                gesture: update.gesture,
                action: update.action,
                hasEagerState: update.hasEagerState,
                eagerState: update.eagerState,
                next: null
              }, null === newBaseQueueLast ? (newBaseQueueFirst = newBaseQueueLast = revertLane, baseFirst = pendingQueue) : newBaseQueueLast = newBaseQueueLast.next = revertLane, currentlyRenderingFiber.lanes |= updateLane, workInProgressRootSkippedLanes |= updateLane;
            update = update.next;
          } while (null !== update && update !== current2);
          null === newBaseQueueLast ? baseFirst = pendingQueue : newBaseQueueLast.next = newBaseQueueFirst;
          if (!objectIs(pendingQueue, hook.memoizedState) && (didReceiveUpdate = true, didReadFromEntangledAsyncAction2 && (reducer = currentEntangledActionThenable, null !== reducer)))
            throw reducer;
          hook.memoizedState = pendingQueue;
          hook.baseState = baseFirst;
          hook.baseQueue = newBaseQueueLast;
          queue.lastRenderedState = pendingQueue;
        }
        null === baseQueue && (queue.lanes = 0);
        return [hook.memoizedState, queue.dispatch];
      }
      function rerenderReducer(reducer) {
        var hook = updateWorkInProgressHook(), queue = hook.queue;
        if (null === queue)
          throw Error(
            "Should have a queue. You are likely calling Hooks conditionally, which is not allowed. (https://react.dev/link/invalid-hook-call)"
          );
        queue.lastRenderedReducer = reducer;
        var dispatch = queue.dispatch, lastRenderPhaseUpdate = queue.pending, newState = hook.memoizedState;
        if (null !== lastRenderPhaseUpdate) {
          queue.pending = null;
          var update = lastRenderPhaseUpdate = lastRenderPhaseUpdate.next;
          do
            newState = reducer(newState, update.action), update = update.next;
          while (update !== lastRenderPhaseUpdate);
          objectIs(newState, hook.memoizedState) || (didReceiveUpdate = true);
          hook.memoizedState = newState;
          null === hook.baseQueue && (hook.baseState = newState);
          queue.lastRenderedState = newState;
        }
        return [newState, dispatch];
      }
      function mountSyncExternalStore(subscribe2, getSnapshot, getServerSnapshot) {
        var fiber = currentlyRenderingFiber, hook = mountWorkInProgressHook();
        if (isHydrating) {
          if (void 0 === getServerSnapshot)
            throw Error(
              "Missing getServerSnapshot, which is required for server-rendered content. Will revert to client rendering."
            );
          var nextSnapshot = getServerSnapshot();
          didWarnUncachedGetSnapshot || nextSnapshot === getServerSnapshot() || (console.error(
            "The result of getServerSnapshot should be cached to avoid an infinite loop"
          ), didWarnUncachedGetSnapshot = true);
        } else {
          nextSnapshot = getSnapshot();
          didWarnUncachedGetSnapshot || (getServerSnapshot = getSnapshot(), objectIs(nextSnapshot, getServerSnapshot) || (console.error(
            "The result of getSnapshot should be cached to avoid an infinite loop"
          ), didWarnUncachedGetSnapshot = true));
          if (null === workInProgressRoot)
            throw Error(
              "Expected a work-in-progress root. This is a bug in React. Please file an issue."
            );
          0 !== (workInProgressRootRenderLanes & 127) || pushStoreConsistencyCheck(fiber, getSnapshot, nextSnapshot);
        }
        hook.memoizedState = nextSnapshot;
        getServerSnapshot = { value: nextSnapshot, getSnapshot };
        hook.queue = getServerSnapshot;
        mountEffect(
          subscribeToStore.bind(null, fiber, getServerSnapshot, subscribe2),
          [subscribe2]
        );
        fiber.flags |= 2048;
        pushSimpleEffect(
          HasEffect | Passive,
          { destroy: void 0 },
          updateStoreInstance.bind(
            null,
            fiber,
            getServerSnapshot,
            nextSnapshot,
            getSnapshot
          ),
          null
        );
        return nextSnapshot;
      }
      function updateSyncExternalStore(subscribe2, getSnapshot, getServerSnapshot) {
        var fiber = currentlyRenderingFiber, hook = updateWorkInProgressHook(), isHydrating$jscomp$0 = isHydrating;
        if (isHydrating$jscomp$0) {
          if (void 0 === getServerSnapshot)
            throw Error(
              "Missing getServerSnapshot, which is required for server-rendered content. Will revert to client rendering."
            );
          getServerSnapshot = getServerSnapshot();
        } else if (getServerSnapshot = getSnapshot(), !didWarnUncachedGetSnapshot) {
          var cachedSnapshot2 = getSnapshot();
          objectIs(getServerSnapshot, cachedSnapshot2) || (console.error(
            "The result of getSnapshot should be cached to avoid an infinite loop"
          ), didWarnUncachedGetSnapshot = true);
        }
        if (cachedSnapshot2 = !objectIs(
          (currentHook || hook).memoizedState,
          getServerSnapshot
        ))
          hook.memoizedState = getServerSnapshot, didReceiveUpdate = true;
        hook = hook.queue;
        var create = subscribeToStore.bind(null, fiber, hook, subscribe2);
        updateEffectImpl(2048, Passive, create, [subscribe2]);
        if (hook.getSnapshot !== getSnapshot || cachedSnapshot2 || null !== workInProgressHook && workInProgressHook.memoizedState.tag & HasEffect) {
          fiber.flags |= 2048;
          pushSimpleEffect(
            HasEffect | Passive,
            { destroy: void 0 },
            updateStoreInstance.bind(
              null,
              fiber,
              hook,
              getServerSnapshot,
              getSnapshot
            ),
            null
          );
          if (null === workInProgressRoot)
            throw Error(
              "Expected a work-in-progress root. This is a bug in React. Please file an issue."
            );
          isHydrating$jscomp$0 || 0 !== (renderLanes & 127) || pushStoreConsistencyCheck(fiber, getSnapshot, getServerSnapshot);
        }
        return getServerSnapshot;
      }
      function pushStoreConsistencyCheck(fiber, getSnapshot, renderedSnapshot) {
        fiber.flags |= 16384;
        fiber = { getSnapshot, value: renderedSnapshot };
        getSnapshot = currentlyRenderingFiber.updateQueue;
        null === getSnapshot ? (getSnapshot = createFunctionComponentUpdateQueue(), currentlyRenderingFiber.updateQueue = getSnapshot, getSnapshot.stores = [fiber]) : (renderedSnapshot = getSnapshot.stores, null === renderedSnapshot ? getSnapshot.stores = [fiber] : renderedSnapshot.push(fiber));
      }
      function updateStoreInstance(fiber, inst, nextSnapshot, getSnapshot) {
        inst.value = nextSnapshot;
        inst.getSnapshot = getSnapshot;
        checkIfSnapshotChanged(inst) && forceStoreRerender(fiber);
      }
      function subscribeToStore(fiber, inst, subscribe2) {
        return subscribe2(function() {
          checkIfSnapshotChanged(inst) && (startUpdateTimerByLane(2, "updateSyncExternalStore()", fiber), forceStoreRerender(fiber));
        });
      }
      function checkIfSnapshotChanged(inst) {
        var latestGetSnapshot = inst.getSnapshot;
        inst = inst.value;
        try {
          var nextValue = latestGetSnapshot();
          return !objectIs(inst, nextValue);
        } catch (error) {
          return true;
        }
      }
      function forceStoreRerender(fiber) {
        var root2 = enqueueConcurrentRenderForLane(fiber, 2);
        null !== root2 && scheduleUpdateOnFiber(root2, fiber, 2);
      }
      function mountStateImpl(initialState) {
        var hook = mountWorkInProgressHook();
        if ("function" === typeof initialState) {
          var initialStateInitializer = initialState;
          initialState = initialStateInitializer();
          if (shouldDoubleInvokeUserFnsInHooksDEV) {
            setIsStrictModeForDevtools(true);
            try {
              initialStateInitializer();
            } finally {
              setIsStrictModeForDevtools(false);
            }
          }
        }
        hook.memoizedState = hook.baseState = initialState;
        hook.queue = {
          pending: null,
          lanes: 0,
          dispatch: null,
          lastRenderedReducer: basicStateReducer,
          lastRenderedState: initialState
        };
        return hook;
      }
      function mountState(initialState) {
        initialState = mountStateImpl(initialState);
        var queue = initialState.queue, dispatch = dispatchSetState.bind(null, currentlyRenderingFiber, queue);
        queue.dispatch = dispatch;
        return [initialState.memoizedState, dispatch];
      }
      function mountOptimistic(passthrough) {
        var hook = mountWorkInProgressHook();
        hook.memoizedState = hook.baseState = passthrough;
        var queue = {
          pending: null,
          lanes: 0,
          dispatch: null,
          lastRenderedReducer: null,
          lastRenderedState: null
        };
        hook.queue = queue;
        hook = dispatchOptimisticSetState.bind(
          null,
          currentlyRenderingFiber,
          true,
          queue
        );
        queue.dispatch = hook;
        return [passthrough, hook];
      }
      function updateOptimistic(passthrough, reducer) {
        var hook = updateWorkInProgressHook();
        return updateOptimisticImpl(hook, currentHook, passthrough, reducer);
      }
      function updateOptimisticImpl(hook, current2, passthrough, reducer) {
        hook.baseState = passthrough;
        return updateReducerImpl(
          hook,
          currentHook,
          "function" === typeof reducer ? reducer : basicStateReducer
        );
      }
      function rerenderOptimistic(passthrough, reducer) {
        var hook = updateWorkInProgressHook();
        if (null !== currentHook)
          return updateOptimisticImpl(hook, currentHook, passthrough, reducer);
        hook.baseState = passthrough;
        return [passthrough, hook.queue.dispatch];
      }
      function dispatchActionState(fiber, actionQueue, setPendingState, setState, payload) {
        if (isRenderPhaseUpdate(fiber))
          throw Error("Cannot update form state while rendering.");
        fiber = actionQueue.action;
        if (null !== fiber) {
          var actionNode = {
            payload,
            action: fiber,
            next: null,
            isTransition: true,
            status: "pending",
            value: null,
            reason: null,
            listeners: [],
            then: function(listener) {
              actionNode.listeners.push(listener);
            }
          };
          null !== ReactSharedInternals.T ? setPendingState(true) : actionNode.isTransition = false;
          setState(actionNode);
          setPendingState = actionQueue.pending;
          null === setPendingState ? (actionNode.next = actionQueue.pending = actionNode, runActionStateAction(actionQueue, actionNode)) : (actionNode.next = setPendingState.next, actionQueue.pending = setPendingState.next = actionNode);
        }
      }
      function runActionStateAction(actionQueue, node) {
        var action = node.action, payload = node.payload, prevState = actionQueue.state;
        if (node.isTransition) {
          var prevTransition = ReactSharedInternals.T, currentTransition = {};
          currentTransition._updatedFibers = /* @__PURE__ */ new Set();
          ReactSharedInternals.T = currentTransition;
          try {
            var returnValue = action(prevState, payload), onStartTransitionFinish = ReactSharedInternals.S;
            null !== onStartTransitionFinish && onStartTransitionFinish(currentTransition, returnValue);
            handleActionReturnValue(actionQueue, node, returnValue);
          } catch (error) {
            onActionError(actionQueue, node, error);
          } finally {
            null !== prevTransition && null !== currentTransition.types && (null !== prevTransition.types && prevTransition.types !== currentTransition.types && console.error(
              "We expected inner Transitions to have transferred the outer types set and that you cannot add to the outer Transition while inside the inner.This is a bug in React."
            ), prevTransition.types = currentTransition.types), ReactSharedInternals.T = prevTransition, null === prevTransition && currentTransition._updatedFibers && (actionQueue = currentTransition._updatedFibers.size, currentTransition._updatedFibers.clear(), 10 < actionQueue && console.warn(
              "Detected a large number of updates inside startTransition. If this is due to a subscription please re-write it to use React provided hooks. Otherwise concurrent mode guarantees are off the table."
            ));
          }
        } else
          try {
            currentTransition = action(prevState, payload), handleActionReturnValue(actionQueue, node, currentTransition);
          } catch (error$4) {
            onActionError(actionQueue, node, error$4);
          }
      }
      function handleActionReturnValue(actionQueue, node, returnValue) {
        null !== returnValue && "object" === typeof returnValue && "function" === typeof returnValue.then ? (ReactSharedInternals.asyncTransitions++, returnValue.then(releaseAsyncTransition, releaseAsyncTransition), returnValue.then(
          function(nextState) {
            onActionSuccess(actionQueue, node, nextState);
          },
          function(error) {
            return onActionError(actionQueue, node, error);
          }
        ), node.isTransition || console.error(
          "An async function with useActionState was called outside of a transition. This is likely not what you intended (for example, isPending will not update correctly). Either call the returned function inside startTransition, or pass it to an `action` or `formAction` prop."
        )) : onActionSuccess(actionQueue, node, returnValue);
      }
      function onActionSuccess(actionQueue, actionNode, nextState) {
        actionNode.status = "fulfilled";
        actionNode.value = nextState;
        notifyActionListeners(actionNode);
        actionQueue.state = nextState;
        actionNode = actionQueue.pending;
        null !== actionNode && (nextState = actionNode.next, nextState === actionNode ? actionQueue.pending = null : (nextState = nextState.next, actionNode.next = nextState, runActionStateAction(actionQueue, nextState)));
      }
      function onActionError(actionQueue, actionNode, error) {
        var last = actionQueue.pending;
        actionQueue.pending = null;
        if (null !== last) {
          last = last.next;
          do
            actionNode.status = "rejected", actionNode.reason = error, notifyActionListeners(actionNode), actionNode = actionNode.next;
          while (actionNode !== last);
        }
        actionQueue.action = null;
      }
      function notifyActionListeners(actionNode) {
        actionNode = actionNode.listeners;
        for (var i = 0; i < actionNode.length; i++) (0, actionNode[i])();
      }
      function actionStateReducer(oldState, newState) {
        return newState;
      }
      function mountActionState(action, initialStateProp) {
        if (isHydrating) {
          var ssrFormState = workInProgressRoot.formState;
          if (null !== ssrFormState) {
            a: {
              var isMatching = currentlyRenderingFiber;
              if (isHydrating) {
                if (nextHydratableInstance) {
                  b: {
                    var markerInstance = nextHydratableInstance;
                    for (var inRootOrSingleton = rootOrSingletonContext; 8 !== markerInstance.nodeType; ) {
                      if (!inRootOrSingleton) {
                        markerInstance = null;
                        break b;
                      }
                      markerInstance = getNextHydratable(
                        markerInstance.nextSibling
                      );
                      if (null === markerInstance) {
                        markerInstance = null;
                        break b;
                      }
                    }
                    inRootOrSingleton = markerInstance.data;
                    markerInstance = inRootOrSingleton === FORM_STATE_IS_MATCHING || inRootOrSingleton === FORM_STATE_IS_NOT_MATCHING ? markerInstance : null;
                  }
                  if (markerInstance) {
                    nextHydratableInstance = getNextHydratable(
                      markerInstance.nextSibling
                    );
                    isMatching = markerInstance.data === FORM_STATE_IS_MATCHING;
                    break a;
                  }
                }
                throwOnHydrationMismatch(isMatching);
              }
              isMatching = false;
            }
            isMatching && (initialStateProp = ssrFormState[0]);
          }
        }
        ssrFormState = mountWorkInProgressHook();
        ssrFormState.memoizedState = ssrFormState.baseState = initialStateProp;
        isMatching = {
          pending: null,
          lanes: 0,
          dispatch: null,
          lastRenderedReducer: actionStateReducer,
          lastRenderedState: initialStateProp
        };
        ssrFormState.queue = isMatching;
        ssrFormState = dispatchSetState.bind(
          null,
          currentlyRenderingFiber,
          isMatching
        );
        isMatching.dispatch = ssrFormState;
        isMatching = mountStateImpl(false);
        inRootOrSingleton = dispatchOptimisticSetState.bind(
          null,
          currentlyRenderingFiber,
          false,
          isMatching.queue
        );
        isMatching = mountWorkInProgressHook();
        markerInstance = {
          state: initialStateProp,
          dispatch: null,
          action,
          pending: null
        };
        isMatching.queue = markerInstance;
        ssrFormState = dispatchActionState.bind(
          null,
          currentlyRenderingFiber,
          markerInstance,
          inRootOrSingleton,
          ssrFormState
        );
        markerInstance.dispatch = ssrFormState;
        isMatching.memoizedState = action;
        return [initialStateProp, ssrFormState, false];
      }
      function updateActionState(action) {
        var stateHook = updateWorkInProgressHook();
        return updateActionStateImpl(stateHook, currentHook, action);
      }
      function updateActionStateImpl(stateHook, currentStateHook, action) {
        currentStateHook = updateReducerImpl(
          stateHook,
          currentStateHook,
          actionStateReducer
        )[0];
        stateHook = updateReducer(basicStateReducer)[0];
        if ("object" === typeof currentStateHook && null !== currentStateHook && "function" === typeof currentStateHook.then)
          try {
            var state = useThenable(currentStateHook);
          } catch (x5) {
            if (x5 === SuspenseException) throw SuspenseActionException;
            throw x5;
          }
        else state = currentStateHook;
        currentStateHook = updateWorkInProgressHook();
        var actionQueue = currentStateHook.queue, dispatch = actionQueue.dispatch;
        action !== currentStateHook.memoizedState && (currentlyRenderingFiber.flags |= 2048, pushSimpleEffect(
          HasEffect | Passive,
          { destroy: void 0 },
          actionStateActionEffect.bind(null, actionQueue, action),
          null
        ));
        return [state, dispatch, stateHook];
      }
      function actionStateActionEffect(actionQueue, action) {
        actionQueue.action = action;
      }
      function rerenderActionState(action) {
        var stateHook = updateWorkInProgressHook(), currentStateHook = currentHook;
        if (null !== currentStateHook)
          return updateActionStateImpl(stateHook, currentStateHook, action);
        updateWorkInProgressHook();
        stateHook = stateHook.memoizedState;
        currentStateHook = updateWorkInProgressHook();
        var dispatch = currentStateHook.queue.dispatch;
        currentStateHook.memoizedState = action;
        return [stateHook, dispatch, false];
      }
      function pushSimpleEffect(tag, inst, create, deps) {
        tag = { tag, create, deps, inst, next: null };
        inst = currentlyRenderingFiber.updateQueue;
        null === inst && (inst = createFunctionComponentUpdateQueue(), currentlyRenderingFiber.updateQueue = inst);
        create = inst.lastEffect;
        null === create ? inst.lastEffect = tag.next = tag : (deps = create.next, create.next = tag, tag.next = deps, inst.lastEffect = tag);
        return tag;
      }
      function mountRef(initialValue) {
        var hook = mountWorkInProgressHook();
        initialValue = { current: initialValue };
        return hook.memoizedState = initialValue;
      }
      function mountEffectImpl(fiberFlags, hookFlags, create, deps) {
        var hook = mountWorkInProgressHook();
        currentlyRenderingFiber.flags |= fiberFlags;
        hook.memoizedState = pushSimpleEffect(
          HasEffect | hookFlags,
          { destroy: void 0 },
          create,
          void 0 === deps ? null : deps
        );
      }
      function updateEffectImpl(fiberFlags, hookFlags, create, deps) {
        var hook = updateWorkInProgressHook();
        deps = void 0 === deps ? null : deps;
        var inst = hook.memoizedState.inst;
        null !== currentHook && null !== deps && areHookInputsEqual(deps, currentHook.memoizedState.deps) ? hook.memoizedState = pushSimpleEffect(hookFlags, inst, create, deps) : (currentlyRenderingFiber.flags |= fiberFlags, hook.memoizedState = pushSimpleEffect(
          HasEffect | hookFlags,
          inst,
          create,
          deps
        ));
      }
      function mountEffect(create, deps) {
        (currentlyRenderingFiber.mode & StrictEffectsMode) !== NoMode ? mountEffectImpl(276826112, Passive, create, deps) : mountEffectImpl(8390656, Passive, create, deps);
      }
      function useEffectEventImpl(payload) {
        currentlyRenderingFiber.flags |= 4;
        var componentUpdateQueue = currentlyRenderingFiber.updateQueue;
        if (null === componentUpdateQueue)
          componentUpdateQueue = createFunctionComponentUpdateQueue(), currentlyRenderingFiber.updateQueue = componentUpdateQueue, componentUpdateQueue.events = [payload];
        else {
          var events = componentUpdateQueue.events;
          null === events ? componentUpdateQueue.events = [payload] : events.push(payload);
        }
      }
      function mountEvent(callback) {
        var hook = mountWorkInProgressHook(), ref = { impl: callback };
        hook.memoizedState = ref;
        return function() {
          if ((executionContext & RenderContext) !== NoContext)
            throw Error(
              "A function wrapped in useEffectEvent can't be called during rendering."
            );
          return ref.impl.apply(void 0, arguments);
        };
      }
      function updateEvent(callback) {
        var ref = updateWorkInProgressHook().memoizedState;
        useEffectEventImpl({ ref, nextImpl: callback });
        return function() {
          if ((executionContext & RenderContext) !== NoContext)
            throw Error(
              "A function wrapped in useEffectEvent can't be called during rendering."
            );
          return ref.impl.apply(void 0, arguments);
        };
      }
      function mountLayoutEffect(create, deps) {
        var fiberFlags = 4194308;
        (currentlyRenderingFiber.mode & StrictEffectsMode) !== NoMode && (fiberFlags |= 134217728);
        return mountEffectImpl(fiberFlags, Layout, create, deps);
      }
      function imperativeHandleEffect(create, ref) {
        if ("function" === typeof ref) {
          create = create();
          var refCleanup = ref(create);
          return function() {
            "function" === typeof refCleanup ? refCleanup() : ref(null);
          };
        }
        if (null !== ref && void 0 !== ref)
          return ref.hasOwnProperty("current") || console.error(
            "Expected useImperativeHandle() first argument to either be a ref callback or React.createRef() object. Instead received: %s.",
            "an object with keys {" + Object.keys(ref).join(", ") + "}"
          ), create = create(), ref.current = create, function() {
            ref.current = null;
          };
      }
      function mountImperativeHandle(ref, create, deps) {
        "function" !== typeof create && console.error(
          "Expected useImperativeHandle() second argument to be a function that creates a handle. Instead received: %s.",
          null !== create ? typeof create : "null"
        );
        deps = null !== deps && void 0 !== deps ? deps.concat([ref]) : null;
        var fiberFlags = 4194308;
        (currentlyRenderingFiber.mode & StrictEffectsMode) !== NoMode && (fiberFlags |= 134217728);
        mountEffectImpl(
          fiberFlags,
          Layout,
          imperativeHandleEffect.bind(null, create, ref),
          deps
        );
      }
      function updateImperativeHandle(ref, create, deps) {
        "function" !== typeof create && console.error(
          "Expected useImperativeHandle() second argument to be a function that creates a handle. Instead received: %s.",
          null !== create ? typeof create : "null"
        );
        deps = null !== deps && void 0 !== deps ? deps.concat([ref]) : null;
        updateEffectImpl(
          4,
          Layout,
          imperativeHandleEffect.bind(null, create, ref),
          deps
        );
      }
      function mountCallback(callback, deps) {
        mountWorkInProgressHook().memoizedState = [
          callback,
          void 0 === deps ? null : deps
        ];
        return callback;
      }
      function updateCallback(callback, deps) {
        var hook = updateWorkInProgressHook();
        deps = void 0 === deps ? null : deps;
        var prevState = hook.memoizedState;
        if (null !== deps && areHookInputsEqual(deps, prevState[1]))
          return prevState[0];
        hook.memoizedState = [callback, deps];
        return callback;
      }
      function mountMemo(nextCreate, deps) {
        var hook = mountWorkInProgressHook();
        deps = void 0 === deps ? null : deps;
        var nextValue = nextCreate();
        if (shouldDoubleInvokeUserFnsInHooksDEV) {
          setIsStrictModeForDevtools(true);
          try {
            nextCreate();
          } finally {
            setIsStrictModeForDevtools(false);
          }
        }
        hook.memoizedState = [nextValue, deps];
        return nextValue;
      }
      function updateMemo(nextCreate, deps) {
        var hook = updateWorkInProgressHook();
        deps = void 0 === deps ? null : deps;
        var prevState = hook.memoizedState;
        if (null !== deps && areHookInputsEqual(deps, prevState[1]))
          return prevState[0];
        prevState = nextCreate();
        if (shouldDoubleInvokeUserFnsInHooksDEV) {
          setIsStrictModeForDevtools(true);
          try {
            nextCreate();
          } finally {
            setIsStrictModeForDevtools(false);
          }
        }
        hook.memoizedState = [prevState, deps];
        return prevState;
      }
      function mountDeferredValue(value, initialValue) {
        var hook = mountWorkInProgressHook();
        return mountDeferredValueImpl(hook, value, initialValue);
      }
      function updateDeferredValue(value, initialValue) {
        var hook = updateWorkInProgressHook();
        return updateDeferredValueImpl(
          hook,
          currentHook.memoizedState,
          value,
          initialValue
        );
      }
      function rerenderDeferredValue(value, initialValue) {
        var hook = updateWorkInProgressHook();
        return null === currentHook ? mountDeferredValueImpl(hook, value, initialValue) : updateDeferredValueImpl(
          hook,
          currentHook.memoizedState,
          value,
          initialValue
        );
      }
      function mountDeferredValueImpl(hook, value, initialValue) {
        if (void 0 === initialValue || 0 !== (renderLanes & 1073741824) && 0 === (workInProgressRootRenderLanes & 261930))
          return hook.memoizedState = value;
        hook.memoizedState = initialValue;
        hook = requestDeferredLane();
        currentlyRenderingFiber.lanes |= hook;
        workInProgressRootSkippedLanes |= hook;
        return initialValue;
      }
      function updateDeferredValueImpl(hook, prevValue, value, initialValue) {
        if (objectIs(value, prevValue)) return value;
        if (null !== currentTreeHiddenStackCursor.current)
          return hook = mountDeferredValueImpl(hook, value, initialValue), objectIs(hook, prevValue) || (didReceiveUpdate = true), hook;
        if (0 === (renderLanes & 42) || 0 !== (renderLanes & 1073741824) && 0 === (workInProgressRootRenderLanes & 261930))
          return didReceiveUpdate = true, hook.memoizedState = value;
        hook = requestDeferredLane();
        currentlyRenderingFiber.lanes |= hook;
        workInProgressRootSkippedLanes |= hook;
        return prevValue;
      }
      function releaseAsyncTransition() {
        ReactSharedInternals.asyncTransitions--;
      }
      function startTransition(fiber, queue, pendingState, finishedState, callback) {
        var previousPriority = ReactDOMSharedInternals.p;
        ReactDOMSharedInternals.p = 0 !== previousPriority && previousPriority < ContinuousEventPriority ? previousPriority : ContinuousEventPriority;
        var prevTransition = ReactSharedInternals.T, currentTransition = {};
        currentTransition._updatedFibers = /* @__PURE__ */ new Set();
        ReactSharedInternals.T = currentTransition;
        dispatchOptimisticSetState(fiber, false, queue, pendingState);
        try {
          var returnValue = callback(), onStartTransitionFinish = ReactSharedInternals.S;
          null !== onStartTransitionFinish && onStartTransitionFinish(currentTransition, returnValue);
          if (null !== returnValue && "object" === typeof returnValue && "function" === typeof returnValue.then) {
            ReactSharedInternals.asyncTransitions++;
            returnValue.then(releaseAsyncTransition, releaseAsyncTransition);
            var thenableForFinishedState = chainThenableValue(
              returnValue,
              finishedState
            );
            dispatchSetStateInternal(
              fiber,
              queue,
              thenableForFinishedState,
              requestUpdateLane(fiber)
            );
          } else
            dispatchSetStateInternal(
              fiber,
              queue,
              finishedState,
              requestUpdateLane(fiber)
            );
        } catch (error) {
          dispatchSetStateInternal(
            fiber,
            queue,
            { then: function() {
            }, status: "rejected", reason: error },
            requestUpdateLane(fiber)
          );
        } finally {
          ReactDOMSharedInternals.p = previousPriority, null !== prevTransition && null !== currentTransition.types && (null !== prevTransition.types && prevTransition.types !== currentTransition.types && console.error(
            "We expected inner Transitions to have transferred the outer types set and that you cannot add to the outer Transition while inside the inner.This is a bug in React."
          ), prevTransition.types = currentTransition.types), ReactSharedInternals.T = prevTransition, null === prevTransition && currentTransition._updatedFibers && (fiber = currentTransition._updatedFibers.size, currentTransition._updatedFibers.clear(), 10 < fiber && console.warn(
            "Detected a large number of updates inside startTransition. If this is due to a subscription please re-write it to use React provided hooks. Otherwise concurrent mode guarantees are off the table."
          ));
        }
      }
      function startHostTransition(formFiber, pendingState, action, formData) {
        if (5 !== formFiber.tag)
          throw Error(
            "Expected the form instance to be a HostComponent. This is a bug in React."
          );
        var queue = ensureFormComponentIsStateful(formFiber).queue;
        startHostActionTimer(formFiber);
        startTransition(
          formFiber,
          queue,
          pendingState,
          NotPendingTransition,
          null === action ? noop3 : function() {
            requestFormReset$1(formFiber);
            return action(formData);
          }
        );
      }
      function ensureFormComponentIsStateful(formFiber) {
        var existingStateHook = formFiber.memoizedState;
        if (null !== existingStateHook) return existingStateHook;
        existingStateHook = {
          memoizedState: NotPendingTransition,
          baseState: NotPendingTransition,
          baseQueue: null,
          queue: {
            pending: null,
            lanes: 0,
            dispatch: null,
            lastRenderedReducer: basicStateReducer,
            lastRenderedState: NotPendingTransition
          },
          next: null
        };
        var initialResetState = {};
        existingStateHook.next = {
          memoizedState: initialResetState,
          baseState: initialResetState,
          baseQueue: null,
          queue: {
            pending: null,
            lanes: 0,
            dispatch: null,
            lastRenderedReducer: basicStateReducer,
            lastRenderedState: initialResetState
          },
          next: null
        };
        formFiber.memoizedState = existingStateHook;
        formFiber = formFiber.alternate;
        null !== formFiber && (formFiber.memoizedState = existingStateHook);
        return existingStateHook;
      }
      function requestFormReset$1(formFiber) {
        null === ReactSharedInternals.T && console.error(
          "requestFormReset was called outside a transition or action. To fix, move to an action, or wrap with startTransition."
        );
        var stateHook = ensureFormComponentIsStateful(formFiber);
        null === stateHook.next && (stateHook = formFiber.alternate.memoizedState);
        dispatchSetStateInternal(
          formFiber,
          stateHook.next.queue,
          {},
          requestUpdateLane(formFiber)
        );
      }
      function mountTransition() {
        var stateHook = mountStateImpl(false);
        stateHook = startTransition.bind(
          null,
          currentlyRenderingFiber,
          stateHook.queue,
          true,
          false
        );
        mountWorkInProgressHook().memoizedState = stateHook;
        return [false, stateHook];
      }
      function updateTransition() {
        var booleanOrThenable = updateReducer(basicStateReducer)[0], start = updateWorkInProgressHook().memoizedState;
        return [
          "boolean" === typeof booleanOrThenable ? booleanOrThenable : useThenable(booleanOrThenable),
          start
        ];
      }
      function rerenderTransition() {
        var booleanOrThenable = rerenderReducer(basicStateReducer)[0], start = updateWorkInProgressHook().memoizedState;
        return [
          "boolean" === typeof booleanOrThenable ? booleanOrThenable : useThenable(booleanOrThenable),
          start
        ];
      }
      function useHostTransitionStatus() {
        return readContext(HostTransitionContext);
      }
      function mountId() {
        var hook = mountWorkInProgressHook(), identifierPrefix = workInProgressRoot.identifierPrefix;
        if (isHydrating) {
          var treeId = treeContextOverflow;
          var idWithLeadingBit = treeContextId;
          treeId = (idWithLeadingBit & ~(1 << 32 - clz32(idWithLeadingBit) - 1)).toString(32) + treeId;
          identifierPrefix = "_" + identifierPrefix + "R_" + treeId;
          treeId = localIdCounter++;
          0 < treeId && (identifierPrefix += "H" + treeId.toString(32));
          identifierPrefix += "_";
        } else
          treeId = globalClientIdCounter++, identifierPrefix = "_" + identifierPrefix + "r_" + treeId.toString(32) + "_";
        return hook.memoizedState = identifierPrefix;
      }
      function mountRefresh() {
        return mountWorkInProgressHook().memoizedState = refreshCache.bind(
          null,
          currentlyRenderingFiber
        );
      }
      function refreshCache(fiber, seedKey) {
        for (var provider = fiber.return; null !== provider; ) {
          switch (provider.tag) {
            case 24:
            case 3:
              var lane = requestUpdateLane(provider), refreshUpdate = createUpdate(lane), root2 = enqueueUpdate(provider, refreshUpdate, lane);
              null !== root2 && (startUpdateTimerByLane(lane, "refresh()", fiber), scheduleUpdateOnFiber(root2, provider, lane), entangleTransitions(root2, provider, lane));
              fiber = createCache();
              null !== seedKey && void 0 !== seedKey && null !== root2 && console.error(
                "The seed argument is not enabled outside experimental channels."
              );
              refreshUpdate.payload = { cache: fiber };
              return;
          }
          provider = provider.return;
        }
      }
      function dispatchReducerAction(fiber, queue, action) {
        var args = arguments;
        "function" === typeof args[3] && console.error(
          "State updates from the useState() and useReducer() Hooks don't support the second callback argument. To execute a side effect after rendering, declare it in the component body with useEffect()."
        );
        args = requestUpdateLane(fiber);
        var update = {
          lane: args,
          revertLane: 0,
          gesture: null,
          action,
          hasEagerState: false,
          eagerState: null,
          next: null
        };
        isRenderPhaseUpdate(fiber) ? enqueueRenderPhaseUpdate(queue, update) : (update = enqueueConcurrentHookUpdate(fiber, queue, update, args), null !== update && (startUpdateTimerByLane(args, "dispatch()", fiber), scheduleUpdateOnFiber(update, fiber, args), entangleTransitionUpdate(update, queue, args)));
      }
      function dispatchSetState(fiber, queue, action) {
        var args = arguments;
        "function" === typeof args[3] && console.error(
          "State updates from the useState() and useReducer() Hooks don't support the second callback argument. To execute a side effect after rendering, declare it in the component body with useEffect()."
        );
        args = requestUpdateLane(fiber);
        dispatchSetStateInternal(fiber, queue, action, args) && startUpdateTimerByLane(args, "setState()", fiber);
      }
      function dispatchSetStateInternal(fiber, queue, action, lane) {
        var update = {
          lane,
          revertLane: 0,
          gesture: null,
          action,
          hasEagerState: false,
          eagerState: null,
          next: null
        };
        if (isRenderPhaseUpdate(fiber)) enqueueRenderPhaseUpdate(queue, update);
        else {
          var alternate = fiber.alternate;
          if (0 === fiber.lanes && (null === alternate || 0 === alternate.lanes) && (alternate = queue.lastRenderedReducer, null !== alternate)) {
            var prevDispatcher = ReactSharedInternals.H;
            ReactSharedInternals.H = InvalidNestedHooksDispatcherOnUpdateInDEV;
            try {
              var currentState = queue.lastRenderedState, eagerState = alternate(currentState, action);
              update.hasEagerState = true;
              update.eagerState = eagerState;
              if (objectIs(eagerState, currentState))
                return enqueueUpdate$1(fiber, queue, update, 0), null === workInProgressRoot && finishQueueingConcurrentUpdates(), false;
            } catch (error) {
            } finally {
              ReactSharedInternals.H = prevDispatcher;
            }
          }
          action = enqueueConcurrentHookUpdate(fiber, queue, update, lane);
          if (null !== action)
            return scheduleUpdateOnFiber(action, fiber, lane), entangleTransitionUpdate(action, queue, lane), true;
        }
        return false;
      }
      function dispatchOptimisticSetState(fiber, throwIfDuringRender, queue, action) {
        null === ReactSharedInternals.T && 0 === currentEntangledLane && console.error(
          "An optimistic state update occurred outside a transition or action. To fix, move the update to an action, or wrap with startTransition."
        );
        action = {
          lane: 2,
          revertLane: requestTransitionLane(),
          gesture: null,
          action,
          hasEagerState: false,
          eagerState: null,
          next: null
        };
        if (isRenderPhaseUpdate(fiber)) {
          if (throwIfDuringRender)
            throw Error("Cannot update optimistic state while rendering.");
          console.error("Cannot call startTransition while rendering.");
        } else
          throwIfDuringRender = enqueueConcurrentHookUpdate(
            fiber,
            queue,
            action,
            2
          ), null !== throwIfDuringRender && (startUpdateTimerByLane(2, "setOptimistic()", fiber), scheduleUpdateOnFiber(throwIfDuringRender, fiber, 2));
      }
      function isRenderPhaseUpdate(fiber) {
        var alternate = fiber.alternate;
        return fiber === currentlyRenderingFiber || null !== alternate && alternate === currentlyRenderingFiber;
      }
      function enqueueRenderPhaseUpdate(queue, update) {
        didScheduleRenderPhaseUpdateDuringThisPass = didScheduleRenderPhaseUpdate = true;
        var pending = queue.pending;
        null === pending ? update.next = update : (update.next = pending.next, pending.next = update);
        queue.pending = update;
      }
      function entangleTransitionUpdate(root2, queue, lane) {
        if (0 !== (lane & 4194048)) {
          var queueLanes = queue.lanes;
          queueLanes &= root2.pendingLanes;
          lane |= queueLanes;
          queue.lanes = lane;
          markRootEntangled(root2, lane);
        }
      }
      function warnOnInvalidCallback(callback) {
        if (null !== callback && "function" !== typeof callback) {
          var key = String(callback);
          didWarnOnInvalidCallback.has(key) || (didWarnOnInvalidCallback.add(key), console.error(
            "Expected the last optional `callback` argument to be a function. Instead received: %s.",
            callback
          ));
        }
      }
      function applyDerivedStateFromProps(workInProgress2, ctor, getDerivedStateFromProps, nextProps) {
        var prevState = workInProgress2.memoizedState, partialState = getDerivedStateFromProps(nextProps, prevState);
        if (workInProgress2.mode & StrictLegacyMode) {
          setIsStrictModeForDevtools(true);
          try {
            partialState = getDerivedStateFromProps(nextProps, prevState);
          } finally {
            setIsStrictModeForDevtools(false);
          }
        }
        void 0 === partialState && (ctor = getComponentNameFromType(ctor) || "Component", didWarnAboutUndefinedDerivedState.has(ctor) || (didWarnAboutUndefinedDerivedState.add(ctor), console.error(
          "%s.getDerivedStateFromProps(): A valid state object (or null) must be returned. You have returned undefined.",
          ctor
        )));
        prevState = null === partialState || void 0 === partialState ? prevState : assign({}, prevState, partialState);
        workInProgress2.memoizedState = prevState;
        0 === workInProgress2.lanes && (workInProgress2.updateQueue.baseState = prevState);
      }
      function checkShouldComponentUpdate(workInProgress2, ctor, oldProps, newProps, oldState, newState, nextContext) {
        var instance = workInProgress2.stateNode;
        if ("function" === typeof instance.shouldComponentUpdate) {
          oldProps = instance.shouldComponentUpdate(
            newProps,
            newState,
            nextContext
          );
          if (workInProgress2.mode & StrictLegacyMode) {
            setIsStrictModeForDevtools(true);
            try {
              oldProps = instance.shouldComponentUpdate(
                newProps,
                newState,
                nextContext
              );
            } finally {
              setIsStrictModeForDevtools(false);
            }
          }
          void 0 === oldProps && console.error(
            "%s.shouldComponentUpdate(): Returned undefined instead of a boolean value. Make sure to return true or false.",
            getComponentNameFromType(ctor) || "Component"
          );
          return oldProps;
        }
        return ctor.prototype && ctor.prototype.isPureReactComponent ? !shallowEqual2(oldProps, newProps) || !shallowEqual2(oldState, newState) : true;
      }
      function callComponentWillReceiveProps(workInProgress2, instance, newProps, nextContext) {
        var oldState = instance.state;
        "function" === typeof instance.componentWillReceiveProps && instance.componentWillReceiveProps(newProps, nextContext);
        "function" === typeof instance.UNSAFE_componentWillReceiveProps && instance.UNSAFE_componentWillReceiveProps(newProps, nextContext);
        instance.state !== oldState && (workInProgress2 = getComponentNameFromFiber(workInProgress2) || "Component", didWarnAboutStateAssignmentForComponent.has(workInProgress2) || (didWarnAboutStateAssignmentForComponent.add(workInProgress2), console.error(
          "%s.componentWillReceiveProps(): Assigning directly to this.state is deprecated (except inside a component's constructor). Use setState instead.",
          workInProgress2
        )), classComponentUpdater.enqueueReplaceState(
          instance,
          instance.state,
          null
        ));
      }
      function resolveClassComponentProps(Component, baseProps) {
        var newProps = baseProps;
        if ("ref" in baseProps) {
          newProps = {};
          for (var propName in baseProps)
            "ref" !== propName && (newProps[propName] = baseProps[propName]);
        }
        if (Component = Component.defaultProps) {
          newProps === baseProps && (newProps = assign({}, newProps));
          for (var _propName in Component)
            void 0 === newProps[_propName] && (newProps[_propName] = Component[_propName]);
        }
        return newProps;
      }
      function defaultOnUncaughtError(error) {
        reportGlobalError(error);
        console.warn(
          "%s\n\n%s\n",
          componentName ? "An error occurred in the <" + componentName + "> component." : "An error occurred in one of your React components.",
          "Consider adding an error boundary to your tree to customize error handling behavior.\nVisit https://react.dev/link/error-boundaries to learn more about error boundaries."
        );
      }
      function defaultOnCaughtError(error) {
        var componentNameMessage = componentName ? "The above error occurred in the <" + componentName + "> component." : "The above error occurred in one of your React components.", recreateMessage = "React will try to recreate this component tree from scratch using the error boundary you provided, " + ((errorBoundaryName || "Anonymous") + ".");
        if ("object" === typeof error && null !== error && "string" === typeof error.environmentName) {
          var JSCompiler_inline_result = error.environmentName;
          error = [
            "%o\n\n%s\n\n%s\n",
            error,
            componentNameMessage,
            recreateMessage
          ].slice(0);
          "string" === typeof error[0] ? error.splice(
            0,
            1,
            badgeFormat + " " + error[0],
            badgeStyle,
            pad2 + JSCompiler_inline_result + pad2,
            resetStyle
          ) : error.splice(
            0,
            0,
            badgeFormat,
            badgeStyle,
            pad2 + JSCompiler_inline_result + pad2,
            resetStyle
          );
          error.unshift(console);
          JSCompiler_inline_result = bind2.apply(console.error, error);
          JSCompiler_inline_result();
        } else
          console.error(
            "%o\n\n%s\n\n%s\n",
            error,
            componentNameMessage,
            recreateMessage
          );
      }
      function defaultOnRecoverableError(error) {
        reportGlobalError(error);
      }
      function logUncaughtError(root2, errorInfo) {
        try {
          componentName = errorInfo.source ? getComponentNameFromFiber(errorInfo.source) : null;
          errorBoundaryName = null;
          var error = errorInfo.value;
          if (null !== ReactSharedInternals.actQueue)
            ReactSharedInternals.thrownErrors.push(error);
          else {
            var onUncaughtError = root2.onUncaughtError;
            onUncaughtError(error, { componentStack: errorInfo.stack });
          }
        } catch (e$5) {
          setTimeout(function() {
            throw e$5;
          });
        }
      }
      function logCaughtError(root2, boundary, errorInfo) {
        try {
          componentName = errorInfo.source ? getComponentNameFromFiber(errorInfo.source) : null;
          errorBoundaryName = getComponentNameFromFiber(boundary);
          var onCaughtError = root2.onCaughtError;
          onCaughtError(errorInfo.value, {
            componentStack: errorInfo.stack,
            errorBoundary: 1 === boundary.tag ? boundary.stateNode : null
          });
        } catch (e$6) {
          setTimeout(function() {
            throw e$6;
          });
        }
      }
      function createRootErrorUpdate(root2, errorInfo, lane) {
        lane = createUpdate(lane);
        lane.tag = CaptureUpdate;
        lane.payload = { element: null };
        lane.callback = function() {
          runWithFiberInDEV(errorInfo.source, logUncaughtError, root2, errorInfo);
        };
        return lane;
      }
      function createClassErrorUpdate(lane) {
        lane = createUpdate(lane);
        lane.tag = CaptureUpdate;
        return lane;
      }
      function initializeClassErrorUpdate(update, root2, fiber, errorInfo) {
        var getDerivedStateFromError = fiber.type.getDerivedStateFromError;
        if ("function" === typeof getDerivedStateFromError) {
          var error = errorInfo.value;
          update.payload = function() {
            return getDerivedStateFromError(error);
          };
          update.callback = function() {
            markFailedErrorBoundaryForHotReloading(fiber);
            runWithFiberInDEV(
              errorInfo.source,
              logCaughtError,
              root2,
              fiber,
              errorInfo
            );
          };
        }
        var inst = fiber.stateNode;
        null !== inst && "function" === typeof inst.componentDidCatch && (update.callback = function() {
          markFailedErrorBoundaryForHotReloading(fiber);
          runWithFiberInDEV(
            errorInfo.source,
            logCaughtError,
            root2,
            fiber,
            errorInfo
          );
          "function" !== typeof getDerivedStateFromError && (null === legacyErrorBoundariesThatAlreadyFailed ? legacyErrorBoundariesThatAlreadyFailed = /* @__PURE__ */ new Set([this]) : legacyErrorBoundariesThatAlreadyFailed.add(this));
          callComponentDidCatchInDEV(this, errorInfo);
          "function" === typeof getDerivedStateFromError || 0 === (fiber.lanes & 2) && console.error(
            "%s: Error boundaries should implement getDerivedStateFromError(). In that method, return a state update to display an error message or fallback UI.",
            getComponentNameFromFiber(fiber) || "Unknown"
          );
        });
      }
      function throwException(root2, returnFiber, sourceFiber, value, rootRenderLanes) {
        sourceFiber.flags |= 32768;
        isDevToolsPresent && restorePendingUpdaters(root2, rootRenderLanes);
        if (null !== value && "object" === typeof value && "function" === typeof value.then) {
          returnFiber = sourceFiber.alternate;
          null !== returnFiber && propagateParentContextChanges(
            returnFiber,
            sourceFiber,
            rootRenderLanes,
            true
          );
          isHydrating && (didSuspendOrErrorDEV = true);
          sourceFiber = suspenseHandlerStackCursor.current;
          if (null !== sourceFiber) {
            switch (sourceFiber.tag) {
              case 31:
              case 13:
                return null === shellBoundary ? renderDidSuspendDelayIfPossible() : null === sourceFiber.alternate && workInProgressRootExitStatus === RootInProgress && (workInProgressRootExitStatus = RootSuspended), sourceFiber.flags &= -257, sourceFiber.flags |= 65536, sourceFiber.lanes = rootRenderLanes, value === noopSuspenseyCommitThenable ? sourceFiber.flags |= 16384 : (returnFiber = sourceFiber.updateQueue, null === returnFiber ? sourceFiber.updateQueue = /* @__PURE__ */ new Set([value]) : returnFiber.add(value), attachPingListener(root2, value, rootRenderLanes)), false;
              case 22:
                return sourceFiber.flags |= 65536, value === noopSuspenseyCommitThenable ? sourceFiber.flags |= 16384 : (returnFiber = sourceFiber.updateQueue, null === returnFiber ? (returnFiber = {
                  transitions: null,
                  markerInstances: null,
                  retryQueue: /* @__PURE__ */ new Set([value])
                }, sourceFiber.updateQueue = returnFiber) : (sourceFiber = returnFiber.retryQueue, null === sourceFiber ? returnFiber.retryQueue = /* @__PURE__ */ new Set([value]) : sourceFiber.add(value)), attachPingListener(root2, value, rootRenderLanes)), false;
            }
            throw Error(
              "Unexpected Suspense handler tag (" + sourceFiber.tag + "). This is a bug in React."
            );
          }
          attachPingListener(root2, value, rootRenderLanes);
          renderDidSuspendDelayIfPossible();
          return false;
        }
        if (isHydrating)
          return didSuspendOrErrorDEV = true, returnFiber = suspenseHandlerStackCursor.current, null !== returnFiber ? (0 === (returnFiber.flags & 65536) && (returnFiber.flags |= 256), returnFiber.flags |= 65536, returnFiber.lanes = rootRenderLanes, value !== HydrationMismatchException && queueHydrationError(
            createCapturedValueAtFiber(
              Error(
                "There was an error while hydrating but React was able to recover by instead client rendering from the nearest Suspense boundary.",
                { cause: value }
              ),
              sourceFiber
            )
          )) : (value !== HydrationMismatchException && queueHydrationError(
            createCapturedValueAtFiber(
              Error(
                "There was an error while hydrating but React was able to recover by instead client rendering the entire root.",
                { cause: value }
              ),
              sourceFiber
            )
          ), root2 = root2.current.alternate, root2.flags |= 65536, rootRenderLanes &= -rootRenderLanes, root2.lanes |= rootRenderLanes, value = createCapturedValueAtFiber(value, sourceFiber), rootRenderLanes = createRootErrorUpdate(
            root2.stateNode,
            value,
            rootRenderLanes
          ), enqueueCapturedUpdate(root2, rootRenderLanes), workInProgressRootExitStatus !== RootSuspendedWithDelay && (workInProgressRootExitStatus = RootErrored)), false;
        var error = createCapturedValueAtFiber(
          Error(
            "There was an error during concurrent rendering but React was able to recover by instead synchronously rendering the entire root.",
            { cause: value }
          ),
          sourceFiber
        );
        null === workInProgressRootConcurrentErrors ? workInProgressRootConcurrentErrors = [error] : workInProgressRootConcurrentErrors.push(error);
        workInProgressRootExitStatus !== RootSuspendedWithDelay && (workInProgressRootExitStatus = RootErrored);
        if (null === returnFiber) return true;
        value = createCapturedValueAtFiber(value, sourceFiber);
        sourceFiber = returnFiber;
        do {
          switch (sourceFiber.tag) {
            case 3:
              return sourceFiber.flags |= 65536, root2 = rootRenderLanes & -rootRenderLanes, sourceFiber.lanes |= root2, root2 = createRootErrorUpdate(
                sourceFiber.stateNode,
                value,
                root2
              ), enqueueCapturedUpdate(sourceFiber, root2), false;
            case 1:
              if (returnFiber = sourceFiber.type, error = sourceFiber.stateNode, 0 === (sourceFiber.flags & 128) && ("function" === typeof returnFiber.getDerivedStateFromError || null !== error && "function" === typeof error.componentDidCatch && (null === legacyErrorBoundariesThatAlreadyFailed || !legacyErrorBoundariesThatAlreadyFailed.has(error))))
                return sourceFiber.flags |= 65536, rootRenderLanes &= -rootRenderLanes, sourceFiber.lanes |= rootRenderLanes, rootRenderLanes = createClassErrorUpdate(rootRenderLanes), initializeClassErrorUpdate(
                  rootRenderLanes,
                  root2,
                  sourceFiber,
                  value
                ), enqueueCapturedUpdate(sourceFiber, rootRenderLanes), false;
          }
          sourceFiber = sourceFiber.return;
        } while (null !== sourceFiber);
        return false;
      }
      function reconcileChildren(current2, workInProgress2, nextChildren, renderLanes2) {
        workInProgress2.child = null === current2 ? mountChildFibers(workInProgress2, null, nextChildren, renderLanes2) : reconcileChildFibers(
          workInProgress2,
          current2.child,
          nextChildren,
          renderLanes2
        );
      }
      function updateForwardRef(current2, workInProgress2, Component, nextProps, renderLanes2) {
        Component = Component.render;
        var ref = workInProgress2.ref;
        if ("ref" in nextProps) {
          var propsWithoutRef = {};
          for (var key in nextProps)
            "ref" !== key && (propsWithoutRef[key] = nextProps[key]);
        } else propsWithoutRef = nextProps;
        prepareToReadContext(workInProgress2);
        nextProps = renderWithHooks(
          current2,
          workInProgress2,
          Component,
          propsWithoutRef,
          ref,
          renderLanes2
        );
        key = checkDidRenderIdHook();
        if (null !== current2 && !didReceiveUpdate)
          return bailoutHooks(current2, workInProgress2, renderLanes2), bailoutOnAlreadyFinishedWork(current2, workInProgress2, renderLanes2);
        isHydrating && key && pushMaterializedTreeId(workInProgress2);
        workInProgress2.flags |= 1;
        reconcileChildren(current2, workInProgress2, nextProps, renderLanes2);
        return workInProgress2.child;
      }
      function updateMemoComponent(current2, workInProgress2, Component, nextProps, renderLanes2) {
        if (null === current2) {
          var type = Component.type;
          if ("function" === typeof type && !shouldConstruct(type) && void 0 === type.defaultProps && null === Component.compare)
            return Component = resolveFunctionForHotReloading(type), workInProgress2.tag = 15, workInProgress2.type = Component, validateFunctionComponentInDev(workInProgress2, type), updateSimpleMemoComponent(
              current2,
              workInProgress2,
              Component,
              nextProps,
              renderLanes2
            );
          current2 = createFiberFromTypeAndProps(
            Component.type,
            null,
            nextProps,
            workInProgress2,
            workInProgress2.mode,
            renderLanes2
          );
          current2.ref = workInProgress2.ref;
          current2.return = workInProgress2;
          return workInProgress2.child = current2;
        }
        type = current2.child;
        if (!checkScheduledUpdateOrContext(current2, renderLanes2)) {
          var prevProps = type.memoizedProps;
          Component = Component.compare;
          Component = null !== Component ? Component : shallowEqual2;
          if (Component(prevProps, nextProps) && current2.ref === workInProgress2.ref)
            return bailoutOnAlreadyFinishedWork(
              current2,
              workInProgress2,
              renderLanes2
            );
        }
        workInProgress2.flags |= 1;
        current2 = createWorkInProgress(type, nextProps);
        current2.ref = workInProgress2.ref;
        current2.return = workInProgress2;
        return workInProgress2.child = current2;
      }
      function updateSimpleMemoComponent(current2, workInProgress2, Component, nextProps, renderLanes2) {
        if (null !== current2) {
          var prevProps = current2.memoizedProps;
          if (shallowEqual2(prevProps, nextProps) && current2.ref === workInProgress2.ref && workInProgress2.type === current2.type)
            if (didReceiveUpdate = false, workInProgress2.pendingProps = nextProps = prevProps, checkScheduledUpdateOrContext(current2, renderLanes2))
              0 !== (current2.flags & 131072) && (didReceiveUpdate = true);
            else
              return workInProgress2.lanes = current2.lanes, bailoutOnAlreadyFinishedWork(current2, workInProgress2, renderLanes2);
        }
        return updateFunctionComponent(
          current2,
          workInProgress2,
          Component,
          nextProps,
          renderLanes2
        );
      }
      function updateOffscreenComponent(current2, workInProgress2, renderLanes2, nextProps) {
        var nextChildren = nextProps.children, prevState = null !== current2 ? current2.memoizedState : null;
        null === current2 && null === workInProgress2.stateNode && (workInProgress2.stateNode = {
          _visibility: OffscreenVisible,
          _pendingMarkers: null,
          _retryCache: null,
          _transitions: null
        });
        if ("hidden" === nextProps.mode) {
          if (0 !== (workInProgress2.flags & 128)) {
            prevState = null !== prevState ? prevState.baseLanes | renderLanes2 : renderLanes2;
            if (null !== current2) {
              nextProps = workInProgress2.child = current2.child;
              for (nextChildren = 0; null !== nextProps; )
                nextChildren = nextChildren | nextProps.lanes | nextProps.childLanes, nextProps = nextProps.sibling;
              nextProps = nextChildren & ~prevState;
            } else nextProps = 0, workInProgress2.child = null;
            return deferHiddenOffscreenComponent(
              current2,
              workInProgress2,
              prevState,
              renderLanes2,
              nextProps
            );
          }
          if (0 !== (renderLanes2 & 536870912))
            workInProgress2.memoizedState = { baseLanes: 0, cachePool: null }, null !== current2 && pushTransition(
              workInProgress2,
              null !== prevState ? prevState.cachePool : null
            ), null !== prevState ? pushHiddenContext(workInProgress2, prevState) : reuseHiddenContextOnStack(workInProgress2), pushOffscreenSuspenseHandler(workInProgress2);
          else
            return nextProps = workInProgress2.lanes = 536870912, deferHiddenOffscreenComponent(
              current2,
              workInProgress2,
              null !== prevState ? prevState.baseLanes | renderLanes2 : renderLanes2,
              renderLanes2,
              nextProps
            );
        } else
          null !== prevState ? (pushTransition(workInProgress2, prevState.cachePool), pushHiddenContext(workInProgress2, prevState), reuseSuspenseHandlerOnStack(workInProgress2), workInProgress2.memoizedState = null) : (null !== current2 && pushTransition(workInProgress2, null), reuseHiddenContextOnStack(workInProgress2), reuseSuspenseHandlerOnStack(workInProgress2));
        reconcileChildren(current2, workInProgress2, nextChildren, renderLanes2);
        return workInProgress2.child;
      }
      function bailoutOffscreenComponent(current2, workInProgress2) {
        null !== current2 && 22 === current2.tag || null !== workInProgress2.stateNode || (workInProgress2.stateNode = {
          _visibility: OffscreenVisible,
          _pendingMarkers: null,
          _retryCache: null,
          _transitions: null
        });
        return workInProgress2.sibling;
      }
      function deferHiddenOffscreenComponent(current2, workInProgress2, nextBaseLanes, renderLanes2, remainingChildLanes) {
        var JSCompiler_inline_result = peekCacheFromPool();
        JSCompiler_inline_result = null === JSCompiler_inline_result ? null : {
          parent: CacheContext._currentValue,
          pool: JSCompiler_inline_result
        };
        workInProgress2.memoizedState = {
          baseLanes: nextBaseLanes,
          cachePool: JSCompiler_inline_result
        };
        null !== current2 && pushTransition(workInProgress2, null);
        reuseHiddenContextOnStack(workInProgress2);
        pushOffscreenSuspenseHandler(workInProgress2);
        null !== current2 && propagateParentContextChanges(current2, workInProgress2, renderLanes2, true);
        workInProgress2.childLanes = remainingChildLanes;
        return null;
      }
      function mountActivityChildren(workInProgress2, nextProps) {
        var hiddenProp = nextProps.hidden;
        void 0 !== hiddenProp && console.error(
          `<Activity> doesn't accept a hidden prop. Use mode="hidden" instead.
- <Activity %s>
+ <Activity %s>`,
          true === hiddenProp ? "hidden" : false === hiddenProp ? "hidden={false}" : "hidden={...}",
          hiddenProp ? 'mode="hidden"' : 'mode="visible"'
        );
        nextProps = mountWorkInProgressOffscreenFiber(
          { mode: nextProps.mode, children: nextProps.children },
          workInProgress2.mode
        );
        nextProps.ref = workInProgress2.ref;
        workInProgress2.child = nextProps;
        nextProps.return = workInProgress2;
        return nextProps;
      }
      function retryActivityComponentWithoutHydrating(current2, workInProgress2, renderLanes2) {
        reconcileChildFibers(workInProgress2, current2.child, null, renderLanes2);
        current2 = mountActivityChildren(
          workInProgress2,
          workInProgress2.pendingProps
        );
        current2.flags |= 2;
        popSuspenseHandler(workInProgress2);
        workInProgress2.memoizedState = null;
        return current2;
      }
      function updateActivityComponent(current2, workInProgress2, renderLanes2) {
        var nextProps = workInProgress2.pendingProps, didSuspend = 0 !== (workInProgress2.flags & 128);
        workInProgress2.flags &= -129;
        if (null === current2) {
          if (isHydrating) {
            if ("hidden" === nextProps.mode)
              return current2 = mountActivityChildren(workInProgress2, nextProps), workInProgress2.lanes = 536870912, bailoutOffscreenComponent(null, current2);
            pushDehydratedActivitySuspenseHandler(workInProgress2);
            (current2 = nextHydratableInstance) ? (renderLanes2 = canHydrateHydrationBoundary(
              current2,
              rootOrSingletonContext
            ), renderLanes2 = null !== renderLanes2 && renderLanes2.data === ACTIVITY_START_DATA ? renderLanes2 : null, null !== renderLanes2 && (nextProps = {
              dehydrated: renderLanes2,
              treeContext: getSuspendedTreeContext(),
              retryLane: 536870912,
              hydrationErrors: null
            }, workInProgress2.memoizedState = nextProps, nextProps = createFiberFromDehydratedFragment(renderLanes2), nextProps.return = workInProgress2, workInProgress2.child = nextProps, hydrationParentFiber = workInProgress2, nextHydratableInstance = null)) : renderLanes2 = null;
            if (null === renderLanes2)
              throw warnNonHydratedInstance(workInProgress2, current2), throwOnHydrationMismatch(workInProgress2);
            workInProgress2.lanes = 536870912;
            return null;
          }
          return mountActivityChildren(workInProgress2, nextProps);
        }
        var prevState = current2.memoizedState;
        if (null !== prevState) {
          var activityInstance = prevState.dehydrated;
          pushDehydratedActivitySuspenseHandler(workInProgress2);
          if (didSuspend)
            if (workInProgress2.flags & 256)
              workInProgress2.flags &= -257, workInProgress2 = retryActivityComponentWithoutHydrating(
                current2,
                workInProgress2,
                renderLanes2
              );
            else if (null !== workInProgress2.memoizedState)
              workInProgress2.child = current2.child, workInProgress2.flags |= 128, workInProgress2 = null;
            else
              throw Error(
                "Client rendering an Activity suspended it again. This is a bug in React."
              );
          else if (warnIfHydrating(), 0 !== (renderLanes2 & 536870912) && markRenderDerivedCause(workInProgress2), didReceiveUpdate || propagateParentContextChanges(
            current2,
            workInProgress2,
            renderLanes2,
            false
          ), didSuspend = 0 !== (renderLanes2 & current2.childLanes), didReceiveUpdate || didSuspend) {
            nextProps = workInProgressRoot;
            if (null !== nextProps && (activityInstance = getBumpedLaneForHydration(
              nextProps,
              renderLanes2
            ), 0 !== activityInstance && activityInstance !== prevState.retryLane))
              throw prevState.retryLane = activityInstance, enqueueConcurrentRenderForLane(current2, activityInstance), scheduleUpdateOnFiber(nextProps, current2, activityInstance), SelectiveHydrationException;
            renderDidSuspendDelayIfPossible();
            workInProgress2 = retryActivityComponentWithoutHydrating(
              current2,
              workInProgress2,
              renderLanes2
            );
          } else
            current2 = prevState.treeContext, nextHydratableInstance = getNextHydratable(
              activityInstance.nextSibling
            ), hydrationParentFiber = workInProgress2, isHydrating = true, hydrationErrors = null, didSuspendOrErrorDEV = false, hydrationDiffRootDEV = null, rootOrSingletonContext = false, null !== current2 && restoreSuspendedTreeContext(workInProgress2, current2), workInProgress2 = mountActivityChildren(workInProgress2, nextProps), workInProgress2.flags |= 4096;
          return workInProgress2;
        }
        prevState = current2.child;
        nextProps = { mode: nextProps.mode, children: nextProps.children };
        0 !== (renderLanes2 & 536870912) && 0 !== (renderLanes2 & current2.lanes) && markRenderDerivedCause(workInProgress2);
        current2 = createWorkInProgress(prevState, nextProps);
        current2.ref = workInProgress2.ref;
        workInProgress2.child = current2;
        current2.return = workInProgress2;
        return current2;
      }
      function markRef(current2, workInProgress2) {
        var ref = workInProgress2.ref;
        if (null === ref)
          null !== current2 && null !== current2.ref && (workInProgress2.flags |= 4194816);
        else {
          if ("function" !== typeof ref && "object" !== typeof ref)
            throw Error(
              "Expected ref to be a function, an object returned by React.createRef(), or undefined/null."
            );
          if (null === current2 || current2.ref !== ref)
            workInProgress2.flags |= 4194816;
        }
      }
      function updateFunctionComponent(current2, workInProgress2, Component, nextProps, renderLanes2) {
        if (Component.prototype && "function" === typeof Component.prototype.render) {
          var componentName2 = getComponentNameFromType(Component) || "Unknown";
          didWarnAboutBadClass[componentName2] || (console.error(
            "The <%s /> component appears to have a render method, but doesn't extend React.Component. This is likely to cause errors. Change %s to extend React.Component instead.",
            componentName2,
            componentName2
          ), didWarnAboutBadClass[componentName2] = true);
        }
        workInProgress2.mode & StrictLegacyMode && ReactStrictModeWarnings.recordLegacyContextWarning(
          workInProgress2,
          null
        );
        null === current2 && (validateFunctionComponentInDev(workInProgress2, workInProgress2.type), Component.contextTypes && (componentName2 = getComponentNameFromType(Component) || "Unknown", didWarnAboutContextTypes[componentName2] || (didWarnAboutContextTypes[componentName2] = true, console.error(
          "%s uses the legacy contextTypes API which was removed in React 19. Use React.createContext() with React.useContext() instead. (https://react.dev/link/legacy-context)",
          componentName2
        ))));
        prepareToReadContext(workInProgress2);
        Component = renderWithHooks(
          current2,
          workInProgress2,
          Component,
          nextProps,
          void 0,
          renderLanes2
        );
        nextProps = checkDidRenderIdHook();
        if (null !== current2 && !didReceiveUpdate)
          return bailoutHooks(current2, workInProgress2, renderLanes2), bailoutOnAlreadyFinishedWork(current2, workInProgress2, renderLanes2);
        isHydrating && nextProps && pushMaterializedTreeId(workInProgress2);
        workInProgress2.flags |= 1;
        reconcileChildren(current2, workInProgress2, Component, renderLanes2);
        return workInProgress2.child;
      }
      function replayFunctionComponent(current2, workInProgress2, nextProps, Component, secondArg, renderLanes2) {
        prepareToReadContext(workInProgress2);
        hookTypesUpdateIndexDev = -1;
        ignorePreviousDependencies = null !== current2 && current2.type !== workInProgress2.type;
        workInProgress2.updateQueue = null;
        nextProps = renderWithHooksAgain(
          workInProgress2,
          Component,
          nextProps,
          secondArg
        );
        finishRenderingHooks(current2, workInProgress2);
        Component = checkDidRenderIdHook();
        if (null !== current2 && !didReceiveUpdate)
          return bailoutHooks(current2, workInProgress2, renderLanes2), bailoutOnAlreadyFinishedWork(current2, workInProgress2, renderLanes2);
        isHydrating && Component && pushMaterializedTreeId(workInProgress2);
        workInProgress2.flags |= 1;
        reconcileChildren(current2, workInProgress2, nextProps, renderLanes2);
        return workInProgress2.child;
      }
      function updateClassComponent(current2, workInProgress2, Component, nextProps, renderLanes2) {
        switch (shouldErrorImpl(workInProgress2)) {
          case false:
            var _instance = workInProgress2.stateNode, state = new workInProgress2.type(
              workInProgress2.memoizedProps,
              _instance.context
            ).state;
            _instance.updater.enqueueSetState(_instance, state, null);
            break;
          case true:
            workInProgress2.flags |= 128;
            workInProgress2.flags |= 65536;
            _instance = Error("Simulated error coming from DevTools");
            var lane = renderLanes2 & -renderLanes2;
            workInProgress2.lanes |= lane;
            state = workInProgressRoot;
            if (null === state)
              throw Error(
                "Expected a work-in-progress root. This is a bug in React. Please file an issue."
              );
            lane = createClassErrorUpdate(lane);
            initializeClassErrorUpdate(
              lane,
              state,
              workInProgress2,
              createCapturedValueAtFiber(_instance, workInProgress2)
            );
            enqueueCapturedUpdate(workInProgress2, lane);
        }
        prepareToReadContext(workInProgress2);
        if (null === workInProgress2.stateNode) {
          state = emptyContextObject;
          _instance = Component.contextType;
          "contextType" in Component && null !== _instance && (void 0 === _instance || _instance.$$typeof !== REACT_CONTEXT_TYPE) && !didWarnAboutInvalidateContextType.has(Component) && (didWarnAboutInvalidateContextType.add(Component), lane = void 0 === _instance ? " However, it is set to undefined. This can be caused by a typo or by mixing up named and default imports. This can also happen due to a circular dependency, so try moving the createContext() call to a separate file." : "object" !== typeof _instance ? " However, it is set to a " + typeof _instance + "." : _instance.$$typeof === REACT_CONSUMER_TYPE ? " Did you accidentally pass the Context.Consumer instead?" : " However, it is set to an object with keys {" + Object.keys(_instance).join(", ") + "}.", console.error(
            "%s defines an invalid contextType. contextType should point to the Context object returned by React.createContext().%s",
            getComponentNameFromType(Component) || "Component",
            lane
          ));
          "object" === typeof _instance && null !== _instance && (state = readContext(_instance));
          _instance = new Component(nextProps, state);
          if (workInProgress2.mode & StrictLegacyMode) {
            setIsStrictModeForDevtools(true);
            try {
              _instance = new Component(nextProps, state);
            } finally {
              setIsStrictModeForDevtools(false);
            }
          }
          state = workInProgress2.memoizedState = null !== _instance.state && void 0 !== _instance.state ? _instance.state : null;
          _instance.updater = classComponentUpdater;
          workInProgress2.stateNode = _instance;
          _instance._reactInternals = workInProgress2;
          _instance._reactInternalInstance = fakeInternalInstance;
          "function" === typeof Component.getDerivedStateFromProps && null === state && (state = getComponentNameFromType(Component) || "Component", didWarnAboutUninitializedState.has(state) || (didWarnAboutUninitializedState.add(state), console.error(
            "`%s` uses `getDerivedStateFromProps` but its initial state is %s. This is not recommended. Instead, define the initial state by assigning an object to `this.state` in the constructor of `%s`. This ensures that `getDerivedStateFromProps` arguments have a consistent shape.",
            state,
            null === _instance.state ? "null" : "undefined",
            state
          )));
          if ("function" === typeof Component.getDerivedStateFromProps || "function" === typeof _instance.getSnapshotBeforeUpdate) {
            var foundWillUpdateName = lane = state = null;
            "function" === typeof _instance.componentWillMount && true !== _instance.componentWillMount.__suppressDeprecationWarning ? state = "componentWillMount" : "function" === typeof _instance.UNSAFE_componentWillMount && (state = "UNSAFE_componentWillMount");
            "function" === typeof _instance.componentWillReceiveProps && true !== _instance.componentWillReceiveProps.__suppressDeprecationWarning ? lane = "componentWillReceiveProps" : "function" === typeof _instance.UNSAFE_componentWillReceiveProps && (lane = "UNSAFE_componentWillReceiveProps");
            "function" === typeof _instance.componentWillUpdate && true !== _instance.componentWillUpdate.__suppressDeprecationWarning ? foundWillUpdateName = "componentWillUpdate" : "function" === typeof _instance.UNSAFE_componentWillUpdate && (foundWillUpdateName = "UNSAFE_componentWillUpdate");
            if (null !== state || null !== lane || null !== foundWillUpdateName) {
              _instance = getComponentNameFromType(Component) || "Component";
              var newApiName = "function" === typeof Component.getDerivedStateFromProps ? "getDerivedStateFromProps()" : "getSnapshotBeforeUpdate()";
              didWarnAboutLegacyLifecyclesAndDerivedState.has(_instance) || (didWarnAboutLegacyLifecyclesAndDerivedState.add(_instance), console.error(
                "Unsafe legacy lifecycles will not be called for components using new component APIs.\n\n%s uses %s but also contains the following legacy lifecycles:%s%s%s\n\nThe above lifecycles should be removed. Learn more about this warning here:\nhttps://react.dev/link/unsafe-component-lifecycles",
                _instance,
                newApiName,
                null !== state ? "\n  " + state : "",
                null !== lane ? "\n  " + lane : "",
                null !== foundWillUpdateName ? "\n  " + foundWillUpdateName : ""
              ));
            }
          }
          _instance = workInProgress2.stateNode;
          state = getComponentNameFromType(Component) || "Component";
          _instance.render || (Component.prototype && "function" === typeof Component.prototype.render ? console.error(
            "No `render` method found on the %s instance: did you accidentally return an object from the constructor?",
            state
          ) : console.error(
            "No `render` method found on the %s instance: you may have forgotten to define `render`.",
            state
          ));
          !_instance.getInitialState || _instance.getInitialState.isReactClassApproved || _instance.state || console.error(
            "getInitialState was defined on %s, a plain JavaScript class. This is only supported for classes created using React.createClass. Did you mean to define a state property instead?",
            state
          );
          _instance.getDefaultProps && !_instance.getDefaultProps.isReactClassApproved && console.error(
            "getDefaultProps was defined on %s, a plain JavaScript class. This is only supported for classes created using React.createClass. Use a static property to define defaultProps instead.",
            state
          );
          _instance.contextType && console.error(
            "contextType was defined as an instance property on %s. Use a static property to define contextType instead.",
            state
          );
          Component.childContextTypes && !didWarnAboutChildContextTypes.has(Component) && (didWarnAboutChildContextTypes.add(Component), console.error(
            "%s uses the legacy childContextTypes API which was removed in React 19. Use React.createContext() instead. (https://react.dev/link/legacy-context)",
            state
          ));
          Component.contextTypes && !didWarnAboutContextTypes$1.has(Component) && (didWarnAboutContextTypes$1.add(Component), console.error(
            "%s uses the legacy contextTypes API which was removed in React 19. Use React.createContext() with static contextType instead. (https://react.dev/link/legacy-context)",
            state
          ));
          "function" === typeof _instance.componentShouldUpdate && console.error(
            "%s has a method called componentShouldUpdate(). Did you mean shouldComponentUpdate()? The name is phrased as a question because the function is expected to return a value.",
            state
          );
          Component.prototype && Component.prototype.isPureReactComponent && "undefined" !== typeof _instance.shouldComponentUpdate && console.error(
            "%s has a method called shouldComponentUpdate(). shouldComponentUpdate should not be used when extending React.PureComponent. Please extend React.Component if shouldComponentUpdate is used.",
            getComponentNameFromType(Component) || "A pure component"
          );
          "function" === typeof _instance.componentDidUnmount && console.error(
            "%s has a method called componentDidUnmount(). But there is no such lifecycle method. Did you mean componentWillUnmount()?",
            state
          );
          "function" === typeof _instance.componentDidReceiveProps && console.error(
            "%s has a method called componentDidReceiveProps(). But there is no such lifecycle method. If you meant to update the state in response to changing props, use componentWillReceiveProps(). If you meant to fetch data or run side-effects or mutations after React has updated the UI, use componentDidUpdate().",
            state
          );
          "function" === typeof _instance.componentWillRecieveProps && console.error(
            "%s has a method called componentWillRecieveProps(). Did you mean componentWillReceiveProps()?",
            state
          );
          "function" === typeof _instance.UNSAFE_componentWillRecieveProps && console.error(
            "%s has a method called UNSAFE_componentWillRecieveProps(). Did you mean UNSAFE_componentWillReceiveProps()?",
            state
          );
          lane = _instance.props !== nextProps;
          void 0 !== _instance.props && lane && console.error(
            "When calling super() in `%s`, make sure to pass up the same props that your component's constructor was passed.",
            state
          );
          _instance.defaultProps && console.error(
            "Setting defaultProps as an instance property on %s is not supported and will be ignored. Instead, define defaultProps as a static property on %s.",
            state,
            state
          );
          "function" !== typeof _instance.getSnapshotBeforeUpdate || "function" === typeof _instance.componentDidUpdate || didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.has(Component) || (didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.add(Component), console.error(
            "%s: getSnapshotBeforeUpdate() should be used with componentDidUpdate(). This component defines getSnapshotBeforeUpdate() only.",
            getComponentNameFromType(Component)
          ));
          "function" === typeof _instance.getDerivedStateFromProps && console.error(
            "%s: getDerivedStateFromProps() is defined as an instance method and will be ignored. Instead, declare it as a static method.",
            state
          );
          "function" === typeof _instance.getDerivedStateFromError && console.error(
            "%s: getDerivedStateFromError() is defined as an instance method and will be ignored. Instead, declare it as a static method.",
            state
          );
          "function" === typeof Component.getSnapshotBeforeUpdate && console.error(
            "%s: getSnapshotBeforeUpdate() is defined as a static method and will be ignored. Instead, declare it as an instance method.",
            state
          );
          (lane = _instance.state) && ("object" !== typeof lane || isArrayImpl(lane)) && console.error("%s.state: must be set to an object or null", state);
          "function" === typeof _instance.getChildContext && "object" !== typeof Component.childContextTypes && console.error(
            "%s.getChildContext(): childContextTypes must be defined in order to use getChildContext().",
            state
          );
          _instance = workInProgress2.stateNode;
          _instance.props = nextProps;
          _instance.state = workInProgress2.memoizedState;
          _instance.refs = {};
          initializeUpdateQueue(workInProgress2);
          state = Component.contextType;
          _instance.context = "object" === typeof state && null !== state ? readContext(state) : emptyContextObject;
          _instance.state === nextProps && (state = getComponentNameFromType(Component) || "Component", didWarnAboutDirectlyAssigningPropsToState.has(state) || (didWarnAboutDirectlyAssigningPropsToState.add(state), console.error(
            "%s: It is not recommended to assign props directly to state because updates to props won't be reflected in state. In most cases, it is better to use props directly.",
            state
          )));
          workInProgress2.mode & StrictLegacyMode && ReactStrictModeWarnings.recordLegacyContextWarning(
            workInProgress2,
            _instance
          );
          ReactStrictModeWarnings.recordUnsafeLifecycleWarnings(
            workInProgress2,
            _instance
          );
          _instance.state = workInProgress2.memoizedState;
          state = Component.getDerivedStateFromProps;
          "function" === typeof state && (applyDerivedStateFromProps(
            workInProgress2,
            Component,
            state,
            nextProps
          ), _instance.state = workInProgress2.memoizedState);
          "function" === typeof Component.getDerivedStateFromProps || "function" === typeof _instance.getSnapshotBeforeUpdate || "function" !== typeof _instance.UNSAFE_componentWillMount && "function" !== typeof _instance.componentWillMount || (state = _instance.state, "function" === typeof _instance.componentWillMount && _instance.componentWillMount(), "function" === typeof _instance.UNSAFE_componentWillMount && _instance.UNSAFE_componentWillMount(), state !== _instance.state && (console.error(
            "%s.componentWillMount(): Assigning directly to this.state is deprecated (except inside a component's constructor). Use setState instead.",
            getComponentNameFromFiber(workInProgress2) || "Component"
          ), classComponentUpdater.enqueueReplaceState(
            _instance,
            _instance.state,
            null
          )), processUpdateQueue(workInProgress2, nextProps, _instance, renderLanes2), suspendIfUpdateReadFromEntangledAsyncAction(), _instance.state = workInProgress2.memoizedState);
          "function" === typeof _instance.componentDidMount && (workInProgress2.flags |= 4194308);
          (workInProgress2.mode & StrictEffectsMode) !== NoMode && (workInProgress2.flags |= 134217728);
          _instance = true;
        } else if (null === current2) {
          _instance = workInProgress2.stateNode;
          var unresolvedOldProps = workInProgress2.memoizedProps;
          lane = resolveClassComponentProps(Component, unresolvedOldProps);
          _instance.props = lane;
          var oldContext = _instance.context;
          foundWillUpdateName = Component.contextType;
          state = emptyContextObject;
          "object" === typeof foundWillUpdateName && null !== foundWillUpdateName && (state = readContext(foundWillUpdateName));
          newApiName = Component.getDerivedStateFromProps;
          foundWillUpdateName = "function" === typeof newApiName || "function" === typeof _instance.getSnapshotBeforeUpdate;
          unresolvedOldProps = workInProgress2.pendingProps !== unresolvedOldProps;
          foundWillUpdateName || "function" !== typeof _instance.UNSAFE_componentWillReceiveProps && "function" !== typeof _instance.componentWillReceiveProps || (unresolvedOldProps || oldContext !== state) && callComponentWillReceiveProps(
            workInProgress2,
            _instance,
            nextProps,
            state
          );
          hasForceUpdate = false;
          var oldState = workInProgress2.memoizedState;
          _instance.state = oldState;
          processUpdateQueue(workInProgress2, nextProps, _instance, renderLanes2);
          suspendIfUpdateReadFromEntangledAsyncAction();
          oldContext = workInProgress2.memoizedState;
          unresolvedOldProps || oldState !== oldContext || hasForceUpdate ? ("function" === typeof newApiName && (applyDerivedStateFromProps(
            workInProgress2,
            Component,
            newApiName,
            nextProps
          ), oldContext = workInProgress2.memoizedState), (lane = hasForceUpdate || checkShouldComponentUpdate(
            workInProgress2,
            Component,
            lane,
            nextProps,
            oldState,
            oldContext,
            state
          )) ? (foundWillUpdateName || "function" !== typeof _instance.UNSAFE_componentWillMount && "function" !== typeof _instance.componentWillMount || ("function" === typeof _instance.componentWillMount && _instance.componentWillMount(), "function" === typeof _instance.UNSAFE_componentWillMount && _instance.UNSAFE_componentWillMount()), "function" === typeof _instance.componentDidMount && (workInProgress2.flags |= 4194308), (workInProgress2.mode & StrictEffectsMode) !== NoMode && (workInProgress2.flags |= 134217728)) : ("function" === typeof _instance.componentDidMount && (workInProgress2.flags |= 4194308), (workInProgress2.mode & StrictEffectsMode) !== NoMode && (workInProgress2.flags |= 134217728), workInProgress2.memoizedProps = nextProps, workInProgress2.memoizedState = oldContext), _instance.props = nextProps, _instance.state = oldContext, _instance.context = state, _instance = lane) : ("function" === typeof _instance.componentDidMount && (workInProgress2.flags |= 4194308), (workInProgress2.mode & StrictEffectsMode) !== NoMode && (workInProgress2.flags |= 134217728), _instance = false);
        } else {
          _instance = workInProgress2.stateNode;
          cloneUpdateQueue(current2, workInProgress2);
          state = workInProgress2.memoizedProps;
          foundWillUpdateName = resolveClassComponentProps(Component, state);
          _instance.props = foundWillUpdateName;
          newApiName = workInProgress2.pendingProps;
          oldState = _instance.context;
          oldContext = Component.contextType;
          lane = emptyContextObject;
          "object" === typeof oldContext && null !== oldContext && (lane = readContext(oldContext));
          unresolvedOldProps = Component.getDerivedStateFromProps;
          (oldContext = "function" === typeof unresolvedOldProps || "function" === typeof _instance.getSnapshotBeforeUpdate) || "function" !== typeof _instance.UNSAFE_componentWillReceiveProps && "function" !== typeof _instance.componentWillReceiveProps || (state !== newApiName || oldState !== lane) && callComponentWillReceiveProps(
            workInProgress2,
            _instance,
            nextProps,
            lane
          );
          hasForceUpdate = false;
          oldState = workInProgress2.memoizedState;
          _instance.state = oldState;
          processUpdateQueue(workInProgress2, nextProps, _instance, renderLanes2);
          suspendIfUpdateReadFromEntangledAsyncAction();
          var newState = workInProgress2.memoizedState;
          state !== newApiName || oldState !== newState || hasForceUpdate || null !== current2 && null !== current2.dependencies && checkIfContextChanged(current2.dependencies) ? ("function" === typeof unresolvedOldProps && (applyDerivedStateFromProps(
            workInProgress2,
            Component,
            unresolvedOldProps,
            nextProps
          ), newState = workInProgress2.memoizedState), (foundWillUpdateName = hasForceUpdate || checkShouldComponentUpdate(
            workInProgress2,
            Component,
            foundWillUpdateName,
            nextProps,
            oldState,
            newState,
            lane
          ) || null !== current2 && null !== current2.dependencies && checkIfContextChanged(current2.dependencies)) ? (oldContext || "function" !== typeof _instance.UNSAFE_componentWillUpdate && "function" !== typeof _instance.componentWillUpdate || ("function" === typeof _instance.componentWillUpdate && _instance.componentWillUpdate(nextProps, newState, lane), "function" === typeof _instance.UNSAFE_componentWillUpdate && _instance.UNSAFE_componentWillUpdate(
            nextProps,
            newState,
            lane
          )), "function" === typeof _instance.componentDidUpdate && (workInProgress2.flags |= 4), "function" === typeof _instance.getSnapshotBeforeUpdate && (workInProgress2.flags |= 1024)) : ("function" !== typeof _instance.componentDidUpdate || state === current2.memoizedProps && oldState === current2.memoizedState || (workInProgress2.flags |= 4), "function" !== typeof _instance.getSnapshotBeforeUpdate || state === current2.memoizedProps && oldState === current2.memoizedState || (workInProgress2.flags |= 1024), workInProgress2.memoizedProps = nextProps, workInProgress2.memoizedState = newState), _instance.props = nextProps, _instance.state = newState, _instance.context = lane, _instance = foundWillUpdateName) : ("function" !== typeof _instance.componentDidUpdate || state === current2.memoizedProps && oldState === current2.memoizedState || (workInProgress2.flags |= 4), "function" !== typeof _instance.getSnapshotBeforeUpdate || state === current2.memoizedProps && oldState === current2.memoizedState || (workInProgress2.flags |= 1024), _instance = false);
        }
        lane = _instance;
        markRef(current2, workInProgress2);
        state = 0 !== (workInProgress2.flags & 128);
        if (lane || state) {
          lane = workInProgress2.stateNode;
          setCurrentFiber(workInProgress2);
          if (state && "function" !== typeof Component.getDerivedStateFromError)
            Component = null, profilerStartTime = -1;
          else if (Component = callRenderInDEV(lane), workInProgress2.mode & StrictLegacyMode) {
            setIsStrictModeForDevtools(true);
            try {
              callRenderInDEV(lane);
            } finally {
              setIsStrictModeForDevtools(false);
            }
          }
          workInProgress2.flags |= 1;
          null !== current2 && state ? (workInProgress2.child = reconcileChildFibers(
            workInProgress2,
            current2.child,
            null,
            renderLanes2
          ), workInProgress2.child = reconcileChildFibers(
            workInProgress2,
            null,
            Component,
            renderLanes2
          )) : reconcileChildren(current2, workInProgress2, Component, renderLanes2);
          workInProgress2.memoizedState = lane.state;
          current2 = workInProgress2.child;
        } else
          current2 = bailoutOnAlreadyFinishedWork(
            current2,
            workInProgress2,
            renderLanes2
          );
        renderLanes2 = workInProgress2.stateNode;
        _instance && renderLanes2.props !== nextProps && (didWarnAboutReassigningProps || console.error(
          "It looks like %s is reassigning its own `this.props` while rendering. This is not supported and can lead to confusing bugs.",
          getComponentNameFromFiber(workInProgress2) || "a component"
        ), didWarnAboutReassigningProps = true);
        return current2;
      }
      function mountHostRootWithoutHydrating(current2, workInProgress2, nextChildren, renderLanes2) {
        resetHydrationState();
        workInProgress2.flags |= 256;
        reconcileChildren(current2, workInProgress2, nextChildren, renderLanes2);
        return workInProgress2.child;
      }
      function validateFunctionComponentInDev(workInProgress2, Component) {
        Component && Component.childContextTypes && console.error(
          "childContextTypes cannot be defined on a function component.\n  %s.childContextTypes = ...",
          Component.displayName || Component.name || "Component"
        );
        "function" === typeof Component.getDerivedStateFromProps && (workInProgress2 = getComponentNameFromType(Component) || "Unknown", didWarnAboutGetDerivedStateOnFunctionComponent[workInProgress2] || (console.error(
          "%s: Function components do not support getDerivedStateFromProps.",
          workInProgress2
        ), didWarnAboutGetDerivedStateOnFunctionComponent[workInProgress2] = true));
        "object" === typeof Component.contextType && null !== Component.contextType && (Component = getComponentNameFromType(Component) || "Unknown", didWarnAboutContextTypeOnFunctionComponent[Component] || (console.error(
          "%s: Function components do not support contextType.",
          Component
        ), didWarnAboutContextTypeOnFunctionComponent[Component] = true));
      }
      function mountSuspenseOffscreenState(renderLanes2) {
        return { baseLanes: renderLanes2, cachePool: getSuspendedCache() };
      }
      function getRemainingWorkInPrimaryTree(current2, primaryTreeDidDefer, renderLanes2) {
        current2 = null !== current2 ? current2.childLanes & ~renderLanes2 : 0;
        primaryTreeDidDefer && (current2 |= workInProgressDeferredLane);
        return current2;
      }
      function updateSuspenseComponent(current2, workInProgress2, renderLanes2) {
        var JSCompiler_object_inline_digest_2724;
        var JSCompiler_object_inline_stack_2725 = workInProgress2.pendingProps;
        shouldSuspendImpl(workInProgress2) && (workInProgress2.flags |= 128);
        var JSCompiler_object_inline_message_2723 = false;
        var didSuspend = 0 !== (workInProgress2.flags & 128);
        (JSCompiler_object_inline_digest_2724 = didSuspend) || (JSCompiler_object_inline_digest_2724 = null !== current2 && null === current2.memoizedState ? false : 0 !== (suspenseStackCursor.current & ForceSuspenseFallback));
        JSCompiler_object_inline_digest_2724 && (JSCompiler_object_inline_message_2723 = true, workInProgress2.flags &= -129);
        JSCompiler_object_inline_digest_2724 = 0 !== (workInProgress2.flags & 32);
        workInProgress2.flags &= -33;
        if (null === current2) {
          if (isHydrating) {
            JSCompiler_object_inline_message_2723 ? pushPrimaryTreeSuspenseHandler(workInProgress2) : reuseSuspenseHandlerOnStack(workInProgress2);
            (current2 = nextHydratableInstance) ? (renderLanes2 = canHydrateHydrationBoundary(
              current2,
              rootOrSingletonContext
            ), renderLanes2 = null !== renderLanes2 && renderLanes2.data !== ACTIVITY_START_DATA ? renderLanes2 : null, null !== renderLanes2 && (JSCompiler_object_inline_digest_2724 = {
              dehydrated: renderLanes2,
              treeContext: getSuspendedTreeContext(),
              retryLane: 536870912,
              hydrationErrors: null
            }, workInProgress2.memoizedState = JSCompiler_object_inline_digest_2724, JSCompiler_object_inline_digest_2724 = createFiberFromDehydratedFragment(renderLanes2), JSCompiler_object_inline_digest_2724.return = workInProgress2, workInProgress2.child = JSCompiler_object_inline_digest_2724, hydrationParentFiber = workInProgress2, nextHydratableInstance = null)) : renderLanes2 = null;
            if (null === renderLanes2)
              throw warnNonHydratedInstance(workInProgress2, current2), throwOnHydrationMismatch(workInProgress2);
            isSuspenseInstanceFallback(renderLanes2) ? workInProgress2.lanes = 32 : workInProgress2.lanes = 536870912;
            return null;
          }
          var nextPrimaryChildren = JSCompiler_object_inline_stack_2725.children;
          JSCompiler_object_inline_stack_2725 = JSCompiler_object_inline_stack_2725.fallback;
          if (JSCompiler_object_inline_message_2723) {
            reuseSuspenseHandlerOnStack(workInProgress2);
            var mode = workInProgress2.mode;
            nextPrimaryChildren = mountWorkInProgressOffscreenFiber(
              { mode: "hidden", children: nextPrimaryChildren },
              mode
            );
            JSCompiler_object_inline_stack_2725 = createFiberFromFragment(
              JSCompiler_object_inline_stack_2725,
              mode,
              renderLanes2,
              null
            );
            nextPrimaryChildren.return = workInProgress2;
            JSCompiler_object_inline_stack_2725.return = workInProgress2;
            nextPrimaryChildren.sibling = JSCompiler_object_inline_stack_2725;
            workInProgress2.child = nextPrimaryChildren;
            JSCompiler_object_inline_stack_2725 = workInProgress2.child;
            JSCompiler_object_inline_stack_2725.memoizedState = mountSuspenseOffscreenState(renderLanes2);
            JSCompiler_object_inline_stack_2725.childLanes = getRemainingWorkInPrimaryTree(
              current2,
              JSCompiler_object_inline_digest_2724,
              renderLanes2
            );
            workInProgress2.memoizedState = SUSPENDED_MARKER;
            return bailoutOffscreenComponent(
              null,
              JSCompiler_object_inline_stack_2725
            );
          }
          pushPrimaryTreeSuspenseHandler(workInProgress2);
          return mountSuspensePrimaryChildren(
            workInProgress2,
            nextPrimaryChildren
          );
        }
        var prevState = current2.memoizedState;
        if (null !== prevState) {
          var JSCompiler_object_inline_componentStack_2726 = prevState.dehydrated;
          if (null !== JSCompiler_object_inline_componentStack_2726) {
            if (didSuspend)
              workInProgress2.flags & 256 ? (pushPrimaryTreeSuspenseHandler(workInProgress2), workInProgress2.flags &= -257, workInProgress2 = retrySuspenseComponentWithoutHydrating(
                current2,
                workInProgress2,
                renderLanes2
              )) : null !== workInProgress2.memoizedState ? (reuseSuspenseHandlerOnStack(workInProgress2), workInProgress2.child = current2.child, workInProgress2.flags |= 128, workInProgress2 = null) : (reuseSuspenseHandlerOnStack(workInProgress2), nextPrimaryChildren = JSCompiler_object_inline_stack_2725.fallback, mode = workInProgress2.mode, JSCompiler_object_inline_stack_2725 = mountWorkInProgressOffscreenFiber(
                {
                  mode: "visible",
                  children: JSCompiler_object_inline_stack_2725.children
                },
                mode
              ), nextPrimaryChildren = createFiberFromFragment(
                nextPrimaryChildren,
                mode,
                renderLanes2,
                null
              ), nextPrimaryChildren.flags |= 2, JSCompiler_object_inline_stack_2725.return = workInProgress2, nextPrimaryChildren.return = workInProgress2, JSCompiler_object_inline_stack_2725.sibling = nextPrimaryChildren, workInProgress2.child = JSCompiler_object_inline_stack_2725, reconcileChildFibers(
                workInProgress2,
                current2.child,
                null,
                renderLanes2
              ), JSCompiler_object_inline_stack_2725 = workInProgress2.child, JSCompiler_object_inline_stack_2725.memoizedState = mountSuspenseOffscreenState(renderLanes2), JSCompiler_object_inline_stack_2725.childLanes = getRemainingWorkInPrimaryTree(
                current2,
                JSCompiler_object_inline_digest_2724,
                renderLanes2
              ), workInProgress2.memoizedState = SUSPENDED_MARKER, workInProgress2 = bailoutOffscreenComponent(
                null,
                JSCompiler_object_inline_stack_2725
              ));
            else if (pushPrimaryTreeSuspenseHandler(workInProgress2), warnIfHydrating(), 0 !== (renderLanes2 & 536870912) && markRenderDerivedCause(workInProgress2), isSuspenseInstanceFallback(
              JSCompiler_object_inline_componentStack_2726
            )) {
              JSCompiler_object_inline_digest_2724 = JSCompiler_object_inline_componentStack_2726.nextSibling && JSCompiler_object_inline_componentStack_2726.nextSibling.dataset;
              if (JSCompiler_object_inline_digest_2724) {
                nextPrimaryChildren = JSCompiler_object_inline_digest_2724.dgst;
                var message = JSCompiler_object_inline_digest_2724.msg;
                mode = JSCompiler_object_inline_digest_2724.stck;
                var componentStack = JSCompiler_object_inline_digest_2724.cstck;
              }
              JSCompiler_object_inline_message_2723 = message;
              JSCompiler_object_inline_digest_2724 = nextPrimaryChildren;
              JSCompiler_object_inline_stack_2725 = mode;
              JSCompiler_object_inline_componentStack_2726 = componentStack;
              nextPrimaryChildren = JSCompiler_object_inline_message_2723;
              mode = JSCompiler_object_inline_componentStack_2726;
              nextPrimaryChildren = nextPrimaryChildren ? Error(nextPrimaryChildren) : Error(
                "The server could not finish this Suspense boundary, likely due to an error during server rendering. Switched to client rendering."
              );
              nextPrimaryChildren.stack = JSCompiler_object_inline_stack_2725 || "";
              nextPrimaryChildren.digest = JSCompiler_object_inline_digest_2724;
              JSCompiler_object_inline_digest_2724 = void 0 === mode ? null : mode;
              JSCompiler_object_inline_stack_2725 = {
                value: nextPrimaryChildren,
                source: null,
                stack: JSCompiler_object_inline_digest_2724
              };
              "string" === typeof JSCompiler_object_inline_digest_2724 && CapturedStacks.set(
                nextPrimaryChildren,
                JSCompiler_object_inline_stack_2725
              );
              queueHydrationError(JSCompiler_object_inline_stack_2725);
              workInProgress2 = retrySuspenseComponentWithoutHydrating(
                current2,
                workInProgress2,
                renderLanes2
              );
            } else if (didReceiveUpdate || propagateParentContextChanges(
              current2,
              workInProgress2,
              renderLanes2,
              false
            ), JSCompiler_object_inline_digest_2724 = 0 !== (renderLanes2 & current2.childLanes), didReceiveUpdate || JSCompiler_object_inline_digest_2724) {
              JSCompiler_object_inline_digest_2724 = workInProgressRoot;
              if (null !== JSCompiler_object_inline_digest_2724 && (JSCompiler_object_inline_stack_2725 = getBumpedLaneForHydration(
                JSCompiler_object_inline_digest_2724,
                renderLanes2
              ), 0 !== JSCompiler_object_inline_stack_2725 && JSCompiler_object_inline_stack_2725 !== prevState.retryLane))
                throw prevState.retryLane = JSCompiler_object_inline_stack_2725, enqueueConcurrentRenderForLane(
                  current2,
                  JSCompiler_object_inline_stack_2725
                ), scheduleUpdateOnFiber(
                  JSCompiler_object_inline_digest_2724,
                  current2,
                  JSCompiler_object_inline_stack_2725
                ), SelectiveHydrationException;
              isSuspenseInstancePending(
                JSCompiler_object_inline_componentStack_2726
              ) || renderDidSuspendDelayIfPossible();
              workInProgress2 = retrySuspenseComponentWithoutHydrating(
                current2,
                workInProgress2,
                renderLanes2
              );
            } else
              isSuspenseInstancePending(
                JSCompiler_object_inline_componentStack_2726
              ) ? (workInProgress2.flags |= 192, workInProgress2.child = current2.child, workInProgress2 = null) : (current2 = prevState.treeContext, nextHydratableInstance = getNextHydratable(
                JSCompiler_object_inline_componentStack_2726.nextSibling
              ), hydrationParentFiber = workInProgress2, isHydrating = true, hydrationErrors = null, didSuspendOrErrorDEV = false, hydrationDiffRootDEV = null, rootOrSingletonContext = false, null !== current2 && restoreSuspendedTreeContext(workInProgress2, current2), workInProgress2 = mountSuspensePrimaryChildren(
                workInProgress2,
                JSCompiler_object_inline_stack_2725.children
              ), workInProgress2.flags |= 4096);
            return workInProgress2;
          }
        }
        if (JSCompiler_object_inline_message_2723)
          return reuseSuspenseHandlerOnStack(workInProgress2), nextPrimaryChildren = JSCompiler_object_inline_stack_2725.fallback, mode = workInProgress2.mode, componentStack = current2.child, JSCompiler_object_inline_componentStack_2726 = componentStack.sibling, JSCompiler_object_inline_stack_2725 = createWorkInProgress(
            componentStack,
            {
              mode: "hidden",
              children: JSCompiler_object_inline_stack_2725.children
            }
          ), JSCompiler_object_inline_stack_2725.subtreeFlags = componentStack.subtreeFlags & 65011712, null !== JSCompiler_object_inline_componentStack_2726 ? nextPrimaryChildren = createWorkInProgress(
            JSCompiler_object_inline_componentStack_2726,
            nextPrimaryChildren
          ) : (nextPrimaryChildren = createFiberFromFragment(
            nextPrimaryChildren,
            mode,
            renderLanes2,
            null
          ), nextPrimaryChildren.flags |= 2), nextPrimaryChildren.return = workInProgress2, JSCompiler_object_inline_stack_2725.return = workInProgress2, JSCompiler_object_inline_stack_2725.sibling = nextPrimaryChildren, workInProgress2.child = JSCompiler_object_inline_stack_2725, bailoutOffscreenComponent(null, JSCompiler_object_inline_stack_2725), JSCompiler_object_inline_stack_2725 = workInProgress2.child, nextPrimaryChildren = current2.child.memoizedState, null === nextPrimaryChildren ? nextPrimaryChildren = mountSuspenseOffscreenState(renderLanes2) : (mode = nextPrimaryChildren.cachePool, null !== mode ? (componentStack = CacheContext._currentValue, mode = mode.parent !== componentStack ? { parent: componentStack, pool: componentStack } : mode) : mode = getSuspendedCache(), nextPrimaryChildren = {
            baseLanes: nextPrimaryChildren.baseLanes | renderLanes2,
            cachePool: mode
          }), JSCompiler_object_inline_stack_2725.memoizedState = nextPrimaryChildren, JSCompiler_object_inline_stack_2725.childLanes = getRemainingWorkInPrimaryTree(
            current2,
            JSCompiler_object_inline_digest_2724,
            renderLanes2
          ), workInProgress2.memoizedState = SUSPENDED_MARKER, bailoutOffscreenComponent(
            current2.child,
            JSCompiler_object_inline_stack_2725
          );
        null !== prevState && (renderLanes2 & 62914560) === renderLanes2 && 0 !== (renderLanes2 & current2.lanes) && markRenderDerivedCause(workInProgress2);
        pushPrimaryTreeSuspenseHandler(workInProgress2);
        renderLanes2 = current2.child;
        current2 = renderLanes2.sibling;
        renderLanes2 = createWorkInProgress(renderLanes2, {
          mode: "visible",
          children: JSCompiler_object_inline_stack_2725.children
        });
        renderLanes2.return = workInProgress2;
        renderLanes2.sibling = null;
        null !== current2 && (JSCompiler_object_inline_digest_2724 = workInProgress2.deletions, null === JSCompiler_object_inline_digest_2724 ? (workInProgress2.deletions = [current2], workInProgress2.flags |= 16) : JSCompiler_object_inline_digest_2724.push(current2));
        workInProgress2.child = renderLanes2;
        workInProgress2.memoizedState = null;
        return renderLanes2;
      }
      function mountSuspensePrimaryChildren(workInProgress2, primaryChildren) {
        primaryChildren = mountWorkInProgressOffscreenFiber(
          { mode: "visible", children: primaryChildren },
          workInProgress2.mode
        );
        primaryChildren.return = workInProgress2;
        return workInProgress2.child = primaryChildren;
      }
      function mountWorkInProgressOffscreenFiber(offscreenProps, mode) {
        offscreenProps = createFiber(22, offscreenProps, null, mode);
        offscreenProps.lanes = 0;
        return offscreenProps;
      }
      function retrySuspenseComponentWithoutHydrating(current2, workInProgress2, renderLanes2) {
        reconcileChildFibers(workInProgress2, current2.child, null, renderLanes2);
        current2 = mountSuspensePrimaryChildren(
          workInProgress2,
          workInProgress2.pendingProps.children
        );
        current2.flags |= 2;
        workInProgress2.memoizedState = null;
        return current2;
      }
      function scheduleSuspenseWorkOnFiber(fiber, renderLanes2, propagationRoot) {
        fiber.lanes |= renderLanes2;
        var alternate = fiber.alternate;
        null !== alternate && (alternate.lanes |= renderLanes2);
        scheduleContextWorkOnParentPath(
          fiber.return,
          renderLanes2,
          propagationRoot
        );
      }
      function initSuspenseListRenderState(workInProgress2, isBackwards, tail, lastContentRow, tailMode, treeForkCount2) {
        var renderState = workInProgress2.memoizedState;
        null === renderState ? workInProgress2.memoizedState = {
          isBackwards,
          rendering: null,
          renderingStartTime: 0,
          last: lastContentRow,
          tail,
          tailMode,
          treeForkCount: treeForkCount2
        } : (renderState.isBackwards = isBackwards, renderState.rendering = null, renderState.renderingStartTime = 0, renderState.last = lastContentRow, renderState.tail = tail, renderState.tailMode = tailMode, renderState.treeForkCount = treeForkCount2);
      }
      function updateSuspenseListComponent(current2, workInProgress2, renderLanes2) {
        var nextProps = workInProgress2.pendingProps, revealOrder = nextProps.revealOrder, tailMode = nextProps.tail, newChildren = nextProps.children, suspenseContext = suspenseStackCursor.current;
        (nextProps = 0 !== (suspenseContext & ForceSuspenseFallback)) ? (suspenseContext = suspenseContext & SubtreeSuspenseContextMask | ForceSuspenseFallback, workInProgress2.flags |= 128) : suspenseContext &= SubtreeSuspenseContextMask;
        push(suspenseStackCursor, suspenseContext, workInProgress2);
        suspenseContext = null == revealOrder ? "null" : revealOrder;
        if ("forwards" !== revealOrder && "unstable_legacy-backwards" !== revealOrder && "together" !== revealOrder && "independent" !== revealOrder && !didWarnAboutRevealOrder[suspenseContext])
          if (didWarnAboutRevealOrder[suspenseContext] = true, null == revealOrder)
            console.error(
              'The default for the <SuspenseList revealOrder="..."> prop is changing. To be future compatible you must explictly specify either "independent" (the current default), "together", "forwards" or "legacy_unstable-backwards".'
            );
          else if ("backwards" === revealOrder)
            console.error(
              'The rendering order of <SuspenseList revealOrder="backwards"> is changing. To be future compatible you must specify revealOrder="legacy_unstable-backwards" instead.'
            );
          else if ("string" === typeof revealOrder)
            switch (revealOrder.toLowerCase()) {
              case "together":
              case "forwards":
              case "backwards":
              case "independent":
                console.error(
                  '"%s" is not a valid value for revealOrder on <SuspenseList />. Use lowercase "%s" instead.',
                  revealOrder,
                  revealOrder.toLowerCase()
                );
                break;
              case "forward":
              case "backward":
                console.error(
                  '"%s" is not a valid value for revealOrder on <SuspenseList />. React uses the -s suffix in the spelling. Use "%ss" instead.',
                  revealOrder,
                  revealOrder.toLowerCase()
                );
                break;
              default:
                console.error(
                  '"%s" is not a supported revealOrder on <SuspenseList />. Did you mean "independent", "together", "forwards" or "backwards"?',
                  revealOrder
                );
            }
          else
            console.error(
              '%s is not a supported value for revealOrder on <SuspenseList />. Did you mean "independent", "together", "forwards" or "backwards"?',
              revealOrder
            );
        suspenseContext = null == tailMode ? "null" : tailMode;
        if (!didWarnAboutTailOptions[suspenseContext])
          if (null == tailMode) {
            if ("forwards" === revealOrder || "backwards" === revealOrder || "unstable_legacy-backwards" === revealOrder)
              didWarnAboutTailOptions[suspenseContext] = true, console.error(
                'The default for the <SuspenseList tail="..."> prop is changing. To be future compatible you must explictly specify either "visible" (the current default), "collapsed" or "hidden".'
              );
          } else
            "visible" !== tailMode && "collapsed" !== tailMode && "hidden" !== tailMode ? (didWarnAboutTailOptions[suspenseContext] = true, console.error(
              '"%s" is not a supported value for tail on <SuspenseList />. Did you mean "visible", "collapsed" or "hidden"?',
              tailMode
            )) : "forwards" !== revealOrder && "backwards" !== revealOrder && "unstable_legacy-backwards" !== revealOrder && (didWarnAboutTailOptions[suspenseContext] = true, console.error(
              '<SuspenseList tail="%s" /> is only valid if revealOrder is "forwards" or "backwards". Did you mean to specify revealOrder="forwards"?',
              tailMode
            ));
        a: if (("forwards" === revealOrder || "backwards" === revealOrder || "unstable_legacy-backwards" === revealOrder) && void 0 !== newChildren && null !== newChildren && false !== newChildren)
          if (isArrayImpl(newChildren))
            for (suspenseContext = 0; suspenseContext < newChildren.length; suspenseContext++) {
              if (!validateSuspenseListNestedChild(
                newChildren[suspenseContext],
                suspenseContext
              ))
                break a;
            }
          else if (suspenseContext = getIteratorFn(newChildren), "function" === typeof suspenseContext) {
            if (suspenseContext = suspenseContext.call(newChildren))
              for (var step = suspenseContext.next(), _i = 0; !step.done; step = suspenseContext.next()) {
                if (!validateSuspenseListNestedChild(step.value, _i)) break a;
                _i++;
              }
          } else
            console.error(
              'A single row was passed to a <SuspenseList revealOrder="%s" />. This is not useful since it needs multiple rows. Did you mean to pass multiple children or an array?',
              revealOrder
            );
        reconcileChildren(current2, workInProgress2, newChildren, renderLanes2);
        isHydrating ? (warnIfNotHydrating(), newChildren = treeForkCount) : newChildren = 0;
        if (!nextProps && null !== current2 && 0 !== (current2.flags & 128))
          a: for (current2 = workInProgress2.child; null !== current2; ) {
            if (13 === current2.tag)
              null !== current2.memoizedState && scheduleSuspenseWorkOnFiber(current2, renderLanes2, workInProgress2);
            else if (19 === current2.tag)
              scheduleSuspenseWorkOnFiber(current2, renderLanes2, workInProgress2);
            else if (null !== current2.child) {
              current2.child.return = current2;
              current2 = current2.child;
              continue;
            }
            if (current2 === workInProgress2) break a;
            for (; null === current2.sibling; ) {
              if (null === current2.return || current2.return === workInProgress2)
                break a;
              current2 = current2.return;
            }
            current2.sibling.return = current2.return;
            current2 = current2.sibling;
          }
        switch (revealOrder) {
          case "forwards":
            renderLanes2 = workInProgress2.child;
            for (revealOrder = null; null !== renderLanes2; )
              current2 = renderLanes2.alternate, null !== current2 && null === findFirstSuspended(current2) && (revealOrder = renderLanes2), renderLanes2 = renderLanes2.sibling;
            renderLanes2 = revealOrder;
            null === renderLanes2 ? (revealOrder = workInProgress2.child, workInProgress2.child = null) : (revealOrder = renderLanes2.sibling, renderLanes2.sibling = null);
            initSuspenseListRenderState(
              workInProgress2,
              false,
              revealOrder,
              renderLanes2,
              tailMode,
              newChildren
            );
            break;
          case "backwards":
          case "unstable_legacy-backwards":
            renderLanes2 = null;
            revealOrder = workInProgress2.child;
            for (workInProgress2.child = null; null !== revealOrder; ) {
              current2 = revealOrder.alternate;
              if (null !== current2 && null === findFirstSuspended(current2)) {
                workInProgress2.child = revealOrder;
                break;
              }
              current2 = revealOrder.sibling;
              revealOrder.sibling = renderLanes2;
              renderLanes2 = revealOrder;
              revealOrder = current2;
            }
            initSuspenseListRenderState(
              workInProgress2,
              true,
              renderLanes2,
              null,
              tailMode,
              newChildren
            );
            break;
          case "together":
            initSuspenseListRenderState(
              workInProgress2,
              false,
              null,
              null,
              void 0,
              newChildren
            );
            break;
          default:
            workInProgress2.memoizedState = null;
        }
        return workInProgress2.child;
      }
      function bailoutOnAlreadyFinishedWork(current2, workInProgress2, renderLanes2) {
        null !== current2 && (workInProgress2.dependencies = current2.dependencies);
        profilerStartTime = -1;
        workInProgressRootSkippedLanes |= workInProgress2.lanes;
        if (0 === (renderLanes2 & workInProgress2.childLanes))
          if (null !== current2) {
            if (propagateParentContextChanges(
              current2,
              workInProgress2,
              renderLanes2,
              false
            ), 0 === (renderLanes2 & workInProgress2.childLanes))
              return null;
          } else return null;
        if (null !== current2 && workInProgress2.child !== current2.child)
          throw Error("Resuming work not yet implemented.");
        if (null !== workInProgress2.child) {
          current2 = workInProgress2.child;
          renderLanes2 = createWorkInProgress(current2, current2.pendingProps);
          workInProgress2.child = renderLanes2;
          for (renderLanes2.return = workInProgress2; null !== current2.sibling; )
            current2 = current2.sibling, renderLanes2 = renderLanes2.sibling = createWorkInProgress(current2, current2.pendingProps), renderLanes2.return = workInProgress2;
          renderLanes2.sibling = null;
        }
        return workInProgress2.child;
      }
      function checkScheduledUpdateOrContext(current2, renderLanes2) {
        if (0 !== (current2.lanes & renderLanes2)) return true;
        current2 = current2.dependencies;
        return null !== current2 && checkIfContextChanged(current2) ? true : false;
      }
      function attemptEarlyBailoutIfNoScheduledUpdate(current2, workInProgress2, renderLanes2) {
        switch (workInProgress2.tag) {
          case 3:
            pushHostContainer(
              workInProgress2,
              workInProgress2.stateNode.containerInfo
            );
            pushProvider(
              workInProgress2,
              CacheContext,
              current2.memoizedState.cache
            );
            resetHydrationState();
            break;
          case 27:
          case 5:
            pushHostContext(workInProgress2);
            break;
          case 4:
            pushHostContainer(
              workInProgress2,
              workInProgress2.stateNode.containerInfo
            );
            break;
          case 10:
            pushProvider(
              workInProgress2,
              workInProgress2.type,
              workInProgress2.memoizedProps.value
            );
            break;
          case 12:
            0 !== (renderLanes2 & workInProgress2.childLanes) && (workInProgress2.flags |= 4);
            workInProgress2.flags |= 2048;
            var stateNode = workInProgress2.stateNode;
            stateNode.effectDuration = -0;
            stateNode.passiveEffectDuration = -0;
            break;
          case 31:
            if (null !== workInProgress2.memoizedState)
              return workInProgress2.flags |= 128, pushDehydratedActivitySuspenseHandler(workInProgress2), null;
            break;
          case 13:
            stateNode = workInProgress2.memoizedState;
            if (null !== stateNode) {
              if (null !== stateNode.dehydrated)
                return pushPrimaryTreeSuspenseHandler(workInProgress2), workInProgress2.flags |= 128, null;
              if (0 !== (renderLanes2 & workInProgress2.child.childLanes))
                return updateSuspenseComponent(
                  current2,
                  workInProgress2,
                  renderLanes2
                );
              pushPrimaryTreeSuspenseHandler(workInProgress2);
              current2 = bailoutOnAlreadyFinishedWork(
                current2,
                workInProgress2,
                renderLanes2
              );
              return null !== current2 ? current2.sibling : null;
            }
            pushPrimaryTreeSuspenseHandler(workInProgress2);
            break;
          case 19:
            var didSuspendBefore = 0 !== (current2.flags & 128);
            stateNode = 0 !== (renderLanes2 & workInProgress2.childLanes);
            stateNode || (propagateParentContextChanges(
              current2,
              workInProgress2,
              renderLanes2,
              false
            ), stateNode = 0 !== (renderLanes2 & workInProgress2.childLanes));
            if (didSuspendBefore) {
              if (stateNode)
                return updateSuspenseListComponent(
                  current2,
                  workInProgress2,
                  renderLanes2
                );
              workInProgress2.flags |= 128;
            }
            didSuspendBefore = workInProgress2.memoizedState;
            null !== didSuspendBefore && (didSuspendBefore.rendering = null, didSuspendBefore.tail = null, didSuspendBefore.lastEffect = null);
            push(
              suspenseStackCursor,
              suspenseStackCursor.current,
              workInProgress2
            );
            if (stateNode) break;
            else return null;
          case 22:
            return workInProgress2.lanes = 0, updateOffscreenComponent(
              current2,
              workInProgress2,
              renderLanes2,
              workInProgress2.pendingProps
            );
          case 24:
            pushProvider(
              workInProgress2,
              CacheContext,
              current2.memoizedState.cache
            );
        }
        return bailoutOnAlreadyFinishedWork(current2, workInProgress2, renderLanes2);
      }
      function beginWork(current2, workInProgress2, renderLanes2) {
        if (workInProgress2._debugNeedsRemount && null !== current2) {
          renderLanes2 = createFiberFromTypeAndProps(
            workInProgress2.type,
            workInProgress2.key,
            workInProgress2.pendingProps,
            workInProgress2._debugOwner || null,
            workInProgress2.mode,
            workInProgress2.lanes
          );
          renderLanes2._debugStack = workInProgress2._debugStack;
          renderLanes2._debugTask = workInProgress2._debugTask;
          var returnFiber = workInProgress2.return;
          if (null === returnFiber) throw Error("Cannot swap the root fiber.");
          current2.alternate = null;
          workInProgress2.alternate = null;
          renderLanes2.index = workInProgress2.index;
          renderLanes2.sibling = workInProgress2.sibling;
          renderLanes2.return = workInProgress2.return;
          renderLanes2.ref = workInProgress2.ref;
          renderLanes2._debugInfo = workInProgress2._debugInfo;
          if (workInProgress2 === returnFiber.child)
            returnFiber.child = renderLanes2;
          else {
            var prevSibling = returnFiber.child;
            if (null === prevSibling)
              throw Error("Expected parent to have a child.");
            for (; prevSibling.sibling !== workInProgress2; )
              if (prevSibling = prevSibling.sibling, null === prevSibling)
                throw Error("Expected to find the previous sibling.");
            prevSibling.sibling = renderLanes2;
          }
          workInProgress2 = returnFiber.deletions;
          null === workInProgress2 ? (returnFiber.deletions = [current2], returnFiber.flags |= 16) : workInProgress2.push(current2);
          renderLanes2.flags |= 2;
          return renderLanes2;
        }
        if (null !== current2)
          if (current2.memoizedProps !== workInProgress2.pendingProps || workInProgress2.type !== current2.type)
            didReceiveUpdate = true;
          else {
            if (!checkScheduledUpdateOrContext(current2, renderLanes2) && 0 === (workInProgress2.flags & 128))
              return didReceiveUpdate = false, attemptEarlyBailoutIfNoScheduledUpdate(
                current2,
                workInProgress2,
                renderLanes2
              );
            didReceiveUpdate = 0 !== (current2.flags & 131072) ? true : false;
          }
        else {
          didReceiveUpdate = false;
          if (returnFiber = isHydrating)
            warnIfNotHydrating(), returnFiber = 0 !== (workInProgress2.flags & 1048576);
          returnFiber && (returnFiber = workInProgress2.index, warnIfNotHydrating(), pushTreeId(workInProgress2, treeForkCount, returnFiber));
        }
        workInProgress2.lanes = 0;
        switch (workInProgress2.tag) {
          case 16:
            a: if (returnFiber = workInProgress2.pendingProps, current2 = resolveLazy(workInProgress2.elementType), workInProgress2.type = current2, "function" === typeof current2)
              shouldConstruct(current2) ? (returnFiber = resolveClassComponentProps(
                current2,
                returnFiber
              ), workInProgress2.tag = 1, workInProgress2.type = current2 = resolveFunctionForHotReloading(current2), workInProgress2 = updateClassComponent(
                null,
                workInProgress2,
                current2,
                returnFiber,
                renderLanes2
              )) : (workInProgress2.tag = 0, validateFunctionComponentInDev(workInProgress2, current2), workInProgress2.type = current2 = resolveFunctionForHotReloading(current2), workInProgress2 = updateFunctionComponent(
                null,
                workInProgress2,
                current2,
                returnFiber,
                renderLanes2
              ));
            else {
              if (void 0 !== current2 && null !== current2) {
                if (prevSibling = current2.$$typeof, prevSibling === REACT_FORWARD_REF_TYPE) {
                  workInProgress2.tag = 11;
                  workInProgress2.type = current2 = resolveForwardRefForHotReloading(current2);
                  workInProgress2 = updateForwardRef(
                    null,
                    workInProgress2,
                    current2,
                    returnFiber,
                    renderLanes2
                  );
                  break a;
                } else if (prevSibling === REACT_MEMO_TYPE) {
                  workInProgress2.tag = 14;
                  workInProgress2 = updateMemoComponent(
                    null,
                    workInProgress2,
                    current2,
                    returnFiber,
                    renderLanes2
                  );
                  break a;
                }
              }
              workInProgress2 = "";
              null !== current2 && "object" === typeof current2 && current2.$$typeof === REACT_LAZY_TYPE && (workInProgress2 = " Did you wrap a component in React.lazy() more than once?");
              renderLanes2 = getComponentNameFromType(current2) || current2;
              throw Error(
                "Element type is invalid. Received a promise that resolves to: " + renderLanes2 + ". Lazy element type must resolve to a class or function." + workInProgress2
              );
            }
            return workInProgress2;
          case 0:
            return updateFunctionComponent(
              current2,
              workInProgress2,
              workInProgress2.type,
              workInProgress2.pendingProps,
              renderLanes2
            );
          case 1:
            return returnFiber = workInProgress2.type, prevSibling = resolveClassComponentProps(
              returnFiber,
              workInProgress2.pendingProps
            ), updateClassComponent(
              current2,
              workInProgress2,
              returnFiber,
              prevSibling,
              renderLanes2
            );
          case 3:
            a: {
              pushHostContainer(
                workInProgress2,
                workInProgress2.stateNode.containerInfo
              );
              if (null === current2)
                throw Error(
                  "Should have a current fiber. This is a bug in React."
                );
              returnFiber = workInProgress2.pendingProps;
              var prevState = workInProgress2.memoizedState;
              prevSibling = prevState.element;
              cloneUpdateQueue(current2, workInProgress2);
              processUpdateQueue(workInProgress2, returnFiber, null, renderLanes2);
              var nextState = workInProgress2.memoizedState;
              returnFiber = nextState.cache;
              pushProvider(workInProgress2, CacheContext, returnFiber);
              returnFiber !== prevState.cache && propagateContextChanges(
                workInProgress2,
                [CacheContext],
                renderLanes2,
                true
              );
              suspendIfUpdateReadFromEntangledAsyncAction();
              returnFiber = nextState.element;
              if (prevState.isDehydrated)
                if (prevState = {
                  element: returnFiber,
                  isDehydrated: false,
                  cache: nextState.cache
                }, workInProgress2.updateQueue.baseState = prevState, workInProgress2.memoizedState = prevState, workInProgress2.flags & 256) {
                  workInProgress2 = mountHostRootWithoutHydrating(
                    current2,
                    workInProgress2,
                    returnFiber,
                    renderLanes2
                  );
                  break a;
                } else if (returnFiber !== prevSibling) {
                  prevSibling = createCapturedValueAtFiber(
                    Error(
                      "This root received an early update, before anything was able hydrate. Switched the entire root to client rendering."
                    ),
                    workInProgress2
                  );
                  queueHydrationError(prevSibling);
                  workInProgress2 = mountHostRootWithoutHydrating(
                    current2,
                    workInProgress2,
                    returnFiber,
                    renderLanes2
                  );
                  break a;
                } else {
                  current2 = workInProgress2.stateNode.containerInfo;
                  switch (current2.nodeType) {
                    case 9:
                      current2 = current2.body;
                      break;
                    default:
                      current2 = "HTML" === current2.nodeName ? current2.ownerDocument.body : current2;
                  }
                  nextHydratableInstance = getNextHydratable(current2.firstChild);
                  hydrationParentFiber = workInProgress2;
                  isHydrating = true;
                  hydrationErrors = null;
                  didSuspendOrErrorDEV = false;
                  hydrationDiffRootDEV = null;
                  rootOrSingletonContext = true;
                  renderLanes2 = mountChildFibers(
                    workInProgress2,
                    null,
                    returnFiber,
                    renderLanes2
                  );
                  for (workInProgress2.child = renderLanes2; renderLanes2; )
                    renderLanes2.flags = renderLanes2.flags & -3 | 4096, renderLanes2 = renderLanes2.sibling;
                }
              else {
                resetHydrationState();
                if (returnFiber === prevSibling) {
                  workInProgress2 = bailoutOnAlreadyFinishedWork(
                    current2,
                    workInProgress2,
                    renderLanes2
                  );
                  break a;
                }
                reconcileChildren(
                  current2,
                  workInProgress2,
                  returnFiber,
                  renderLanes2
                );
              }
              workInProgress2 = workInProgress2.child;
            }
            return workInProgress2;
          case 26:
            return markRef(current2, workInProgress2), null === current2 ? (renderLanes2 = getResource(
              workInProgress2.type,
              null,
              workInProgress2.pendingProps,
              null
            )) ? workInProgress2.memoizedState = renderLanes2 : isHydrating || (renderLanes2 = workInProgress2.type, current2 = workInProgress2.pendingProps, returnFiber = requiredContext(
              rootInstanceStackCursor.current
            ), returnFiber = getOwnerDocumentFromRootContainer(
              returnFiber
            ).createElement(renderLanes2), returnFiber[internalInstanceKey] = workInProgress2, returnFiber[internalPropsKey] = current2, setInitialProperties(returnFiber, renderLanes2, current2), markNodeAsHoistable(returnFiber), workInProgress2.stateNode = returnFiber) : workInProgress2.memoizedState = getResource(
              workInProgress2.type,
              current2.memoizedProps,
              workInProgress2.pendingProps,
              current2.memoizedState
            ), null;
          case 27:
            return pushHostContext(workInProgress2), null === current2 && isHydrating && (returnFiber = requiredContext(rootInstanceStackCursor.current), prevSibling = getHostContext(), returnFiber = workInProgress2.stateNode = resolveSingletonInstance(
              workInProgress2.type,
              workInProgress2.pendingProps,
              returnFiber,
              prevSibling,
              false
            ), didSuspendOrErrorDEV || (prevSibling = diffHydratedProperties(
              returnFiber,
              workInProgress2.type,
              workInProgress2.pendingProps,
              prevSibling
            ), null !== prevSibling && (buildHydrationDiffNode(workInProgress2, 0).serverProps = prevSibling)), hydrationParentFiber = workInProgress2, rootOrSingletonContext = true, prevSibling = nextHydratableInstance, isSingletonScope(workInProgress2.type) ? (previousHydratableOnEnteringScopedSingleton = prevSibling, nextHydratableInstance = getNextHydratable(
              returnFiber.firstChild
            )) : nextHydratableInstance = prevSibling), reconcileChildren(
              current2,
              workInProgress2,
              workInProgress2.pendingProps.children,
              renderLanes2
            ), markRef(current2, workInProgress2), null === current2 && (workInProgress2.flags |= 4194304), workInProgress2.child;
          case 5:
            return null === current2 && isHydrating && (prevState = getHostContext(), returnFiber = validateDOMNesting(
              workInProgress2.type,
              prevState.ancestorInfo
            ), prevSibling = nextHydratableInstance, (nextState = !prevSibling) || (nextState = canHydrateInstance(
              prevSibling,
              workInProgress2.type,
              workInProgress2.pendingProps,
              rootOrSingletonContext
            ), null !== nextState ? (workInProgress2.stateNode = nextState, didSuspendOrErrorDEV || (prevState = diffHydratedProperties(
              nextState,
              workInProgress2.type,
              workInProgress2.pendingProps,
              prevState
            ), null !== prevState && (buildHydrationDiffNode(workInProgress2, 0).serverProps = prevState)), hydrationParentFiber = workInProgress2, nextHydratableInstance = getNextHydratable(
              nextState.firstChild
            ), rootOrSingletonContext = false, prevState = true) : prevState = false, nextState = !prevState), nextState && (returnFiber && warnNonHydratedInstance(workInProgress2, prevSibling), throwOnHydrationMismatch(workInProgress2))), pushHostContext(workInProgress2), prevSibling = workInProgress2.type, prevState = workInProgress2.pendingProps, nextState = null !== current2 ? current2.memoizedProps : null, returnFiber = prevState.children, shouldSetTextContent(prevSibling, prevState) ? returnFiber = null : null !== nextState && shouldSetTextContent(prevSibling, nextState) && (workInProgress2.flags |= 32), null !== workInProgress2.memoizedState && (prevSibling = renderWithHooks(
              current2,
              workInProgress2,
              TransitionAwareHostComponent,
              null,
              null,
              renderLanes2
            ), HostTransitionContext._currentValue = prevSibling), markRef(current2, workInProgress2), reconcileChildren(
              current2,
              workInProgress2,
              returnFiber,
              renderLanes2
            ), workInProgress2.child;
          case 6:
            return null === current2 && isHydrating && (renderLanes2 = workInProgress2.pendingProps, current2 = getHostContext(), returnFiber = current2.ancestorInfo.current, renderLanes2 = null != returnFiber ? validateTextNesting(
              renderLanes2,
              returnFiber.tag,
              current2.ancestorInfo.implicitRootScope
            ) : true, current2 = nextHydratableInstance, (returnFiber = !current2) || (returnFiber = canHydrateTextInstance(
              current2,
              workInProgress2.pendingProps,
              rootOrSingletonContext
            ), null !== returnFiber ? (workInProgress2.stateNode = returnFiber, hydrationParentFiber = workInProgress2, nextHydratableInstance = null, returnFiber = true) : returnFiber = false, returnFiber = !returnFiber), returnFiber && (renderLanes2 && warnNonHydratedInstance(workInProgress2, current2), throwOnHydrationMismatch(workInProgress2))), null;
          case 13:
            return updateSuspenseComponent(current2, workInProgress2, renderLanes2);
          case 4:
            return pushHostContainer(
              workInProgress2,
              workInProgress2.stateNode.containerInfo
            ), returnFiber = workInProgress2.pendingProps, null === current2 ? workInProgress2.child = reconcileChildFibers(
              workInProgress2,
              null,
              returnFiber,
              renderLanes2
            ) : reconcileChildren(
              current2,
              workInProgress2,
              returnFiber,
              renderLanes2
            ), workInProgress2.child;
          case 11:
            return updateForwardRef(
              current2,
              workInProgress2,
              workInProgress2.type,
              workInProgress2.pendingProps,
              renderLanes2
            );
          case 7:
            return reconcileChildren(
              current2,
              workInProgress2,
              workInProgress2.pendingProps,
              renderLanes2
            ), workInProgress2.child;
          case 8:
            return reconcileChildren(
              current2,
              workInProgress2,
              workInProgress2.pendingProps.children,
              renderLanes2
            ), workInProgress2.child;
          case 12:
            return workInProgress2.flags |= 4, workInProgress2.flags |= 2048, returnFiber = workInProgress2.stateNode, returnFiber.effectDuration = -0, returnFiber.passiveEffectDuration = -0, reconcileChildren(
              current2,
              workInProgress2,
              workInProgress2.pendingProps.children,
              renderLanes2
            ), workInProgress2.child;
          case 10:
            return returnFiber = workInProgress2.type, prevSibling = workInProgress2.pendingProps, prevState = prevSibling.value, "value" in prevSibling || hasWarnedAboutUsingNoValuePropOnContextProvider || (hasWarnedAboutUsingNoValuePropOnContextProvider = true, console.error(
              "The `value` prop is required for the `<Context.Provider>`. Did you misspell it or forget to pass it?"
            )), pushProvider(workInProgress2, returnFiber, prevState), reconcileChildren(
              current2,
              workInProgress2,
              prevSibling.children,
              renderLanes2
            ), workInProgress2.child;
          case 9:
            return prevSibling = workInProgress2.type._context, returnFiber = workInProgress2.pendingProps.children, "function" !== typeof returnFiber && console.error(
              "A context consumer was rendered with multiple children, or a child that isn't a function. A context consumer expects a single child that is a function. If you did pass a function, make sure there is no trailing or leading whitespace around it."
            ), prepareToReadContext(workInProgress2), prevSibling = readContext(prevSibling), returnFiber = callComponentInDEV(
              returnFiber,
              prevSibling,
              void 0
            ), workInProgress2.flags |= 1, reconcileChildren(
              current2,
              workInProgress2,
              returnFiber,
              renderLanes2
            ), workInProgress2.child;
          case 14:
            return updateMemoComponent(
              current2,
              workInProgress2,
              workInProgress2.type,
              workInProgress2.pendingProps,
              renderLanes2
            );
          case 15:
            return updateSimpleMemoComponent(
              current2,
              workInProgress2,
              workInProgress2.type,
              workInProgress2.pendingProps,
              renderLanes2
            );
          case 19:
            return updateSuspenseListComponent(
              current2,
              workInProgress2,
              renderLanes2
            );
          case 31:
            return updateActivityComponent(current2, workInProgress2, renderLanes2);
          case 22:
            return updateOffscreenComponent(
              current2,
              workInProgress2,
              renderLanes2,
              workInProgress2.pendingProps
            );
          case 24:
            return prepareToReadContext(workInProgress2), returnFiber = readContext(CacheContext), null === current2 ? (prevSibling = peekCacheFromPool(), null === prevSibling && (prevSibling = workInProgressRoot, prevState = createCache(), prevSibling.pooledCache = prevState, retainCache(prevState), null !== prevState && (prevSibling.pooledCacheLanes |= renderLanes2), prevSibling = prevState), workInProgress2.memoizedState = {
              parent: returnFiber,
              cache: prevSibling
            }, initializeUpdateQueue(workInProgress2), pushProvider(workInProgress2, CacheContext, prevSibling)) : (0 !== (current2.lanes & renderLanes2) && (cloneUpdateQueue(current2, workInProgress2), processUpdateQueue(workInProgress2, null, null, renderLanes2), suspendIfUpdateReadFromEntangledAsyncAction()), prevSibling = current2.memoizedState, prevState = workInProgress2.memoizedState, prevSibling.parent !== returnFiber ? (prevSibling = {
              parent: returnFiber,
              cache: returnFiber
            }, workInProgress2.memoizedState = prevSibling, 0 === workInProgress2.lanes && (workInProgress2.memoizedState = workInProgress2.updateQueue.baseState = prevSibling), pushProvider(workInProgress2, CacheContext, returnFiber)) : (returnFiber = prevState.cache, pushProvider(workInProgress2, CacheContext, returnFiber), returnFiber !== prevSibling.cache && propagateContextChanges(
              workInProgress2,
              [CacheContext],
              renderLanes2,
              true
            ))), reconcileChildren(
              current2,
              workInProgress2,
              workInProgress2.pendingProps.children,
              renderLanes2
            ), workInProgress2.child;
          case 29:
            throw workInProgress2.pendingProps;
        }
        throw Error(
          "Unknown unit of work tag (" + workInProgress2.tag + "). This error is likely caused by a bug in React. Please file an issue."
        );
      }
      function markUpdate(workInProgress2) {
        workInProgress2.flags |= 4;
      }
      function preloadInstanceAndSuspendIfNeeded(workInProgress2, type, oldProps, newProps, renderLanes2) {
        if (type = (workInProgress2.mode & SuspenseyImagesMode) !== NoMode)
          type = false;
        if (type) {
          if (workInProgress2.flags |= 16777216, (renderLanes2 & 335544128) === renderLanes2)
            if (workInProgress2.stateNode.complete) workInProgress2.flags |= 8192;
            else if (shouldRemainOnPreviousScreen()) workInProgress2.flags |= 8192;
            else
              throw suspendedThenable = noopSuspenseyCommitThenable, SuspenseyCommitException;
        } else workInProgress2.flags &= -16777217;
      }
      function preloadResourceAndSuspendIfNeeded(workInProgress2, resource) {
        if ("stylesheet" !== resource.type || (resource.state.loading & Inserted) !== NotLoaded)
          workInProgress2.flags &= -16777217;
        else if (workInProgress2.flags |= 16777216, !preloadResource(resource))
          if (shouldRemainOnPreviousScreen()) workInProgress2.flags |= 8192;
          else
            throw suspendedThenable = noopSuspenseyCommitThenable, SuspenseyCommitException;
      }
      function scheduleRetryEffect(workInProgress2, retryQueue) {
        null !== retryQueue && (workInProgress2.flags |= 4);
        workInProgress2.flags & 16384 && (retryQueue = 22 !== workInProgress2.tag ? claimNextRetryLane() : 536870912, workInProgress2.lanes |= retryQueue, workInProgressSuspendedRetryLanes |= retryQueue);
      }
      function cutOffTailIfNeeded(renderState, hasRenderedATailFallback) {
        if (!isHydrating)
          switch (renderState.tailMode) {
            case "hidden":
              hasRenderedATailFallback = renderState.tail;
              for (var lastTailNode = null; null !== hasRenderedATailFallback; )
                null !== hasRenderedATailFallback.alternate && (lastTailNode = hasRenderedATailFallback), hasRenderedATailFallback = hasRenderedATailFallback.sibling;
              null === lastTailNode ? renderState.tail = null : lastTailNode.sibling = null;
              break;
            case "collapsed":
              lastTailNode = renderState.tail;
              for (var _lastTailNode = null; null !== lastTailNode; )
                null !== lastTailNode.alternate && (_lastTailNode = lastTailNode), lastTailNode = lastTailNode.sibling;
              null === _lastTailNode ? hasRenderedATailFallback || null === renderState.tail ? renderState.tail = null : renderState.tail.sibling = null : _lastTailNode.sibling = null;
          }
      }
      function bubbleProperties(completedWork) {
        var didBailout = null !== completedWork.alternate && completedWork.alternate.child === completedWork.child, newChildLanes = 0, subtreeFlags = 0;
        if (didBailout)
          if ((completedWork.mode & ProfileMode) !== NoMode) {
            for (var _treeBaseDuration = completedWork.selfBaseDuration, _child2 = completedWork.child; null !== _child2; )
              newChildLanes |= _child2.lanes | _child2.childLanes, subtreeFlags |= _child2.subtreeFlags & 65011712, subtreeFlags |= _child2.flags & 65011712, _treeBaseDuration += _child2.treeBaseDuration, _child2 = _child2.sibling;
            completedWork.treeBaseDuration = _treeBaseDuration;
          } else
            for (_treeBaseDuration = completedWork.child; null !== _treeBaseDuration; )
              newChildLanes |= _treeBaseDuration.lanes | _treeBaseDuration.childLanes, subtreeFlags |= _treeBaseDuration.subtreeFlags & 65011712, subtreeFlags |= _treeBaseDuration.flags & 65011712, _treeBaseDuration.return = completedWork, _treeBaseDuration = _treeBaseDuration.sibling;
        else if ((completedWork.mode & ProfileMode) !== NoMode) {
          _treeBaseDuration = completedWork.actualDuration;
          _child2 = completedWork.selfBaseDuration;
          for (var child = completedWork.child; null !== child; )
            newChildLanes |= child.lanes | child.childLanes, subtreeFlags |= child.subtreeFlags, subtreeFlags |= child.flags, _treeBaseDuration += child.actualDuration, _child2 += child.treeBaseDuration, child = child.sibling;
          completedWork.actualDuration = _treeBaseDuration;
          completedWork.treeBaseDuration = _child2;
        } else
          for (_treeBaseDuration = completedWork.child; null !== _treeBaseDuration; )
            newChildLanes |= _treeBaseDuration.lanes | _treeBaseDuration.childLanes, subtreeFlags |= _treeBaseDuration.subtreeFlags, subtreeFlags |= _treeBaseDuration.flags, _treeBaseDuration.return = completedWork, _treeBaseDuration = _treeBaseDuration.sibling;
        completedWork.subtreeFlags |= subtreeFlags;
        completedWork.childLanes = newChildLanes;
        return didBailout;
      }
      function completeWork(current2, workInProgress2, renderLanes2) {
        var newProps = workInProgress2.pendingProps;
        popTreeContext(workInProgress2);
        switch (workInProgress2.tag) {
          case 16:
          case 15:
          case 0:
          case 11:
          case 7:
          case 8:
          case 12:
          case 9:
          case 14:
            return bubbleProperties(workInProgress2), null;
          case 1:
            return bubbleProperties(workInProgress2), null;
          case 3:
            renderLanes2 = workInProgress2.stateNode;
            newProps = null;
            null !== current2 && (newProps = current2.memoizedState.cache);
            workInProgress2.memoizedState.cache !== newProps && (workInProgress2.flags |= 2048);
            popProvider(CacheContext, workInProgress2);
            popHostContainer(workInProgress2);
            renderLanes2.pendingContext && (renderLanes2.context = renderLanes2.pendingContext, renderLanes2.pendingContext = null);
            if (null === current2 || null === current2.child)
              popHydrationState(workInProgress2) ? (emitPendingHydrationWarnings(), markUpdate(workInProgress2)) : null === current2 || current2.memoizedState.isDehydrated && 0 === (workInProgress2.flags & 256) || (workInProgress2.flags |= 1024, upgradeHydrationErrorsToRecoverable());
            bubbleProperties(workInProgress2);
            return null;
          case 26:
            var type = workInProgress2.type, nextResource = workInProgress2.memoizedState;
            null === current2 ? (markUpdate(workInProgress2), null !== nextResource ? (bubbleProperties(workInProgress2), preloadResourceAndSuspendIfNeeded(
              workInProgress2,
              nextResource
            )) : (bubbleProperties(workInProgress2), preloadInstanceAndSuspendIfNeeded(
              workInProgress2,
              type,
              null,
              newProps,
              renderLanes2
            ))) : nextResource ? nextResource !== current2.memoizedState ? (markUpdate(workInProgress2), bubbleProperties(workInProgress2), preloadResourceAndSuspendIfNeeded(
              workInProgress2,
              nextResource
            )) : (bubbleProperties(workInProgress2), workInProgress2.flags &= -16777217) : (current2 = current2.memoizedProps, current2 !== newProps && markUpdate(workInProgress2), bubbleProperties(workInProgress2), preloadInstanceAndSuspendIfNeeded(
              workInProgress2,
              type,
              current2,
              newProps,
              renderLanes2
            ));
            return null;
          case 27:
            popHostContext(workInProgress2);
            renderLanes2 = requiredContext(rootInstanceStackCursor.current);
            type = workInProgress2.type;
            if (null !== current2 && null != workInProgress2.stateNode)
              current2.memoizedProps !== newProps && markUpdate(workInProgress2);
            else {
              if (!newProps) {
                if (null === workInProgress2.stateNode)
                  throw Error(
                    "We must have new props for new mounts. This error is likely caused by a bug in React. Please file an issue."
                  );
                bubbleProperties(workInProgress2);
                return null;
              }
              current2 = getHostContext();
              popHydrationState(workInProgress2) ? prepareToHydrateHostInstance(workInProgress2, current2) : (current2 = resolveSingletonInstance(
                type,
                newProps,
                renderLanes2,
                current2,
                true
              ), workInProgress2.stateNode = current2, markUpdate(workInProgress2));
            }
            bubbleProperties(workInProgress2);
            return null;
          case 5:
            popHostContext(workInProgress2);
            type = workInProgress2.type;
            if (null !== current2 && null != workInProgress2.stateNode)
              current2.memoizedProps !== newProps && markUpdate(workInProgress2);
            else {
              if (!newProps) {
                if (null === workInProgress2.stateNode)
                  throw Error(
                    "We must have new props for new mounts. This error is likely caused by a bug in React. Please file an issue."
                  );
                bubbleProperties(workInProgress2);
                return null;
              }
              var _currentHostContext = getHostContext();
              if (popHydrationState(workInProgress2))
                prepareToHydrateHostInstance(workInProgress2, _currentHostContext);
              else {
                nextResource = requiredContext(rootInstanceStackCursor.current);
                validateDOMNesting(type, _currentHostContext.ancestorInfo);
                _currentHostContext = _currentHostContext.context;
                nextResource = getOwnerDocumentFromRootContainer(nextResource);
                switch (_currentHostContext) {
                  case HostContextNamespaceSvg:
                    nextResource = nextResource.createElementNS(
                      SVG_NAMESPACE,
                      type
                    );
                    break;
                  case HostContextNamespaceMath:
                    nextResource = nextResource.createElementNS(
                      MATH_NAMESPACE,
                      type
                    );
                    break;
                  default:
                    switch (type) {
                      case "svg":
                        nextResource = nextResource.createElementNS(
                          SVG_NAMESPACE,
                          type
                        );
                        break;
                      case "math":
                        nextResource = nextResource.createElementNS(
                          MATH_NAMESPACE,
                          type
                        );
                        break;
                      case "script":
                        nextResource = nextResource.createElement("div");
                        nextResource.innerHTML = "<script><\/script>";
                        nextResource = nextResource.removeChild(
                          nextResource.firstChild
                        );
                        break;
                      case "select":
                        nextResource = "string" === typeof newProps.is ? nextResource.createElement("select", {
                          is: newProps.is
                        }) : nextResource.createElement("select");
                        newProps.multiple ? nextResource.multiple = true : newProps.size && (nextResource.size = newProps.size);
                        break;
                      default:
                        nextResource = "string" === typeof newProps.is ? nextResource.createElement(type, {
                          is: newProps.is
                        }) : nextResource.createElement(type), -1 === type.indexOf("-") && (type !== type.toLowerCase() && console.error(
                          "<%s /> is using incorrect casing. Use PascalCase for React components, or lowercase for HTML elements.",
                          type
                        ), "[object HTMLUnknownElement]" !== Object.prototype.toString.call(nextResource) || hasOwnProperty2.call(warnedUnknownTags, type) || (warnedUnknownTags[type] = true, console.error(
                          "The tag <%s> is unrecognized in this browser. If you meant to render a React component, start its name with an uppercase letter.",
                          type
                        )));
                    }
                }
                nextResource[internalInstanceKey] = workInProgress2;
                nextResource[internalPropsKey] = newProps;
                a: for (_currentHostContext = workInProgress2.child; null !== _currentHostContext; ) {
                  if (5 === _currentHostContext.tag || 6 === _currentHostContext.tag)
                    nextResource.appendChild(_currentHostContext.stateNode);
                  else if (4 !== _currentHostContext.tag && 27 !== _currentHostContext.tag && null !== _currentHostContext.child) {
                    _currentHostContext.child.return = _currentHostContext;
                    _currentHostContext = _currentHostContext.child;
                    continue;
                  }
                  if (_currentHostContext === workInProgress2) break a;
                  for (; null === _currentHostContext.sibling; ) {
                    if (null === _currentHostContext.return || _currentHostContext.return === workInProgress2)
                      break a;
                    _currentHostContext = _currentHostContext.return;
                  }
                  _currentHostContext.sibling.return = _currentHostContext.return;
                  _currentHostContext = _currentHostContext.sibling;
                }
                workInProgress2.stateNode = nextResource;
                a: switch (setInitialProperties(nextResource, type, newProps), type) {
                  case "button":
                  case "input":
                  case "select":
                  case "textarea":
                    newProps = !!newProps.autoFocus;
                    break a;
                  case "img":
                    newProps = true;
                    break a;
                  default:
                    newProps = false;
                }
                newProps && markUpdate(workInProgress2);
              }
            }
            bubbleProperties(workInProgress2);
            preloadInstanceAndSuspendIfNeeded(
              workInProgress2,
              workInProgress2.type,
              null === current2 ? null : current2.memoizedProps,
              workInProgress2.pendingProps,
              renderLanes2
            );
            return null;
          case 6:
            if (current2 && null != workInProgress2.stateNode)
              current2.memoizedProps !== newProps && markUpdate(workInProgress2);
            else {
              if ("string" !== typeof newProps && null === workInProgress2.stateNode)
                throw Error(
                  "We must have new props for new mounts. This error is likely caused by a bug in React. Please file an issue."
                );
              current2 = requiredContext(rootInstanceStackCursor.current);
              renderLanes2 = getHostContext();
              if (popHydrationState(workInProgress2)) {
                current2 = workInProgress2.stateNode;
                renderLanes2 = workInProgress2.memoizedProps;
                type = !didSuspendOrErrorDEV;
                newProps = null;
                nextResource = hydrationParentFiber;
                if (null !== nextResource)
                  switch (nextResource.tag) {
                    case 3:
                      type && (type = diffHydratedTextForDevWarnings(
                        current2,
                        renderLanes2,
                        newProps
                      ), null !== type && (buildHydrationDiffNode(workInProgress2, 0).serverProps = type));
                      break;
                    case 27:
                    case 5:
                      newProps = nextResource.memoizedProps, type && (type = diffHydratedTextForDevWarnings(
                        current2,
                        renderLanes2,
                        newProps
                      ), null !== type && (buildHydrationDiffNode(
                        workInProgress2,
                        0
                      ).serverProps = type));
                  }
                current2[internalInstanceKey] = workInProgress2;
                current2 = current2.nodeValue === renderLanes2 || null !== newProps && true === newProps.suppressHydrationWarning || checkForUnmatchedText(current2.nodeValue, renderLanes2) ? true : false;
                current2 || throwOnHydrationMismatch(workInProgress2, true);
              } else
                type = renderLanes2.ancestorInfo.current, null != type && validateTextNesting(
                  newProps,
                  type.tag,
                  renderLanes2.ancestorInfo.implicitRootScope
                ), current2 = getOwnerDocumentFromRootContainer(current2).createTextNode(
                  newProps
                ), current2[internalInstanceKey] = workInProgress2, workInProgress2.stateNode = current2;
            }
            bubbleProperties(workInProgress2);
            return null;
          case 31:
            renderLanes2 = workInProgress2.memoizedState;
            if (null === current2 || null !== current2.memoizedState) {
              newProps = popHydrationState(workInProgress2);
              if (null !== renderLanes2) {
                if (null === current2) {
                  if (!newProps)
                    throw Error(
                      "A dehydrated suspense component was completed without a hydrated node. This is probably a bug in React."
                    );
                  current2 = workInProgress2.memoizedState;
                  current2 = null !== current2 ? current2.dehydrated : null;
                  if (!current2)
                    throw Error(
                      "Expected to have a hydrated activity instance. This error is likely caused by a bug in React. Please file an issue."
                    );
                  current2[internalInstanceKey] = workInProgress2;
                  bubbleProperties(workInProgress2);
                  (workInProgress2.mode & ProfileMode) !== NoMode && null !== renderLanes2 && (current2 = workInProgress2.child, null !== current2 && (workInProgress2.treeBaseDuration -= current2.treeBaseDuration));
                } else
                  emitPendingHydrationWarnings(), resetHydrationState(), 0 === (workInProgress2.flags & 128) && (renderLanes2 = workInProgress2.memoizedState = null), workInProgress2.flags |= 4, bubbleProperties(workInProgress2), (workInProgress2.mode & ProfileMode) !== NoMode && null !== renderLanes2 && (current2 = workInProgress2.child, null !== current2 && (workInProgress2.treeBaseDuration -= current2.treeBaseDuration));
                current2 = false;
              } else
                renderLanes2 = upgradeHydrationErrorsToRecoverable(), null !== current2 && null !== current2.memoizedState && (current2.memoizedState.hydrationErrors = renderLanes2), current2 = true;
              if (!current2) {
                if (workInProgress2.flags & 256)
                  return popSuspenseHandler(workInProgress2), workInProgress2;
                popSuspenseHandler(workInProgress2);
                return null;
              }
              if (0 !== (workInProgress2.flags & 128))
                throw Error(
                  "Client rendering an Activity suspended it again. This is a bug in React."
                );
            }
            bubbleProperties(workInProgress2);
            return null;
          case 13:
            newProps = workInProgress2.memoizedState;
            if (null === current2 || null !== current2.memoizedState && null !== current2.memoizedState.dehydrated) {
              type = newProps;
              nextResource = popHydrationState(workInProgress2);
              if (null !== type && null !== type.dehydrated) {
                if (null === current2) {
                  if (!nextResource)
                    throw Error(
                      "A dehydrated suspense component was completed without a hydrated node. This is probably a bug in React."
                    );
                  nextResource = workInProgress2.memoizedState;
                  nextResource = null !== nextResource ? nextResource.dehydrated : null;
                  if (!nextResource)
                    throw Error(
                      "Expected to have a hydrated suspense instance. This error is likely caused by a bug in React. Please file an issue."
                    );
                  nextResource[internalInstanceKey] = workInProgress2;
                  bubbleProperties(workInProgress2);
                  (workInProgress2.mode & ProfileMode) !== NoMode && null !== type && (type = workInProgress2.child, null !== type && (workInProgress2.treeBaseDuration -= type.treeBaseDuration));
                } else
                  emitPendingHydrationWarnings(), resetHydrationState(), 0 === (workInProgress2.flags & 128) && (type = workInProgress2.memoizedState = null), workInProgress2.flags |= 4, bubbleProperties(workInProgress2), (workInProgress2.mode & ProfileMode) !== NoMode && null !== type && (type = workInProgress2.child, null !== type && (workInProgress2.treeBaseDuration -= type.treeBaseDuration));
                type = false;
              } else
                type = upgradeHydrationErrorsToRecoverable(), null !== current2 && null !== current2.memoizedState && (current2.memoizedState.hydrationErrors = type), type = true;
              if (!type) {
                if (workInProgress2.flags & 256)
                  return popSuspenseHandler(workInProgress2), workInProgress2;
                popSuspenseHandler(workInProgress2);
                return null;
              }
            }
            popSuspenseHandler(workInProgress2);
            if (0 !== (workInProgress2.flags & 128))
              return workInProgress2.lanes = renderLanes2, (workInProgress2.mode & ProfileMode) !== NoMode && transferActualDuration(workInProgress2), workInProgress2;
            renderLanes2 = null !== newProps;
            current2 = null !== current2 && null !== current2.memoizedState;
            renderLanes2 && (newProps = workInProgress2.child, type = null, null !== newProps.alternate && null !== newProps.alternate.memoizedState && null !== newProps.alternate.memoizedState.cachePool && (type = newProps.alternate.memoizedState.cachePool.pool), nextResource = null, null !== newProps.memoizedState && null !== newProps.memoizedState.cachePool && (nextResource = newProps.memoizedState.cachePool.pool), nextResource !== type && (newProps.flags |= 2048));
            renderLanes2 !== current2 && renderLanes2 && (workInProgress2.child.flags |= 8192);
            scheduleRetryEffect(workInProgress2, workInProgress2.updateQueue);
            bubbleProperties(workInProgress2);
            (workInProgress2.mode & ProfileMode) !== NoMode && renderLanes2 && (current2 = workInProgress2.child, null !== current2 && (workInProgress2.treeBaseDuration -= current2.treeBaseDuration));
            return null;
          case 4:
            return popHostContainer(workInProgress2), null === current2 && listenToAllSupportedEvents(
              workInProgress2.stateNode.containerInfo
            ), bubbleProperties(workInProgress2), null;
          case 10:
            return popProvider(workInProgress2.type, workInProgress2), bubbleProperties(workInProgress2), null;
          case 19:
            pop(suspenseStackCursor, workInProgress2);
            newProps = workInProgress2.memoizedState;
            if (null === newProps) return bubbleProperties(workInProgress2), null;
            type = 0 !== (workInProgress2.flags & 128);
            nextResource = newProps.rendering;
            if (null === nextResource)
              if (type) cutOffTailIfNeeded(newProps, false);
              else {
                if (workInProgressRootExitStatus !== RootInProgress || null !== current2 && 0 !== (current2.flags & 128))
                  for (current2 = workInProgress2.child; null !== current2; ) {
                    nextResource = findFirstSuspended(current2);
                    if (null !== nextResource) {
                      workInProgress2.flags |= 128;
                      cutOffTailIfNeeded(newProps, false);
                      current2 = nextResource.updateQueue;
                      workInProgress2.updateQueue = current2;
                      scheduleRetryEffect(workInProgress2, current2);
                      workInProgress2.subtreeFlags = 0;
                      current2 = renderLanes2;
                      for (renderLanes2 = workInProgress2.child; null !== renderLanes2; )
                        resetWorkInProgress(renderLanes2, current2), renderLanes2 = renderLanes2.sibling;
                      push(
                        suspenseStackCursor,
                        suspenseStackCursor.current & SubtreeSuspenseContextMask | ForceSuspenseFallback,
                        workInProgress2
                      );
                      isHydrating && pushTreeFork(workInProgress2, newProps.treeForkCount);
                      return workInProgress2.child;
                    }
                    current2 = current2.sibling;
                  }
                null !== newProps.tail && now$1() > workInProgressRootRenderTargetTime && (workInProgress2.flags |= 128, type = true, cutOffTailIfNeeded(newProps, false), workInProgress2.lanes = 4194304);
              }
            else {
              if (!type)
                if (current2 = findFirstSuspended(nextResource), null !== current2) {
                  if (workInProgress2.flags |= 128, type = true, current2 = current2.updateQueue, workInProgress2.updateQueue = current2, scheduleRetryEffect(workInProgress2, current2), cutOffTailIfNeeded(newProps, true), null === newProps.tail && "hidden" === newProps.tailMode && !nextResource.alternate && !isHydrating)
                    return bubbleProperties(workInProgress2), null;
                } else
                  2 * now$1() - newProps.renderingStartTime > workInProgressRootRenderTargetTime && 536870912 !== renderLanes2 && (workInProgress2.flags |= 128, type = true, cutOffTailIfNeeded(newProps, false), workInProgress2.lanes = 4194304);
              newProps.isBackwards ? (nextResource.sibling = workInProgress2.child, workInProgress2.child = nextResource) : (current2 = newProps.last, null !== current2 ? current2.sibling = nextResource : workInProgress2.child = nextResource, newProps.last = nextResource);
            }
            if (null !== newProps.tail)
              return current2 = newProps.tail, newProps.rendering = current2, newProps.tail = current2.sibling, newProps.renderingStartTime = now$1(), current2.sibling = null, renderLanes2 = suspenseStackCursor.current, renderLanes2 = type ? renderLanes2 & SubtreeSuspenseContextMask | ForceSuspenseFallback : renderLanes2 & SubtreeSuspenseContextMask, push(suspenseStackCursor, renderLanes2, workInProgress2), isHydrating && pushTreeFork(workInProgress2, newProps.treeForkCount), current2;
            bubbleProperties(workInProgress2);
            return null;
          case 22:
          case 23:
            return popSuspenseHandler(workInProgress2), popHiddenContext(workInProgress2), newProps = null !== workInProgress2.memoizedState, null !== current2 ? null !== current2.memoizedState !== newProps && (workInProgress2.flags |= 8192) : newProps && (workInProgress2.flags |= 8192), newProps ? 0 !== (renderLanes2 & 536870912) && 0 === (workInProgress2.flags & 128) && (bubbleProperties(workInProgress2), workInProgress2.subtreeFlags & 6 && (workInProgress2.flags |= 8192)) : bubbleProperties(workInProgress2), renderLanes2 = workInProgress2.updateQueue, null !== renderLanes2 && scheduleRetryEffect(workInProgress2, renderLanes2.retryQueue), renderLanes2 = null, null !== current2 && null !== current2.memoizedState && null !== current2.memoizedState.cachePool && (renderLanes2 = current2.memoizedState.cachePool.pool), newProps = null, null !== workInProgress2.memoizedState && null !== workInProgress2.memoizedState.cachePool && (newProps = workInProgress2.memoizedState.cachePool.pool), newProps !== renderLanes2 && (workInProgress2.flags |= 2048), null !== current2 && pop(resumedCache, workInProgress2), null;
          case 24:
            return renderLanes2 = null, null !== current2 && (renderLanes2 = current2.memoizedState.cache), workInProgress2.memoizedState.cache !== renderLanes2 && (workInProgress2.flags |= 2048), popProvider(CacheContext, workInProgress2), bubbleProperties(workInProgress2), null;
          case 25:
            return null;
          case 30:
            return null;
        }
        throw Error(
          "Unknown unit of work tag (" + workInProgress2.tag + "). This error is likely caused by a bug in React. Please file an issue."
        );
      }
      function unwindWork(current2, workInProgress2) {
        popTreeContext(workInProgress2);
        switch (workInProgress2.tag) {
          case 1:
            return current2 = workInProgress2.flags, current2 & 65536 ? (workInProgress2.flags = current2 & -65537 | 128, (workInProgress2.mode & ProfileMode) !== NoMode && transferActualDuration(workInProgress2), workInProgress2) : null;
          case 3:
            return popProvider(CacheContext, workInProgress2), popHostContainer(workInProgress2), current2 = workInProgress2.flags, 0 !== (current2 & 65536) && 0 === (current2 & 128) ? (workInProgress2.flags = current2 & -65537 | 128, workInProgress2) : null;
          case 26:
          case 27:
          case 5:
            return popHostContext(workInProgress2), null;
          case 31:
            if (null !== workInProgress2.memoizedState) {
              popSuspenseHandler(workInProgress2);
              if (null === workInProgress2.alternate)
                throw Error(
                  "Threw in newly mounted dehydrated component. This is likely a bug in React. Please file an issue."
                );
              resetHydrationState();
            }
            current2 = workInProgress2.flags;
            return current2 & 65536 ? (workInProgress2.flags = current2 & -65537 | 128, (workInProgress2.mode & ProfileMode) !== NoMode && transferActualDuration(workInProgress2), workInProgress2) : null;
          case 13:
            popSuspenseHandler(workInProgress2);
            current2 = workInProgress2.memoizedState;
            if (null !== current2 && null !== current2.dehydrated) {
              if (null === workInProgress2.alternate)
                throw Error(
                  "Threw in newly mounted dehydrated component. This is likely a bug in React. Please file an issue."
                );
              resetHydrationState();
            }
            current2 = workInProgress2.flags;
            return current2 & 65536 ? (workInProgress2.flags = current2 & -65537 | 128, (workInProgress2.mode & ProfileMode) !== NoMode && transferActualDuration(workInProgress2), workInProgress2) : null;
          case 19:
            return pop(suspenseStackCursor, workInProgress2), null;
          case 4:
            return popHostContainer(workInProgress2), null;
          case 10:
            return popProvider(workInProgress2.type, workInProgress2), null;
          case 22:
          case 23:
            return popSuspenseHandler(workInProgress2), popHiddenContext(workInProgress2), null !== current2 && pop(resumedCache, workInProgress2), current2 = workInProgress2.flags, current2 & 65536 ? (workInProgress2.flags = current2 & -65537 | 128, (workInProgress2.mode & ProfileMode) !== NoMode && transferActualDuration(workInProgress2), workInProgress2) : null;
          case 24:
            return popProvider(CacheContext, workInProgress2), null;
          case 25:
            return null;
          default:
            return null;
        }
      }
      function unwindInterruptedWork(current2, interruptedWork) {
        popTreeContext(interruptedWork);
        switch (interruptedWork.tag) {
          case 3:
            popProvider(CacheContext, interruptedWork);
            popHostContainer(interruptedWork);
            break;
          case 26:
          case 27:
          case 5:
            popHostContext(interruptedWork);
            break;
          case 4:
            popHostContainer(interruptedWork);
            break;
          case 31:
            null !== interruptedWork.memoizedState && popSuspenseHandler(interruptedWork);
            break;
          case 13:
            popSuspenseHandler(interruptedWork);
            break;
          case 19:
            pop(suspenseStackCursor, interruptedWork);
            break;
          case 10:
            popProvider(interruptedWork.type, interruptedWork);
            break;
          case 22:
          case 23:
            popSuspenseHandler(interruptedWork);
            popHiddenContext(interruptedWork);
            null !== current2 && pop(resumedCache, interruptedWork);
            break;
          case 24:
            popProvider(CacheContext, interruptedWork);
        }
      }
      function shouldProfile(current2) {
        return (current2.mode & ProfileMode) !== NoMode;
      }
      function commitHookLayoutEffects(finishedWork, hookFlags) {
        shouldProfile(finishedWork) ? (startEffectTimer(), commitHookEffectListMount(hookFlags, finishedWork), recordEffectDuration()) : commitHookEffectListMount(hookFlags, finishedWork);
      }
      function commitHookLayoutUnmountEffects(finishedWork, nearestMountedAncestor, hookFlags) {
        shouldProfile(finishedWork) ? (startEffectTimer(), commitHookEffectListUnmount(
          hookFlags,
          finishedWork,
          nearestMountedAncestor
        ), recordEffectDuration()) : commitHookEffectListUnmount(
          hookFlags,
          finishedWork,
          nearestMountedAncestor
        );
      }
      function commitHookEffectListMount(flags, finishedWork) {
        try {
          var updateQueue = finishedWork.updateQueue, lastEffect = null !== updateQueue ? updateQueue.lastEffect : null;
          if (null !== lastEffect) {
            var firstEffect = lastEffect.next;
            updateQueue = firstEffect;
            do {
              if ((updateQueue.tag & flags) === flags && (lastEffect = void 0, (flags & Insertion) !== NoFlags && (isRunningInsertionEffect = true), lastEffect = runWithFiberInDEV(
                finishedWork,
                callCreateInDEV,
                updateQueue
              ), (flags & Insertion) !== NoFlags && (isRunningInsertionEffect = false), void 0 !== lastEffect && "function" !== typeof lastEffect)) {
                var hookName = void 0;
                hookName = 0 !== (updateQueue.tag & Layout) ? "useLayoutEffect" : 0 !== (updateQueue.tag & Insertion) ? "useInsertionEffect" : "useEffect";
                var addendum = void 0;
                addendum = null === lastEffect ? " You returned null. If your effect does not require clean up, return undefined (or nothing)." : "function" === typeof lastEffect.then ? "\n\nIt looks like you wrote " + hookName + "(async () => ...) or returned a Promise. Instead, write the async function inside your effect and call it immediately:\n\n" + hookName + "(() => {\n  async function fetchData() {\n    // You can await here\n    const response = await MyAPI.getData(someId);\n    // ...\n  }\n  fetchData();\n}, [someId]); // Or [] if effect doesn't need props or state\n\nLearn more about data fetching with Hooks: https://react.dev/link/hooks-data-fetching" : " You returned: " + lastEffect;
                runWithFiberInDEV(
                  finishedWork,
                  function(n, a2) {
                    console.error(
                      "%s must not return anything besides a function, which is used for clean-up.%s",
                      n,
                      a2
                    );
                  },
                  hookName,
                  addendum
                );
              }
              updateQueue = updateQueue.next;
            } while (updateQueue !== firstEffect);
          }
        } catch (error) {
          captureCommitPhaseError(finishedWork, finishedWork.return, error);
        }
      }
      function commitHookEffectListUnmount(flags, finishedWork, nearestMountedAncestor) {
        try {
          var updateQueue = finishedWork.updateQueue, lastEffect = null !== updateQueue ? updateQueue.lastEffect : null;
          if (null !== lastEffect) {
            var firstEffect = lastEffect.next;
            updateQueue = firstEffect;
            do {
              if ((updateQueue.tag & flags) === flags) {
                var inst = updateQueue.inst, destroy = inst.destroy;
                void 0 !== destroy && (inst.destroy = void 0, (flags & Insertion) !== NoFlags && (isRunningInsertionEffect = true), lastEffect = finishedWork, runWithFiberInDEV(
                  lastEffect,
                  callDestroyInDEV,
                  lastEffect,
                  nearestMountedAncestor,
                  destroy
                ), (flags & Insertion) !== NoFlags && (isRunningInsertionEffect = false));
              }
              updateQueue = updateQueue.next;
            } while (updateQueue !== firstEffect);
          }
        } catch (error) {
          captureCommitPhaseError(finishedWork, finishedWork.return, error);
        }
      }
      function commitHookPassiveMountEffects(finishedWork, hookFlags) {
        shouldProfile(finishedWork) ? (startEffectTimer(), commitHookEffectListMount(hookFlags, finishedWork), recordEffectDuration()) : commitHookEffectListMount(hookFlags, finishedWork);
      }
      function commitHookPassiveUnmountEffects(finishedWork, nearestMountedAncestor, hookFlags) {
        shouldProfile(finishedWork) ? (startEffectTimer(), commitHookEffectListUnmount(
          hookFlags,
          finishedWork,
          nearestMountedAncestor
        ), recordEffectDuration()) : commitHookEffectListUnmount(
          hookFlags,
          finishedWork,
          nearestMountedAncestor
        );
      }
      function commitClassCallbacks(finishedWork) {
        var updateQueue = finishedWork.updateQueue;
        if (null !== updateQueue) {
          var instance = finishedWork.stateNode;
          finishedWork.type.defaultProps || "ref" in finishedWork.memoizedProps || didWarnAboutReassigningProps || (instance.props !== finishedWork.memoizedProps && console.error(
            "Expected %s props to match memoized props before processing the update queue. This might either be because of a bug in React, or because a component reassigns its own `this.props`. Please file an issue.",
            getComponentNameFromFiber(finishedWork) || "instance"
          ), instance.state !== finishedWork.memoizedState && console.error(
            "Expected %s state to match memoized state before processing the update queue. This might either be because of a bug in React, or because a component reassigns its own `this.state`. Please file an issue.",
            getComponentNameFromFiber(finishedWork) || "instance"
          ));
          try {
            runWithFiberInDEV(
              finishedWork,
              commitCallbacks,
              updateQueue,
              instance
            );
          } catch (error) {
            captureCommitPhaseError(finishedWork, finishedWork.return, error);
          }
        }
      }
      function callGetSnapshotBeforeUpdates(instance, prevProps, prevState) {
        return instance.getSnapshotBeforeUpdate(prevProps, prevState);
      }
      function commitClassSnapshot(finishedWork, current2) {
        var prevProps = current2.memoizedProps, prevState = current2.memoizedState;
        current2 = finishedWork.stateNode;
        finishedWork.type.defaultProps || "ref" in finishedWork.memoizedProps || didWarnAboutReassigningProps || (current2.props !== finishedWork.memoizedProps && console.error(
          "Expected %s props to match memoized props before getSnapshotBeforeUpdate. This might either be because of a bug in React, or because a component reassigns its own `this.props`. Please file an issue.",
          getComponentNameFromFiber(finishedWork) || "instance"
        ), current2.state !== finishedWork.memoizedState && console.error(
          "Expected %s state to match memoized state before getSnapshotBeforeUpdate. This might either be because of a bug in React, or because a component reassigns its own `this.state`. Please file an issue.",
          getComponentNameFromFiber(finishedWork) || "instance"
        ));
        try {
          var resolvedPrevProps = resolveClassComponentProps(
            finishedWork.type,
            prevProps
          );
          var snapshot = runWithFiberInDEV(
            finishedWork,
            callGetSnapshotBeforeUpdates,
            current2,
            resolvedPrevProps,
            prevState
          );
          prevProps = didWarnAboutUndefinedSnapshotBeforeUpdate;
          void 0 !== snapshot || prevProps.has(finishedWork.type) || (prevProps.add(finishedWork.type), runWithFiberInDEV(finishedWork, function() {
            console.error(
              "%s.getSnapshotBeforeUpdate(): A snapshot value (or null) must be returned. You have returned undefined.",
              getComponentNameFromFiber(finishedWork)
            );
          }));
          current2.__reactInternalSnapshotBeforeUpdate = snapshot;
        } catch (error) {
          captureCommitPhaseError(finishedWork, finishedWork.return, error);
        }
      }
      function safelyCallComponentWillUnmount(current2, nearestMountedAncestor, instance) {
        instance.props = resolveClassComponentProps(
          current2.type,
          current2.memoizedProps
        );
        instance.state = current2.memoizedState;
        shouldProfile(current2) ? (startEffectTimer(), runWithFiberInDEV(
          current2,
          callComponentWillUnmountInDEV,
          current2,
          nearestMountedAncestor,
          instance
        ), recordEffectDuration()) : runWithFiberInDEV(
          current2,
          callComponentWillUnmountInDEV,
          current2,
          nearestMountedAncestor,
          instance
        );
      }
      function commitAttachRef(finishedWork) {
        var ref = finishedWork.ref;
        if (null !== ref) {
          switch (finishedWork.tag) {
            case 26:
            case 27:
            case 5:
              var instanceToUse = finishedWork.stateNode;
              break;
            case 30:
              instanceToUse = finishedWork.stateNode;
              break;
            default:
              instanceToUse = finishedWork.stateNode;
          }
          if ("function" === typeof ref)
            if (shouldProfile(finishedWork))
              try {
                startEffectTimer(), finishedWork.refCleanup = ref(instanceToUse);
              } finally {
                recordEffectDuration();
              }
            else finishedWork.refCleanup = ref(instanceToUse);
          else
            "string" === typeof ref ? console.error("String refs are no longer supported.") : ref.hasOwnProperty("current") || console.error(
              "Unexpected ref object provided for %s. Use either a ref-setter function or React.createRef().",
              getComponentNameFromFiber(finishedWork)
            ), ref.current = instanceToUse;
        }
      }
      function safelyAttachRef(current2, nearestMountedAncestor) {
        try {
          runWithFiberInDEV(current2, commitAttachRef, current2);
        } catch (error) {
          captureCommitPhaseError(current2, nearestMountedAncestor, error);
        }
      }
      function safelyDetachRef(current2, nearestMountedAncestor) {
        var ref = current2.ref, refCleanup = current2.refCleanup;
        if (null !== ref)
          if ("function" === typeof refCleanup)
            try {
              if (shouldProfile(current2))
                try {
                  startEffectTimer(), runWithFiberInDEV(current2, refCleanup);
                } finally {
                  recordEffectDuration(current2);
                }
              else runWithFiberInDEV(current2, refCleanup);
            } catch (error) {
              captureCommitPhaseError(current2, nearestMountedAncestor, error);
            } finally {
              current2.refCleanup = null, current2 = current2.alternate, null != current2 && (current2.refCleanup = null);
            }
          else if ("function" === typeof ref)
            try {
              if (shouldProfile(current2))
                try {
                  startEffectTimer(), runWithFiberInDEV(current2, ref, null);
                } finally {
                  recordEffectDuration(current2);
                }
              else runWithFiberInDEV(current2, ref, null);
            } catch (error$7) {
              captureCommitPhaseError(current2, nearestMountedAncestor, error$7);
            }
          else ref.current = null;
      }
      function commitProfiler(finishedWork, current2, commitStartTime2, effectDuration) {
        var _finishedWork$memoize = finishedWork.memoizedProps, id = _finishedWork$memoize.id, onCommit = _finishedWork$memoize.onCommit;
        _finishedWork$memoize = _finishedWork$memoize.onRender;
        current2 = null === current2 ? "mount" : "update";
        currentUpdateIsNested && (current2 = "nested-update");
        "function" === typeof _finishedWork$memoize && _finishedWork$memoize(
          id,
          current2,
          finishedWork.actualDuration,
          finishedWork.treeBaseDuration,
          finishedWork.actualStartTime,
          commitStartTime2
        );
        "function" === typeof onCommit && onCommit(id, current2, effectDuration, commitStartTime2);
      }
      function commitProfilerPostCommitImpl(finishedWork, current2, commitStartTime2, passiveEffectDuration) {
        var _finishedWork$memoize2 = finishedWork.memoizedProps;
        finishedWork = _finishedWork$memoize2.id;
        _finishedWork$memoize2 = _finishedWork$memoize2.onPostCommit;
        current2 = null === current2 ? "mount" : "update";
        currentUpdateIsNested && (current2 = "nested-update");
        "function" === typeof _finishedWork$memoize2 && _finishedWork$memoize2(
          finishedWork,
          current2,
          passiveEffectDuration,
          commitStartTime2
        );
      }
      function commitHostMount(finishedWork) {
        var type = finishedWork.type, props = finishedWork.memoizedProps, instance = finishedWork.stateNode;
        try {
          runWithFiberInDEV(
            finishedWork,
            commitMount,
            instance,
            type,
            props,
            finishedWork
          );
        } catch (error) {
          captureCommitPhaseError(finishedWork, finishedWork.return, error);
        }
      }
      function commitHostUpdate(finishedWork, newProps, oldProps) {
        try {
          runWithFiberInDEV(
            finishedWork,
            commitUpdate,
            finishedWork.stateNode,
            finishedWork.type,
            oldProps,
            newProps,
            finishedWork
          );
        } catch (error) {
          captureCommitPhaseError(finishedWork, finishedWork.return, error);
        }
      }
      function isHostParent(fiber) {
        return 5 === fiber.tag || 3 === fiber.tag || 26 === fiber.tag || 27 === fiber.tag && isSingletonScope(fiber.type) || 4 === fiber.tag;
      }
      function getHostSibling(fiber) {
        a: for (; ; ) {
          for (; null === fiber.sibling; ) {
            if (null === fiber.return || isHostParent(fiber.return)) return null;
            fiber = fiber.return;
          }
          fiber.sibling.return = fiber.return;
          for (fiber = fiber.sibling; 5 !== fiber.tag && 6 !== fiber.tag && 18 !== fiber.tag; ) {
            if (27 === fiber.tag && isSingletonScope(fiber.type)) continue a;
            if (fiber.flags & 2) continue a;
            if (null === fiber.child || 4 === fiber.tag) continue a;
            else fiber.child.return = fiber, fiber = fiber.child;
          }
          if (!(fiber.flags & 2)) return fiber.stateNode;
        }
      }
      function insertOrAppendPlacementNodeIntoContainer(node, before, parent) {
        var tag = node.tag;
        if (5 === tag || 6 === tag)
          node = node.stateNode, before ? (warnForReactChildrenConflict(parent), (9 === parent.nodeType ? parent.body : "HTML" === parent.nodeName ? parent.ownerDocument.body : parent).insertBefore(node, before)) : (warnForReactChildrenConflict(parent), before = 9 === parent.nodeType ? parent.body : "HTML" === parent.nodeName ? parent.ownerDocument.body : parent, before.appendChild(node), parent = parent._reactRootContainer, null !== parent && void 0 !== parent || null !== before.onclick || (before.onclick = noop$1));
        else if (4 !== tag && (27 === tag && isSingletonScope(node.type) && (parent = node.stateNode, before = null), node = node.child, null !== node))
          for (insertOrAppendPlacementNodeIntoContainer(node, before, parent), node = node.sibling; null !== node; )
            insertOrAppendPlacementNodeIntoContainer(node, before, parent), node = node.sibling;
      }
      function insertOrAppendPlacementNode(node, before, parent) {
        var tag = node.tag;
        if (5 === tag || 6 === tag)
          node = node.stateNode, before ? parent.insertBefore(node, before) : parent.appendChild(node);
        else if (4 !== tag && (27 === tag && isSingletonScope(node.type) && (parent = node.stateNode), node = node.child, null !== node))
          for (insertOrAppendPlacementNode(node, before, parent), node = node.sibling; null !== node; )
            insertOrAppendPlacementNode(node, before, parent), node = node.sibling;
      }
      function commitPlacement(finishedWork) {
        for (var hostParentFiber, parentFiber = finishedWork.return; null !== parentFiber; ) {
          if (isHostParent(parentFiber)) {
            hostParentFiber = parentFiber;
            break;
          }
          parentFiber = parentFiber.return;
        }
        if (null == hostParentFiber)
          throw Error(
            "Expected to find a host parent. This error is likely caused by a bug in React. Please file an issue."
          );
        switch (hostParentFiber.tag) {
          case 27:
            hostParentFiber = hostParentFiber.stateNode;
            parentFiber = getHostSibling(finishedWork);
            insertOrAppendPlacementNode(
              finishedWork,
              parentFiber,
              hostParentFiber
            );
            break;
          case 5:
            parentFiber = hostParentFiber.stateNode;
            hostParentFiber.flags & 32 && (resetTextContent(parentFiber), hostParentFiber.flags &= -33);
            hostParentFiber = getHostSibling(finishedWork);
            insertOrAppendPlacementNode(
              finishedWork,
              hostParentFiber,
              parentFiber
            );
            break;
          case 3:
          case 4:
            hostParentFiber = hostParentFiber.stateNode.containerInfo;
            parentFiber = getHostSibling(finishedWork);
            insertOrAppendPlacementNodeIntoContainer(
              finishedWork,
              parentFiber,
              hostParentFiber
            );
            break;
          default:
            throw Error(
              "Invalid host parent fiber. This error is likely caused by a bug in React. Please file an issue."
            );
        }
      }
      function commitHostSingletonAcquisition(finishedWork) {
        var singleton = finishedWork.stateNode, props = finishedWork.memoizedProps;
        try {
          runWithFiberInDEV(
            finishedWork,
            acquireSingletonInstance,
            finishedWork.type,
            props,
            singleton,
            finishedWork
          );
        } catch (error) {
          captureCommitPhaseError(finishedWork, finishedWork.return, error);
        }
      }
      function isHydratingParent(current2, finishedWork) {
        return 31 === finishedWork.tag ? (finishedWork = finishedWork.memoizedState, null !== current2.memoizedState && null === finishedWork) : 13 === finishedWork.tag ? (current2 = current2.memoizedState, finishedWork = finishedWork.memoizedState, null !== current2 && null !== current2.dehydrated && (null === finishedWork || null === finishedWork.dehydrated)) : 3 === finishedWork.tag ? current2.memoizedState.isDehydrated && 0 === (finishedWork.flags & 256) : false;
      }
      function commitBeforeMutationEffects(root2, firstChild) {
        root2 = root2.containerInfo;
        eventsEnabled = _enabled;
        root2 = getActiveElementDeep(root2);
        if (hasSelectionCapabilities(root2)) {
          if ("selectionStart" in root2)
            var JSCompiler_temp = {
              start: root2.selectionStart,
              end: root2.selectionEnd
            };
          else
            a: {
              JSCompiler_temp = (JSCompiler_temp = root2.ownerDocument) && JSCompiler_temp.defaultView || window;
              var selection = JSCompiler_temp.getSelection && JSCompiler_temp.getSelection();
              if (selection && 0 !== selection.rangeCount) {
                JSCompiler_temp = selection.anchorNode;
                var anchorOffset = selection.anchorOffset, focusNode = selection.focusNode;
                selection = selection.focusOffset;
                try {
                  JSCompiler_temp.nodeType, focusNode.nodeType;
                } catch (e$2) {
                  JSCompiler_temp = null;
                  break a;
                }
                var length = 0, start = -1, end = -1, indexWithinAnchor = 0, indexWithinFocus = 0, node = root2, parentNode2 = null;
                b: for (; ; ) {
                  for (var next; ; ) {
                    node !== JSCompiler_temp || 0 !== anchorOffset && 3 !== node.nodeType || (start = length + anchorOffset);
                    node !== focusNode || 0 !== selection && 3 !== node.nodeType || (end = length + selection);
                    3 === node.nodeType && (length += node.nodeValue.length);
                    if (null === (next = node.firstChild)) break;
                    parentNode2 = node;
                    node = next;
                  }
                  for (; ; ) {
                    if (node === root2) break b;
                    parentNode2 === JSCompiler_temp && ++indexWithinAnchor === anchorOffset && (start = length);
                    parentNode2 === focusNode && ++indexWithinFocus === selection && (end = length);
                    if (null !== (next = node.nextSibling)) break;
                    node = parentNode2;
                    parentNode2 = node.parentNode;
                  }
                  node = next;
                }
                JSCompiler_temp = -1 === start || -1 === end ? null : { start, end };
              } else JSCompiler_temp = null;
            }
          JSCompiler_temp = JSCompiler_temp || { start: 0, end: 0 };
        } else JSCompiler_temp = null;
        selectionInformation = {
          focusedElem: root2,
          selectionRange: JSCompiler_temp
        };
        _enabled = false;
        for (nextEffect = firstChild; null !== nextEffect; )
          if (firstChild = nextEffect, root2 = firstChild.child, 0 !== (firstChild.subtreeFlags & 1028) && null !== root2)
            root2.return = firstChild, nextEffect = root2;
          else
            for (; null !== nextEffect; ) {
              root2 = firstChild = nextEffect;
              JSCompiler_temp = root2.alternate;
              anchorOffset = root2.flags;
              switch (root2.tag) {
                case 0:
                  if (0 !== (anchorOffset & 4) && (root2 = root2.updateQueue, root2 = null !== root2 ? root2.events : null, null !== root2))
                    for (JSCompiler_temp = 0; JSCompiler_temp < root2.length; JSCompiler_temp++)
                      anchorOffset = root2[JSCompiler_temp], anchorOffset.ref.impl = anchorOffset.nextImpl;
                  break;
                case 11:
                case 15:
                  break;
                case 1:
                  0 !== (anchorOffset & 1024) && null !== JSCompiler_temp && commitClassSnapshot(root2, JSCompiler_temp);
                  break;
                case 3:
                  if (0 !== (anchorOffset & 1024)) {
                    if (root2 = root2.stateNode.containerInfo, JSCompiler_temp = root2.nodeType, 9 === JSCompiler_temp)
                      clearContainerSparingly(root2);
                    else if (1 === JSCompiler_temp)
                      switch (root2.nodeName) {
                        case "HEAD":
                        case "HTML":
                        case "BODY":
                          clearContainerSparingly(root2);
                          break;
                        default:
                          root2.textContent = "";
                      }
                  }
                  break;
                case 5:
                case 26:
                case 27:
                case 6:
                case 4:
                case 17:
                  break;
                default:
                  if (0 !== (anchorOffset & 1024))
                    throw Error(
                      "This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue."
                    );
              }
              root2 = firstChild.sibling;
              if (null !== root2) {
                root2.return = firstChild.return;
                nextEffect = root2;
                break;
              }
              nextEffect = firstChild.return;
            }
      }
      function commitLayoutEffectOnFiber(finishedRoot, current2, finishedWork) {
        var prevEffectStart = pushComponentEffectStart(), prevEffectDuration = pushComponentEffectDuration(), prevEffectErrors = pushComponentEffectErrors(), prevEffectDidSpawnUpdate = pushComponentEffectDidSpawnUpdate(), flags = finishedWork.flags;
        switch (finishedWork.tag) {
          case 0:
          case 11:
          case 15:
            recursivelyTraverseLayoutEffects(finishedRoot, finishedWork);
            flags & 4 && commitHookLayoutEffects(finishedWork, Layout | HasEffect);
            break;
          case 1:
            recursivelyTraverseLayoutEffects(finishedRoot, finishedWork);
            if (flags & 4)
              if (finishedRoot = finishedWork.stateNode, null === current2)
                finishedWork.type.defaultProps || "ref" in finishedWork.memoizedProps || didWarnAboutReassigningProps || (finishedRoot.props !== finishedWork.memoizedProps && console.error(
                  "Expected %s props to match memoized props before componentDidMount. This might either be because of a bug in React, or because a component reassigns its own `this.props`. Please file an issue.",
                  getComponentNameFromFiber(finishedWork) || "instance"
                ), finishedRoot.state !== finishedWork.memoizedState && console.error(
                  "Expected %s state to match memoized state before componentDidMount. This might either be because of a bug in React, or because a component reassigns its own `this.state`. Please file an issue.",
                  getComponentNameFromFiber(finishedWork) || "instance"
                )), shouldProfile(finishedWork) ? (startEffectTimer(), runWithFiberInDEV(
                  finishedWork,
                  callComponentDidMountInDEV,
                  finishedWork,
                  finishedRoot
                ), recordEffectDuration()) : runWithFiberInDEV(
                  finishedWork,
                  callComponentDidMountInDEV,
                  finishedWork,
                  finishedRoot
                );
              else {
                var prevProps = resolveClassComponentProps(
                  finishedWork.type,
                  current2.memoizedProps
                );
                current2 = current2.memoizedState;
                finishedWork.type.defaultProps || "ref" in finishedWork.memoizedProps || didWarnAboutReassigningProps || (finishedRoot.props !== finishedWork.memoizedProps && console.error(
                  "Expected %s props to match memoized props before componentDidUpdate. This might either be because of a bug in React, or because a component reassigns its own `this.props`. Please file an issue.",
                  getComponentNameFromFiber(finishedWork) || "instance"
                ), finishedRoot.state !== finishedWork.memoizedState && console.error(
                  "Expected %s state to match memoized state before componentDidUpdate. This might either be because of a bug in React, or because a component reassigns its own `this.state`. Please file an issue.",
                  getComponentNameFromFiber(finishedWork) || "instance"
                ));
                shouldProfile(finishedWork) ? (startEffectTimer(), runWithFiberInDEV(
                  finishedWork,
                  callComponentDidUpdateInDEV,
                  finishedWork,
                  finishedRoot,
                  prevProps,
                  current2,
                  finishedRoot.__reactInternalSnapshotBeforeUpdate
                ), recordEffectDuration()) : runWithFiberInDEV(
                  finishedWork,
                  callComponentDidUpdateInDEV,
                  finishedWork,
                  finishedRoot,
                  prevProps,
                  current2,
                  finishedRoot.__reactInternalSnapshotBeforeUpdate
                );
              }
            flags & 64 && commitClassCallbacks(finishedWork);
            flags & 512 && safelyAttachRef(finishedWork, finishedWork.return);
            break;
          case 3:
            current2 = pushNestedEffectDurations();
            recursivelyTraverseLayoutEffects(finishedRoot, finishedWork);
            if (flags & 64 && (flags = finishedWork.updateQueue, null !== flags)) {
              prevProps = null;
              if (null !== finishedWork.child)
                switch (finishedWork.child.tag) {
                  case 27:
                  case 5:
                    prevProps = finishedWork.child.stateNode;
                    break;
                  case 1:
                    prevProps = finishedWork.child.stateNode;
                }
              try {
                runWithFiberInDEV(
                  finishedWork,
                  commitCallbacks,
                  flags,
                  prevProps
                );
              } catch (error) {
                captureCommitPhaseError(finishedWork, finishedWork.return, error);
              }
            }
            finishedRoot.effectDuration += popNestedEffectDurations(current2);
            break;
          case 27:
            null === current2 && flags & 4 && commitHostSingletonAcquisition(finishedWork);
          case 26:
          case 5:
            recursivelyTraverseLayoutEffects(finishedRoot, finishedWork);
            if (null === current2) {
              if (flags & 4) commitHostMount(finishedWork);
              else if (flags & 64) {
                finishedRoot = finishedWork.type;
                current2 = finishedWork.memoizedProps;
                prevProps = finishedWork.stateNode;
                try {
                  runWithFiberInDEV(
                    finishedWork,
                    commitHydratedInstance,
                    prevProps,
                    finishedRoot,
                    current2,
                    finishedWork
                  );
                } catch (error) {
                  captureCommitPhaseError(
                    finishedWork,
                    finishedWork.return,
                    error
                  );
                }
              }
            }
            flags & 512 && safelyAttachRef(finishedWork, finishedWork.return);
            break;
          case 12:
            if (flags & 4) {
              flags = pushNestedEffectDurations();
              recursivelyTraverseLayoutEffects(finishedRoot, finishedWork);
              finishedRoot = finishedWork.stateNode;
              finishedRoot.effectDuration += bubbleNestedEffectDurations(flags);
              try {
                runWithFiberInDEV(
                  finishedWork,
                  commitProfiler,
                  finishedWork,
                  current2,
                  commitStartTime,
                  finishedRoot.effectDuration
                );
              } catch (error) {
                captureCommitPhaseError(finishedWork, finishedWork.return, error);
              }
            } else recursivelyTraverseLayoutEffects(finishedRoot, finishedWork);
            break;
          case 31:
            recursivelyTraverseLayoutEffects(finishedRoot, finishedWork);
            flags & 4 && commitActivityHydrationCallbacks(finishedRoot, finishedWork);
            break;
          case 13:
            recursivelyTraverseLayoutEffects(finishedRoot, finishedWork);
            flags & 4 && commitSuspenseHydrationCallbacks(finishedRoot, finishedWork);
            flags & 64 && (finishedRoot = finishedWork.memoizedState, null !== finishedRoot && (finishedRoot = finishedRoot.dehydrated, null !== finishedRoot && (flags = retryDehydratedSuspenseBoundary.bind(
              null,
              finishedWork
            ), registerSuspenseInstanceRetry(finishedRoot, flags))));
            break;
          case 22:
            flags = null !== finishedWork.memoizedState || offscreenSubtreeIsHidden;
            if (!flags) {
              current2 = null !== current2 && null !== current2.memoizedState || offscreenSubtreeWasHidden;
              prevProps = offscreenSubtreeIsHidden;
              var prevOffscreenSubtreeWasHidden = offscreenSubtreeWasHidden;
              offscreenSubtreeIsHidden = flags;
              (offscreenSubtreeWasHidden = current2) && !prevOffscreenSubtreeWasHidden ? (recursivelyTraverseReappearLayoutEffects(
                finishedRoot,
                finishedWork,
                0 !== (finishedWork.subtreeFlags & 8772)
              ), (finishedWork.mode & ProfileMode) !== NoMode && 0 <= componentEffectStartTime && 0 <= componentEffectEndTime && 0.05 < componentEffectEndTime - componentEffectStartTime && logComponentReappeared(
                finishedWork,
                componentEffectStartTime,
                componentEffectEndTime
              )) : recursivelyTraverseLayoutEffects(finishedRoot, finishedWork);
              offscreenSubtreeIsHidden = prevProps;
              offscreenSubtreeWasHidden = prevOffscreenSubtreeWasHidden;
            }
            break;
          case 30:
            break;
          default:
            recursivelyTraverseLayoutEffects(finishedRoot, finishedWork);
        }
        (finishedWork.mode & ProfileMode) !== NoMode && 0 <= componentEffectStartTime && 0 <= componentEffectEndTime && ((componentEffectSpawnedUpdate || 0.05 < componentEffectDuration) && logComponentEffect(
          finishedWork,
          componentEffectStartTime,
          componentEffectEndTime,
          componentEffectDuration,
          componentEffectErrors
        ), null === finishedWork.alternate && null !== finishedWork.return && null !== finishedWork.return.alternate && 0.05 < componentEffectEndTime - componentEffectStartTime && (isHydratingParent(
          finishedWork.return.alternate,
          finishedWork.return
        ) || logComponentTrigger(
          finishedWork,
          componentEffectStartTime,
          componentEffectEndTime,
          "Mount"
        )));
        popComponentEffectStart(prevEffectStart);
        popComponentEffectDuration(prevEffectDuration);
        componentEffectErrors = prevEffectErrors;
        componentEffectSpawnedUpdate = prevEffectDidSpawnUpdate;
      }
      function detachFiberAfterEffects(fiber) {
        var alternate = fiber.alternate;
        null !== alternate && (fiber.alternate = null, detachFiberAfterEffects(alternate));
        fiber.child = null;
        fiber.deletions = null;
        fiber.sibling = null;
        5 === fiber.tag && (alternate = fiber.stateNode, null !== alternate && detachDeletedInstance(alternate));
        fiber.stateNode = null;
        fiber._debugOwner = null;
        fiber.return = null;
        fiber.dependencies = null;
        fiber.memoizedProps = null;
        fiber.memoizedState = null;
        fiber.pendingProps = null;
        fiber.stateNode = null;
        fiber.updateQueue = null;
      }
      function recursivelyTraverseDeletionEffects(finishedRoot, nearestMountedAncestor, parent) {
        for (parent = parent.child; null !== parent; )
          commitDeletionEffectsOnFiber(
            finishedRoot,
            nearestMountedAncestor,
            parent
          ), parent = parent.sibling;
      }
      function commitDeletionEffectsOnFiber(finishedRoot, nearestMountedAncestor, deletedFiber) {
        if (injectedHook && "function" === typeof injectedHook.onCommitFiberUnmount)
          try {
            injectedHook.onCommitFiberUnmount(rendererID, deletedFiber);
          } catch (err) {
            hasLoggedError || (hasLoggedError = true, console.error(
              "React instrumentation encountered an error: %o",
              err
            ));
          }
        var prevEffectStart = pushComponentEffectStart(), prevEffectDuration = pushComponentEffectDuration(), prevEffectErrors = pushComponentEffectErrors(), prevEffectDidSpawnUpdate = pushComponentEffectDidSpawnUpdate();
        switch (deletedFiber.tag) {
          case 26:
            offscreenSubtreeWasHidden || safelyDetachRef(deletedFiber, nearestMountedAncestor);
            recursivelyTraverseDeletionEffects(
              finishedRoot,
              nearestMountedAncestor,
              deletedFiber
            );
            deletedFiber.memoizedState ? deletedFiber.memoizedState.count-- : deletedFiber.stateNode && (finishedRoot = deletedFiber.stateNode, finishedRoot.parentNode.removeChild(finishedRoot));
            break;
          case 27:
            offscreenSubtreeWasHidden || safelyDetachRef(deletedFiber, nearestMountedAncestor);
            var prevHostParent = hostParent, prevHostParentIsContainer = hostParentIsContainer;
            isSingletonScope(deletedFiber.type) && (hostParent = deletedFiber.stateNode, hostParentIsContainer = false);
            recursivelyTraverseDeletionEffects(
              finishedRoot,
              nearestMountedAncestor,
              deletedFiber
            );
            runWithFiberInDEV(
              deletedFiber,
              releaseSingletonInstance,
              deletedFiber.stateNode
            );
            hostParent = prevHostParent;
            hostParentIsContainer = prevHostParentIsContainer;
            break;
          case 5:
            offscreenSubtreeWasHidden || safelyDetachRef(deletedFiber, nearestMountedAncestor);
          case 6:
            prevHostParent = hostParent;
            prevHostParentIsContainer = hostParentIsContainer;
            hostParent = null;
            recursivelyTraverseDeletionEffects(
              finishedRoot,
              nearestMountedAncestor,
              deletedFiber
            );
            hostParent = prevHostParent;
            hostParentIsContainer = prevHostParentIsContainer;
            if (null !== hostParent)
              if (hostParentIsContainer)
                try {
                  runWithFiberInDEV(
                    deletedFiber,
                    removeChildFromContainer,
                    hostParent,
                    deletedFiber.stateNode
                  );
                } catch (error) {
                  captureCommitPhaseError(
                    deletedFiber,
                    nearestMountedAncestor,
                    error
                  );
                }
              else
                try {
                  runWithFiberInDEV(
                    deletedFiber,
                    removeChild,
                    hostParent,
                    deletedFiber.stateNode
                  );
                } catch (error) {
                  captureCommitPhaseError(
                    deletedFiber,
                    nearestMountedAncestor,
                    error
                  );
                }
            break;
          case 18:
            null !== hostParent && (hostParentIsContainer ? (finishedRoot = hostParent, clearHydrationBoundary(
              9 === finishedRoot.nodeType ? finishedRoot.body : "HTML" === finishedRoot.nodeName ? finishedRoot.ownerDocument.body : finishedRoot,
              deletedFiber.stateNode
            ), retryIfBlockedOn(finishedRoot)) : clearHydrationBoundary(hostParent, deletedFiber.stateNode));
            break;
          case 4:
            prevHostParent = hostParent;
            prevHostParentIsContainer = hostParentIsContainer;
            hostParent = deletedFiber.stateNode.containerInfo;
            hostParentIsContainer = true;
            recursivelyTraverseDeletionEffects(
              finishedRoot,
              nearestMountedAncestor,
              deletedFiber
            );
            hostParent = prevHostParent;
            hostParentIsContainer = prevHostParentIsContainer;
            break;
          case 0:
          case 11:
          case 14:
          case 15:
            commitHookEffectListUnmount(
              Insertion,
              deletedFiber,
              nearestMountedAncestor
            );
            offscreenSubtreeWasHidden || commitHookLayoutUnmountEffects(
              deletedFiber,
              nearestMountedAncestor,
              Layout
            );
            recursivelyTraverseDeletionEffects(
              finishedRoot,
              nearestMountedAncestor,
              deletedFiber
            );
            break;
          case 1:
            offscreenSubtreeWasHidden || (safelyDetachRef(deletedFiber, nearestMountedAncestor), prevHostParent = deletedFiber.stateNode, "function" === typeof prevHostParent.componentWillUnmount && safelyCallComponentWillUnmount(
              deletedFiber,
              nearestMountedAncestor,
              prevHostParent
            ));
            recursivelyTraverseDeletionEffects(
              finishedRoot,
              nearestMountedAncestor,
              deletedFiber
            );
            break;
          case 21:
            recursivelyTraverseDeletionEffects(
              finishedRoot,
              nearestMountedAncestor,
              deletedFiber
            );
            break;
          case 22:
            offscreenSubtreeWasHidden = (prevHostParent = offscreenSubtreeWasHidden) || null !== deletedFiber.memoizedState;
            recursivelyTraverseDeletionEffects(
              finishedRoot,
              nearestMountedAncestor,
              deletedFiber
            );
            offscreenSubtreeWasHidden = prevHostParent;
            break;
          default:
            recursivelyTraverseDeletionEffects(
              finishedRoot,
              nearestMountedAncestor,
              deletedFiber
            );
        }
        (deletedFiber.mode & ProfileMode) !== NoMode && 0 <= componentEffectStartTime && 0 <= componentEffectEndTime && (componentEffectSpawnedUpdate || 0.05 < componentEffectDuration) && logComponentEffect(
          deletedFiber,
          componentEffectStartTime,
          componentEffectEndTime,
          componentEffectDuration,
          componentEffectErrors
        );
        popComponentEffectStart(prevEffectStart);
        popComponentEffectDuration(prevEffectDuration);
        componentEffectErrors = prevEffectErrors;
        componentEffectSpawnedUpdate = prevEffectDidSpawnUpdate;
      }
      function commitActivityHydrationCallbacks(finishedRoot, finishedWork) {
        if (null === finishedWork.memoizedState && (finishedRoot = finishedWork.alternate, null !== finishedRoot && (finishedRoot = finishedRoot.memoizedState, null !== finishedRoot))) {
          finishedRoot = finishedRoot.dehydrated;
          try {
            runWithFiberInDEV(
              finishedWork,
              commitHydratedActivityInstance,
              finishedRoot
            );
          } catch (error) {
            captureCommitPhaseError(finishedWork, finishedWork.return, error);
          }
        }
      }
      function commitSuspenseHydrationCallbacks(finishedRoot, finishedWork) {
        if (null === finishedWork.memoizedState && (finishedRoot = finishedWork.alternate, null !== finishedRoot && (finishedRoot = finishedRoot.memoizedState, null !== finishedRoot && (finishedRoot = finishedRoot.dehydrated, null !== finishedRoot))))
          try {
            runWithFiberInDEV(
              finishedWork,
              commitHydratedSuspenseInstance,
              finishedRoot
            );
          } catch (error) {
            captureCommitPhaseError(finishedWork, finishedWork.return, error);
          }
      }
      function getRetryCache(finishedWork) {
        switch (finishedWork.tag) {
          case 31:
          case 13:
          case 19:
            var retryCache = finishedWork.stateNode;
            null === retryCache && (retryCache = finishedWork.stateNode = new PossiblyWeakSet());
            return retryCache;
          case 22:
            return finishedWork = finishedWork.stateNode, retryCache = finishedWork._retryCache, null === retryCache && (retryCache = finishedWork._retryCache = new PossiblyWeakSet()), retryCache;
          default:
            throw Error(
              "Unexpected Suspense handler tag (" + finishedWork.tag + "). This is a bug in React."
            );
        }
      }
      function attachSuspenseRetryListeners(finishedWork, wakeables) {
        var retryCache = getRetryCache(finishedWork);
        wakeables.forEach(function(wakeable) {
          if (!retryCache.has(wakeable)) {
            retryCache.add(wakeable);
            if (isDevToolsPresent)
              if (null !== inProgressLanes && null !== inProgressRoot)
                restorePendingUpdaters(inProgressRoot, inProgressLanes);
              else
                throw Error(
                  "Expected finished root and lanes to be set. This is a bug in React."
                );
            var retry = resolveRetryWakeable.bind(null, finishedWork, wakeable);
            wakeable.then(retry, retry);
          }
        });
      }
      function recursivelyTraverseMutationEffects(root$jscomp$0, parentFiber) {
        var deletions = parentFiber.deletions;
        if (null !== deletions)
          for (var i = 0; i < deletions.length; i++) {
            var root2 = root$jscomp$0, returnFiber = parentFiber, deletedFiber = deletions[i], prevEffectStart = pushComponentEffectStart(), parent = returnFiber;
            a: for (; null !== parent; ) {
              switch (parent.tag) {
                case 27:
                  if (isSingletonScope(parent.type)) {
                    hostParent = parent.stateNode;
                    hostParentIsContainer = false;
                    break a;
                  }
                  break;
                case 5:
                  hostParent = parent.stateNode;
                  hostParentIsContainer = false;
                  break a;
                case 3:
                case 4:
                  hostParent = parent.stateNode.containerInfo;
                  hostParentIsContainer = true;
                  break a;
              }
              parent = parent.return;
            }
            if (null === hostParent)
              throw Error(
                "Expected to find a host parent. This error is likely caused by a bug in React. Please file an issue."
              );
            commitDeletionEffectsOnFiber(root2, returnFiber, deletedFiber);
            hostParent = null;
            hostParentIsContainer = false;
            (deletedFiber.mode & ProfileMode) !== NoMode && 0 <= componentEffectStartTime && 0 <= componentEffectEndTime && 0.05 < componentEffectEndTime - componentEffectStartTime && logComponentTrigger(
              deletedFiber,
              componentEffectStartTime,
              componentEffectEndTime,
              "Unmount"
            );
            popComponentEffectStart(prevEffectStart);
            root2 = deletedFiber;
            returnFiber = root2.alternate;
            null !== returnFiber && (returnFiber.return = null);
            root2.return = null;
          }
        if (parentFiber.subtreeFlags & 13886)
          for (parentFiber = parentFiber.child; null !== parentFiber; )
            commitMutationEffectsOnFiber(parentFiber, root$jscomp$0), parentFiber = parentFiber.sibling;
      }
      function commitMutationEffectsOnFiber(finishedWork, root2) {
        var prevEffectStart = pushComponentEffectStart(), prevEffectDuration = pushComponentEffectDuration(), prevEffectErrors = pushComponentEffectErrors(), prevEffectDidSpawnUpdate = pushComponentEffectDidSpawnUpdate(), current2 = finishedWork.alternate, flags = finishedWork.flags;
        switch (finishedWork.tag) {
          case 0:
          case 11:
          case 14:
          case 15:
            recursivelyTraverseMutationEffects(root2, finishedWork);
            commitReconciliationEffects(finishedWork);
            flags & 4 && (commitHookEffectListUnmount(
              Insertion | HasEffect,
              finishedWork,
              finishedWork.return
            ), commitHookEffectListMount(Insertion | HasEffect, finishedWork), commitHookLayoutUnmountEffects(
              finishedWork,
              finishedWork.return,
              Layout | HasEffect
            ));
            break;
          case 1:
            recursivelyTraverseMutationEffects(root2, finishedWork);
            commitReconciliationEffects(finishedWork);
            flags & 512 && (offscreenSubtreeWasHidden || null === current2 || safelyDetachRef(current2, current2.return));
            if (flags & 64 && offscreenSubtreeIsHidden && (flags = finishedWork.updateQueue, null !== flags && (current2 = flags.callbacks, null !== current2))) {
              var existingHiddenCallbacks = flags.shared.hiddenCallbacks;
              flags.shared.hiddenCallbacks = null === existingHiddenCallbacks ? current2 : existingHiddenCallbacks.concat(current2);
            }
            break;
          case 26:
            existingHiddenCallbacks = currentHoistableRoot;
            recursivelyTraverseMutationEffects(root2, finishedWork);
            commitReconciliationEffects(finishedWork);
            flags & 512 && (offscreenSubtreeWasHidden || null === current2 || safelyDetachRef(current2, current2.return));
            if (flags & 4) {
              var currentResource = null !== current2 ? current2.memoizedState : null;
              flags = finishedWork.memoizedState;
              if (null === current2)
                if (null === flags)
                  if (null === finishedWork.stateNode) {
                    a: {
                      flags = finishedWork.type;
                      current2 = finishedWork.memoizedProps;
                      existingHiddenCallbacks = existingHiddenCallbacks.ownerDocument || existingHiddenCallbacks;
                      b: switch (flags) {
                        case "title":
                          currentResource = existingHiddenCallbacks.getElementsByTagName(
                            "title"
                          )[0];
                          if (!currentResource || currentResource[internalHoistableMarker] || currentResource[internalInstanceKey] || currentResource.namespaceURI === SVG_NAMESPACE || currentResource.hasAttribute("itemprop"))
                            currentResource = existingHiddenCallbacks.createElement(flags), existingHiddenCallbacks.head.insertBefore(
                              currentResource,
                              existingHiddenCallbacks.querySelector(
                                "head > title"
                              )
                            );
                          setInitialProperties(currentResource, flags, current2);
                          currentResource[internalInstanceKey] = finishedWork;
                          markNodeAsHoistable(currentResource);
                          flags = currentResource;
                          break a;
                        case "link":
                          var maybeNodes = getHydratableHoistableCache(
                            "link",
                            "href",
                            existingHiddenCallbacks
                          ).get(flags + (current2.href || ""));
                          if (maybeNodes) {
                            for (var i = 0; i < maybeNodes.length; i++)
                              if (currentResource = maybeNodes[i], currentResource.getAttribute("href") === (null == current2.href || "" === current2.href ? null : current2.href) && currentResource.getAttribute("rel") === (null == current2.rel ? null : current2.rel) && currentResource.getAttribute("title") === (null == current2.title ? null : current2.title) && currentResource.getAttribute("crossorigin") === (null == current2.crossOrigin ? null : current2.crossOrigin)) {
                                maybeNodes.splice(i, 1);
                                break b;
                              }
                          }
                          currentResource = existingHiddenCallbacks.createElement(flags);
                          setInitialProperties(currentResource, flags, current2);
                          existingHiddenCallbacks.head.appendChild(
                            currentResource
                          );
                          break;
                        case "meta":
                          if (maybeNodes = getHydratableHoistableCache(
                            "meta",
                            "content",
                            existingHiddenCallbacks
                          ).get(flags + (current2.content || ""))) {
                            for (i = 0; i < maybeNodes.length; i++)
                              if (currentResource = maybeNodes[i], checkAttributeStringCoercion(
                                current2.content,
                                "content"
                              ), currentResource.getAttribute("content") === (null == current2.content ? null : "" + current2.content) && currentResource.getAttribute("name") === (null == current2.name ? null : current2.name) && currentResource.getAttribute("property") === (null == current2.property ? null : current2.property) && currentResource.getAttribute("http-equiv") === (null == current2.httpEquiv ? null : current2.httpEquiv) && currentResource.getAttribute("charset") === (null == current2.charSet ? null : current2.charSet)) {
                                maybeNodes.splice(i, 1);
                                break b;
                              }
                          }
                          currentResource = existingHiddenCallbacks.createElement(flags);
                          setInitialProperties(currentResource, flags, current2);
                          existingHiddenCallbacks.head.appendChild(
                            currentResource
                          );
                          break;
                        default:
                          throw Error(
                            'getNodesForType encountered a type it did not expect: "' + flags + '". This is a bug in React.'
                          );
                      }
                      currentResource[internalInstanceKey] = finishedWork;
                      markNodeAsHoistable(currentResource);
                      flags = currentResource;
                    }
                    finishedWork.stateNode = flags;
                  } else
                    mountHoistable(
                      existingHiddenCallbacks,
                      finishedWork.type,
                      finishedWork.stateNode
                    );
                else
                  finishedWork.stateNode = acquireResource(
                    existingHiddenCallbacks,
                    flags,
                    finishedWork.memoizedProps
                  );
              else
                currentResource !== flags ? (null === currentResource ? null !== current2.stateNode && (current2 = current2.stateNode, current2.parentNode.removeChild(current2)) : currentResource.count--, null === flags ? mountHoistable(
                  existingHiddenCallbacks,
                  finishedWork.type,
                  finishedWork.stateNode
                ) : acquireResource(
                  existingHiddenCallbacks,
                  flags,
                  finishedWork.memoizedProps
                )) : null === flags && null !== finishedWork.stateNode && commitHostUpdate(
                  finishedWork,
                  finishedWork.memoizedProps,
                  current2.memoizedProps
                );
            }
            break;
          case 27:
            recursivelyTraverseMutationEffects(root2, finishedWork);
            commitReconciliationEffects(finishedWork);
            flags & 512 && (offscreenSubtreeWasHidden || null === current2 || safelyDetachRef(current2, current2.return));
            null !== current2 && flags & 4 && commitHostUpdate(
              finishedWork,
              finishedWork.memoizedProps,
              current2.memoizedProps
            );
            break;
          case 5:
            recursivelyTraverseMutationEffects(root2, finishedWork);
            commitReconciliationEffects(finishedWork);
            flags & 512 && (offscreenSubtreeWasHidden || null === current2 || safelyDetachRef(current2, current2.return));
            if (finishedWork.flags & 32) {
              existingHiddenCallbacks = finishedWork.stateNode;
              try {
                runWithFiberInDEV(
                  finishedWork,
                  resetTextContent,
                  existingHiddenCallbacks
                );
              } catch (error) {
                captureCommitPhaseError(finishedWork, finishedWork.return, error);
              }
            }
            flags & 4 && null != finishedWork.stateNode && (existingHiddenCallbacks = finishedWork.memoizedProps, commitHostUpdate(
              finishedWork,
              existingHiddenCallbacks,
              null !== current2 ? current2.memoizedProps : existingHiddenCallbacks
            ));
            flags & 1024 && (needsFormReset = true, "form" !== finishedWork.type && console.error(
              "Unexpected host component type. Expected a form. This is a bug in React."
            ));
            break;
          case 6:
            recursivelyTraverseMutationEffects(root2, finishedWork);
            commitReconciliationEffects(finishedWork);
            if (flags & 4) {
              if (null === finishedWork.stateNode)
                throw Error(
                  "This should have a text node initialized. This error is likely caused by a bug in React. Please file an issue."
                );
              flags = finishedWork.memoizedProps;
              current2 = null !== current2 ? current2.memoizedProps : flags;
              existingHiddenCallbacks = finishedWork.stateNode;
              try {
                runWithFiberInDEV(
                  finishedWork,
                  commitTextUpdate,
                  existingHiddenCallbacks,
                  current2,
                  flags
                );
              } catch (error) {
                captureCommitPhaseError(finishedWork, finishedWork.return, error);
              }
            }
            break;
          case 3:
            existingHiddenCallbacks = pushNestedEffectDurations();
            tagCaches = null;
            currentResource = currentHoistableRoot;
            currentHoistableRoot = getHoistableRoot(root2.containerInfo);
            recursivelyTraverseMutationEffects(root2, finishedWork);
            currentHoistableRoot = currentResource;
            commitReconciliationEffects(finishedWork);
            if (flags & 4 && null !== current2 && current2.memoizedState.isDehydrated)
              try {
                runWithFiberInDEV(
                  finishedWork,
                  commitHydratedContainer,
                  root2.containerInfo
                );
              } catch (error) {
                captureCommitPhaseError(finishedWork, finishedWork.return, error);
              }
            needsFormReset && (needsFormReset = false, recursivelyResetForms(finishedWork));
            root2.effectDuration += popNestedEffectDurations(
              existingHiddenCallbacks
            );
            break;
          case 4:
            flags = currentHoistableRoot;
            currentHoistableRoot = getHoistableRoot(
              finishedWork.stateNode.containerInfo
            );
            recursivelyTraverseMutationEffects(root2, finishedWork);
            commitReconciliationEffects(finishedWork);
            currentHoistableRoot = flags;
            break;
          case 12:
            flags = pushNestedEffectDurations();
            recursivelyTraverseMutationEffects(root2, finishedWork);
            commitReconciliationEffects(finishedWork);
            finishedWork.stateNode.effectDuration += bubbleNestedEffectDurations(flags);
            break;
          case 31:
            recursivelyTraverseMutationEffects(root2, finishedWork);
            commitReconciliationEffects(finishedWork);
            flags & 4 && (flags = finishedWork.updateQueue, null !== flags && (finishedWork.updateQueue = null, attachSuspenseRetryListeners(finishedWork, flags)));
            break;
          case 13:
            recursivelyTraverseMutationEffects(root2, finishedWork);
            commitReconciliationEffects(finishedWork);
            finishedWork.child.flags & 8192 && null !== finishedWork.memoizedState !== (null !== current2 && null !== current2.memoizedState) && (globalMostRecentFallbackTime = now$1());
            flags & 4 && (flags = finishedWork.updateQueue, null !== flags && (finishedWork.updateQueue = null, attachSuspenseRetryListeners(finishedWork, flags)));
            break;
          case 22:
            existingHiddenCallbacks = null !== finishedWork.memoizedState;
            var wasHidden = null !== current2 && null !== current2.memoizedState, prevOffscreenSubtreeIsHidden = offscreenSubtreeIsHidden, prevOffscreenSubtreeWasHidden = offscreenSubtreeWasHidden;
            offscreenSubtreeIsHidden = prevOffscreenSubtreeIsHidden || existingHiddenCallbacks;
            offscreenSubtreeWasHidden = prevOffscreenSubtreeWasHidden || wasHidden;
            recursivelyTraverseMutationEffects(root2, finishedWork);
            offscreenSubtreeWasHidden = prevOffscreenSubtreeWasHidden;
            offscreenSubtreeIsHidden = prevOffscreenSubtreeIsHidden;
            wasHidden && !existingHiddenCallbacks && !prevOffscreenSubtreeIsHidden && !prevOffscreenSubtreeWasHidden && (finishedWork.mode & ProfileMode) !== NoMode && 0 <= componentEffectStartTime && 0 <= componentEffectEndTime && 0.05 < componentEffectEndTime - componentEffectStartTime && logComponentReappeared(
              finishedWork,
              componentEffectStartTime,
              componentEffectEndTime
            );
            commitReconciliationEffects(finishedWork);
            if (flags & 8192)
              a: for (root2 = finishedWork.stateNode, root2._visibility = existingHiddenCallbacks ? root2._visibility & ~OffscreenVisible : root2._visibility | OffscreenVisible, !existingHiddenCallbacks || null === current2 || wasHidden || offscreenSubtreeIsHidden || offscreenSubtreeWasHidden || (recursivelyTraverseDisappearLayoutEffects(finishedWork), (finishedWork.mode & ProfileMode) !== NoMode && 0 <= componentEffectStartTime && 0 <= componentEffectEndTime && 0.05 < componentEffectEndTime - componentEffectStartTime && logComponentTrigger(
                finishedWork,
                componentEffectStartTime,
                componentEffectEndTime,
                "Disconnect"
              )), current2 = null, root2 = finishedWork; ; ) {
                if (5 === root2.tag || 26 === root2.tag) {
                  if (null === current2) {
                    wasHidden = current2 = root2;
                    try {
                      currentResource = wasHidden.stateNode, existingHiddenCallbacks ? runWithFiberInDEV(
                        wasHidden,
                        hideInstance,
                        currentResource
                      ) : runWithFiberInDEV(
                        wasHidden,
                        unhideInstance,
                        wasHidden.stateNode,
                        wasHidden.memoizedProps
                      );
                    } catch (error) {
                      captureCommitPhaseError(wasHidden, wasHidden.return, error);
                    }
                  }
                } else if (6 === root2.tag) {
                  if (null === current2) {
                    wasHidden = root2;
                    try {
                      maybeNodes = wasHidden.stateNode, existingHiddenCallbacks ? runWithFiberInDEV(
                        wasHidden,
                        hideTextInstance,
                        maybeNodes
                      ) : runWithFiberInDEV(
                        wasHidden,
                        unhideTextInstance,
                        maybeNodes,
                        wasHidden.memoizedProps
                      );
                    } catch (error) {
                      captureCommitPhaseError(wasHidden, wasHidden.return, error);
                    }
                  }
                } else if (18 === root2.tag) {
                  if (null === current2) {
                    wasHidden = root2;
                    try {
                      i = wasHidden.stateNode, existingHiddenCallbacks ? runWithFiberInDEV(
                        wasHidden,
                        hideDehydratedBoundary,
                        i
                      ) : runWithFiberInDEV(
                        wasHidden,
                        unhideDehydratedBoundary,
                        wasHidden.stateNode
                      );
                    } catch (error) {
                      captureCommitPhaseError(wasHidden, wasHidden.return, error);
                    }
                  }
                } else if ((22 !== root2.tag && 23 !== root2.tag || null === root2.memoizedState || root2 === finishedWork) && null !== root2.child) {
                  root2.child.return = root2;
                  root2 = root2.child;
                  continue;
                }
                if (root2 === finishedWork) break a;
                for (; null === root2.sibling; ) {
                  if (null === root2.return || root2.return === finishedWork)
                    break a;
                  current2 === root2 && (current2 = null);
                  root2 = root2.return;
                }
                current2 === root2 && (current2 = null);
                root2.sibling.return = root2.return;
                root2 = root2.sibling;
              }
            flags & 4 && (flags = finishedWork.updateQueue, null !== flags && (current2 = flags.retryQueue, null !== current2 && (flags.retryQueue = null, attachSuspenseRetryListeners(finishedWork, current2))));
            break;
          case 19:
            recursivelyTraverseMutationEffects(root2, finishedWork);
            commitReconciliationEffects(finishedWork);
            flags & 4 && (flags = finishedWork.updateQueue, null !== flags && (finishedWork.updateQueue = null, attachSuspenseRetryListeners(finishedWork, flags)));
            break;
          case 30:
            break;
          case 21:
            break;
          default:
            recursivelyTraverseMutationEffects(root2, finishedWork), commitReconciliationEffects(finishedWork);
        }
        (finishedWork.mode & ProfileMode) !== NoMode && 0 <= componentEffectStartTime && 0 <= componentEffectEndTime && ((componentEffectSpawnedUpdate || 0.05 < componentEffectDuration) && logComponentEffect(
          finishedWork,
          componentEffectStartTime,
          componentEffectEndTime,
          componentEffectDuration,
          componentEffectErrors
        ), null === finishedWork.alternate && null !== finishedWork.return && null !== finishedWork.return.alternate && 0.05 < componentEffectEndTime - componentEffectStartTime && (isHydratingParent(
          finishedWork.return.alternate,
          finishedWork.return
        ) || logComponentTrigger(
          finishedWork,
          componentEffectStartTime,
          componentEffectEndTime,
          "Mount"
        )));
        popComponentEffectStart(prevEffectStart);
        popComponentEffectDuration(prevEffectDuration);
        componentEffectErrors = prevEffectErrors;
        componentEffectSpawnedUpdate = prevEffectDidSpawnUpdate;
      }
      function commitReconciliationEffects(finishedWork) {
        var flags = finishedWork.flags;
        if (flags & 2) {
          try {
            runWithFiberInDEV(finishedWork, commitPlacement, finishedWork);
          } catch (error) {
            captureCommitPhaseError(finishedWork, finishedWork.return, error);
          }
          finishedWork.flags &= -3;
        }
        flags & 4096 && (finishedWork.flags &= -4097);
      }
      function recursivelyResetForms(parentFiber) {
        if (parentFiber.subtreeFlags & 1024)
          for (parentFiber = parentFiber.child; null !== parentFiber; ) {
            var fiber = parentFiber;
            recursivelyResetForms(fiber);
            5 === fiber.tag && fiber.flags & 1024 && fiber.stateNode.reset();
            parentFiber = parentFiber.sibling;
          }
      }
      function recursivelyTraverseLayoutEffects(root2, parentFiber) {
        if (parentFiber.subtreeFlags & 8772)
          for (parentFiber = parentFiber.child; null !== parentFiber; )
            commitLayoutEffectOnFiber(root2, parentFiber.alternate, parentFiber), parentFiber = parentFiber.sibling;
      }
      function disappearLayoutEffects(finishedWork) {
        var prevEffectStart = pushComponentEffectStart(), prevEffectDuration = pushComponentEffectDuration(), prevEffectErrors = pushComponentEffectErrors(), prevEffectDidSpawnUpdate = pushComponentEffectDidSpawnUpdate();
        switch (finishedWork.tag) {
          case 0:
          case 11:
          case 14:
          case 15:
            commitHookLayoutUnmountEffects(
              finishedWork,
              finishedWork.return,
              Layout
            );
            recursivelyTraverseDisappearLayoutEffects(finishedWork);
            break;
          case 1:
            safelyDetachRef(finishedWork, finishedWork.return);
            var instance = finishedWork.stateNode;
            "function" === typeof instance.componentWillUnmount && safelyCallComponentWillUnmount(
              finishedWork,
              finishedWork.return,
              instance
            );
            recursivelyTraverseDisappearLayoutEffects(finishedWork);
            break;
          case 27:
            runWithFiberInDEV(
              finishedWork,
              releaseSingletonInstance,
              finishedWork.stateNode
            );
          case 26:
          case 5:
            safelyDetachRef(finishedWork, finishedWork.return);
            recursivelyTraverseDisappearLayoutEffects(finishedWork);
            break;
          case 22:
            null === finishedWork.memoizedState && recursivelyTraverseDisappearLayoutEffects(finishedWork);
            break;
          case 30:
            recursivelyTraverseDisappearLayoutEffects(finishedWork);
            break;
          default:
            recursivelyTraverseDisappearLayoutEffects(finishedWork);
        }
        (finishedWork.mode & ProfileMode) !== NoMode && 0 <= componentEffectStartTime && 0 <= componentEffectEndTime && (componentEffectSpawnedUpdate || 0.05 < componentEffectDuration) && logComponentEffect(
          finishedWork,
          componentEffectStartTime,
          componentEffectEndTime,
          componentEffectDuration,
          componentEffectErrors
        );
        popComponentEffectStart(prevEffectStart);
        popComponentEffectDuration(prevEffectDuration);
        componentEffectErrors = prevEffectErrors;
        componentEffectSpawnedUpdate = prevEffectDidSpawnUpdate;
      }
      function recursivelyTraverseDisappearLayoutEffects(parentFiber) {
        for (parentFiber = parentFiber.child; null !== parentFiber; )
          disappearLayoutEffects(parentFiber), parentFiber = parentFiber.sibling;
      }
      function reappearLayoutEffects(finishedRoot, current2, finishedWork, includeWorkInProgressEffects) {
        var prevEffectStart = pushComponentEffectStart(), prevEffectDuration = pushComponentEffectDuration(), prevEffectErrors = pushComponentEffectErrors(), prevEffectDidSpawnUpdate = pushComponentEffectDidSpawnUpdate(), flags = finishedWork.flags;
        switch (finishedWork.tag) {
          case 0:
          case 11:
          case 15:
            recursivelyTraverseReappearLayoutEffects(
              finishedRoot,
              finishedWork,
              includeWorkInProgressEffects
            );
            commitHookLayoutEffects(finishedWork, Layout);
            break;
          case 1:
            recursivelyTraverseReappearLayoutEffects(
              finishedRoot,
              finishedWork,
              includeWorkInProgressEffects
            );
            current2 = finishedWork.stateNode;
            "function" === typeof current2.componentDidMount && runWithFiberInDEV(
              finishedWork,
              callComponentDidMountInDEV,
              finishedWork,
              current2
            );
            current2 = finishedWork.updateQueue;
            if (null !== current2) {
              finishedRoot = finishedWork.stateNode;
              try {
                runWithFiberInDEV(
                  finishedWork,
                  commitHiddenCallbacks,
                  current2,
                  finishedRoot
                );
              } catch (error) {
                captureCommitPhaseError(finishedWork, finishedWork.return, error);
              }
            }
            includeWorkInProgressEffects && flags & 64 && commitClassCallbacks(finishedWork);
            safelyAttachRef(finishedWork, finishedWork.return);
            break;
          case 27:
            commitHostSingletonAcquisition(finishedWork);
          case 26:
          case 5:
            recursivelyTraverseReappearLayoutEffects(
              finishedRoot,
              finishedWork,
              includeWorkInProgressEffects
            );
            includeWorkInProgressEffects && null === current2 && flags & 4 && commitHostMount(finishedWork);
            safelyAttachRef(finishedWork, finishedWork.return);
            break;
          case 12:
            if (includeWorkInProgressEffects && flags & 4) {
              flags = pushNestedEffectDurations();
              recursivelyTraverseReappearLayoutEffects(
                finishedRoot,
                finishedWork,
                includeWorkInProgressEffects
              );
              includeWorkInProgressEffects = finishedWork.stateNode;
              includeWorkInProgressEffects.effectDuration += bubbleNestedEffectDurations(flags);
              try {
                runWithFiberInDEV(
                  finishedWork,
                  commitProfiler,
                  finishedWork,
                  current2,
                  commitStartTime,
                  includeWorkInProgressEffects.effectDuration
                );
              } catch (error) {
                captureCommitPhaseError(finishedWork, finishedWork.return, error);
              }
            } else
              recursivelyTraverseReappearLayoutEffects(
                finishedRoot,
                finishedWork,
                includeWorkInProgressEffects
              );
            break;
          case 31:
            recursivelyTraverseReappearLayoutEffects(
              finishedRoot,
              finishedWork,
              includeWorkInProgressEffects
            );
            includeWorkInProgressEffects && flags & 4 && commitActivityHydrationCallbacks(finishedRoot, finishedWork);
            break;
          case 13:
            recursivelyTraverseReappearLayoutEffects(
              finishedRoot,
              finishedWork,
              includeWorkInProgressEffects
            );
            includeWorkInProgressEffects && flags & 4 && commitSuspenseHydrationCallbacks(finishedRoot, finishedWork);
            break;
          case 22:
            null === finishedWork.memoizedState && recursivelyTraverseReappearLayoutEffects(
              finishedRoot,
              finishedWork,
              includeWorkInProgressEffects
            );
            safelyAttachRef(finishedWork, finishedWork.return);
            break;
          case 30:
            break;
          default:
            recursivelyTraverseReappearLayoutEffects(
              finishedRoot,
              finishedWork,
              includeWorkInProgressEffects
            );
        }
        (finishedWork.mode & ProfileMode) !== NoMode && 0 <= componentEffectStartTime && 0 <= componentEffectEndTime && (componentEffectSpawnedUpdate || 0.05 < componentEffectDuration) && logComponentEffect(
          finishedWork,
          componentEffectStartTime,
          componentEffectEndTime,
          componentEffectDuration,
          componentEffectErrors
        );
        popComponentEffectStart(prevEffectStart);
        popComponentEffectDuration(prevEffectDuration);
        componentEffectErrors = prevEffectErrors;
        componentEffectSpawnedUpdate = prevEffectDidSpawnUpdate;
      }
      function recursivelyTraverseReappearLayoutEffects(finishedRoot, parentFiber, includeWorkInProgressEffects) {
        includeWorkInProgressEffects = includeWorkInProgressEffects && 0 !== (parentFiber.subtreeFlags & 8772);
        for (parentFiber = parentFiber.child; null !== parentFiber; )
          reappearLayoutEffects(
            finishedRoot,
            parentFiber.alternate,
            parentFiber,
            includeWorkInProgressEffects
          ), parentFiber = parentFiber.sibling;
      }
      function commitOffscreenPassiveMountEffects(current2, finishedWork) {
        var previousCache = null;
        null !== current2 && null !== current2.memoizedState && null !== current2.memoizedState.cachePool && (previousCache = current2.memoizedState.cachePool.pool);
        current2 = null;
        null !== finishedWork.memoizedState && null !== finishedWork.memoizedState.cachePool && (current2 = finishedWork.memoizedState.cachePool.pool);
        current2 !== previousCache && (null != current2 && retainCache(current2), null != previousCache && releaseCache(previousCache));
      }
      function commitCachePassiveMountEffect(current2, finishedWork) {
        current2 = null;
        null !== finishedWork.alternate && (current2 = finishedWork.alternate.memoizedState.cache);
        finishedWork = finishedWork.memoizedState.cache;
        finishedWork !== current2 && (retainCache(finishedWork), null != current2 && releaseCache(current2));
      }
      function recursivelyTraversePassiveMountEffects(root2, parentFiber, committedLanes, committedTransitions, endTime) {
        if (parentFiber.subtreeFlags & 10256 || 0 !== parentFiber.actualDuration && (null === parentFiber.alternate || parentFiber.alternate.child !== parentFiber.child))
          for (parentFiber = parentFiber.child; null !== parentFiber; ) {
            var nextSibling = parentFiber.sibling;
            commitPassiveMountOnFiber(
              root2,
              parentFiber,
              committedLanes,
              committedTransitions,
              null !== nextSibling ? nextSibling.actualStartTime : endTime
            );
            parentFiber = nextSibling;
          }
      }
      function commitPassiveMountOnFiber(finishedRoot, finishedWork, committedLanes, committedTransitions, endTime) {
        var prevEffectStart = pushComponentEffectStart(), prevEffectDuration = pushComponentEffectDuration(), prevEffectErrors = pushComponentEffectErrors(), prevEffectDidSpawnUpdate = pushComponentEffectDidSpawnUpdate(), prevDeepEquality = alreadyWarnedForDeepEquality, flags = finishedWork.flags;
        switch (finishedWork.tag) {
          case 0:
          case 11:
          case 15:
            (finishedWork.mode & ProfileMode) !== NoMode && 0 < finishedWork.actualStartTime && 0 !== (finishedWork.flags & 1) && logComponentRender(
              finishedWork,
              finishedWork.actualStartTime,
              endTime,
              inHydratedSubtree,
              committedLanes
            );
            recursivelyTraversePassiveMountEffects(
              finishedRoot,
              finishedWork,
              committedLanes,
              committedTransitions,
              endTime
            );
            flags & 2048 && commitHookPassiveMountEffects(finishedWork, Passive | HasEffect);
            break;
          case 1:
            (finishedWork.mode & ProfileMode) !== NoMode && 0 < finishedWork.actualStartTime && (0 !== (finishedWork.flags & 128) ? logComponentErrored(
              finishedWork,
              finishedWork.actualStartTime,
              endTime,
              []
            ) : 0 !== (finishedWork.flags & 1) && logComponentRender(
              finishedWork,
              finishedWork.actualStartTime,
              endTime,
              inHydratedSubtree,
              committedLanes
            ));
            recursivelyTraversePassiveMountEffects(
              finishedRoot,
              finishedWork,
              committedLanes,
              committedTransitions,
              endTime
            );
            break;
          case 3:
            var prevProfilerEffectDuration = pushNestedEffectDurations(), wasInHydratedSubtree = inHydratedSubtree;
            inHydratedSubtree = null !== finishedWork.alternate && finishedWork.alternate.memoizedState.isDehydrated && 0 === (finishedWork.flags & 256);
            recursivelyTraversePassiveMountEffects(
              finishedRoot,
              finishedWork,
              committedLanes,
              committedTransitions,
              endTime
            );
            inHydratedSubtree = wasInHydratedSubtree;
            flags & 2048 && (committedLanes = null, null !== finishedWork.alternate && (committedLanes = finishedWork.alternate.memoizedState.cache), committedTransitions = finishedWork.memoizedState.cache, committedTransitions !== committedLanes && (retainCache(committedTransitions), null != committedLanes && releaseCache(committedLanes)));
            finishedRoot.passiveEffectDuration += popNestedEffectDurations(
              prevProfilerEffectDuration
            );
            break;
          case 12:
            if (flags & 2048) {
              flags = pushNestedEffectDurations();
              recursivelyTraversePassiveMountEffects(
                finishedRoot,
                finishedWork,
                committedLanes,
                committedTransitions,
                endTime
              );
              finishedRoot = finishedWork.stateNode;
              finishedRoot.passiveEffectDuration += bubbleNestedEffectDurations(flags);
              try {
                runWithFiberInDEV(
                  finishedWork,
                  commitProfilerPostCommitImpl,
                  finishedWork,
                  finishedWork.alternate,
                  commitStartTime,
                  finishedRoot.passiveEffectDuration
                );
              } catch (error) {
                captureCommitPhaseError(finishedWork, finishedWork.return, error);
              }
            } else
              recursivelyTraversePassiveMountEffects(
                finishedRoot,
                finishedWork,
                committedLanes,
                committedTransitions,
                endTime
              );
            break;
          case 31:
            flags = inHydratedSubtree;
            prevProfilerEffectDuration = null !== finishedWork.alternate ? finishedWork.alternate.memoizedState : null;
            wasInHydratedSubtree = finishedWork.memoizedState;
            null !== prevProfilerEffectDuration && null === wasInHydratedSubtree ? (wasInHydratedSubtree = finishedWork.deletions, null !== wasInHydratedSubtree && 0 < wasInHydratedSubtree.length && 18 === wasInHydratedSubtree[0].tag ? (inHydratedSubtree = false, prevProfilerEffectDuration = prevProfilerEffectDuration.hydrationErrors, null !== prevProfilerEffectDuration && logComponentErrored(
              finishedWork,
              finishedWork.actualStartTime,
              endTime,
              prevProfilerEffectDuration
            )) : inHydratedSubtree = true) : inHydratedSubtree = false;
            recursivelyTraversePassiveMountEffects(
              finishedRoot,
              finishedWork,
              committedLanes,
              committedTransitions,
              endTime
            );
            inHydratedSubtree = flags;
            break;
          case 13:
            flags = inHydratedSubtree;
            prevProfilerEffectDuration = null !== finishedWork.alternate ? finishedWork.alternate.memoizedState : null;
            wasInHydratedSubtree = finishedWork.memoizedState;
            null === prevProfilerEffectDuration || null === prevProfilerEffectDuration.dehydrated || null !== wasInHydratedSubtree && null !== wasInHydratedSubtree.dehydrated ? inHydratedSubtree = false : (wasInHydratedSubtree = finishedWork.deletions, null !== wasInHydratedSubtree && 0 < wasInHydratedSubtree.length && 18 === wasInHydratedSubtree[0].tag ? (inHydratedSubtree = false, prevProfilerEffectDuration = prevProfilerEffectDuration.hydrationErrors, null !== prevProfilerEffectDuration && logComponentErrored(
              finishedWork,
              finishedWork.actualStartTime,
              endTime,
              prevProfilerEffectDuration
            )) : inHydratedSubtree = true);
            recursivelyTraversePassiveMountEffects(
              finishedRoot,
              finishedWork,
              committedLanes,
              committedTransitions,
              endTime
            );
            inHydratedSubtree = flags;
            break;
          case 23:
            break;
          case 22:
            wasInHydratedSubtree = finishedWork.stateNode;
            prevProfilerEffectDuration = finishedWork.alternate;
            null !== finishedWork.memoizedState ? wasInHydratedSubtree._visibility & OffscreenPassiveEffectsConnected ? recursivelyTraversePassiveMountEffects(
              finishedRoot,
              finishedWork,
              committedLanes,
              committedTransitions,
              endTime
            ) : recursivelyTraverseAtomicPassiveEffects(
              finishedRoot,
              finishedWork,
              committedLanes,
              committedTransitions,
              endTime
            ) : wasInHydratedSubtree._visibility & OffscreenPassiveEffectsConnected ? recursivelyTraversePassiveMountEffects(
              finishedRoot,
              finishedWork,
              committedLanes,
              committedTransitions,
              endTime
            ) : (wasInHydratedSubtree._visibility |= OffscreenPassiveEffectsConnected, recursivelyTraverseReconnectPassiveEffects(
              finishedRoot,
              finishedWork,
              committedLanes,
              committedTransitions,
              0 !== (finishedWork.subtreeFlags & 10256) || 0 !== finishedWork.actualDuration && (null === finishedWork.alternate || finishedWork.alternate.child !== finishedWork.child),
              endTime
            ), (finishedWork.mode & ProfileMode) === NoMode || inHydratedSubtree || (finishedRoot = finishedWork.actualStartTime, 0 <= finishedRoot && 0.05 < endTime - finishedRoot && logComponentReappeared(finishedWork, finishedRoot, endTime), 0 <= componentEffectStartTime && 0 <= componentEffectEndTime && 0.05 < componentEffectEndTime - componentEffectStartTime && logComponentReappeared(
              finishedWork,
              componentEffectStartTime,
              componentEffectEndTime
            )));
            flags & 2048 && commitOffscreenPassiveMountEffects(
              prevProfilerEffectDuration,
              finishedWork
            );
            break;
          case 24:
            recursivelyTraversePassiveMountEffects(
              finishedRoot,
              finishedWork,
              committedLanes,
              committedTransitions,
              endTime
            );
            flags & 2048 && commitCachePassiveMountEffect(finishedWork.alternate, finishedWork);
            break;
          default:
            recursivelyTraversePassiveMountEffects(
              finishedRoot,
              finishedWork,
              committedLanes,
              committedTransitions,
              endTime
            );
        }
        if ((finishedWork.mode & ProfileMode) !== NoMode) {
          if (finishedRoot = !inHydratedSubtree && null === finishedWork.alternate && null !== finishedWork.return && null !== finishedWork.return.alternate)
            committedLanes = finishedWork.actualStartTime, 0 <= committedLanes && 0.05 < endTime - committedLanes && logComponentTrigger(
              finishedWork,
              committedLanes,
              endTime,
              "Mount"
            );
          0 <= componentEffectStartTime && 0 <= componentEffectEndTime && ((componentEffectSpawnedUpdate || 0.05 < componentEffectDuration) && logComponentEffect(
            finishedWork,
            componentEffectStartTime,
            componentEffectEndTime,
            componentEffectDuration,
            componentEffectErrors
          ), finishedRoot && 0.05 < componentEffectEndTime - componentEffectStartTime && logComponentTrigger(
            finishedWork,
            componentEffectStartTime,
            componentEffectEndTime,
            "Mount"
          ));
        }
        popComponentEffectStart(prevEffectStart);
        popComponentEffectDuration(prevEffectDuration);
        componentEffectErrors = prevEffectErrors;
        componentEffectSpawnedUpdate = prevEffectDidSpawnUpdate;
        alreadyWarnedForDeepEquality = prevDeepEquality;
      }
      function recursivelyTraverseReconnectPassiveEffects(finishedRoot, parentFiber, committedLanes, committedTransitions, includeWorkInProgressEffects, endTime) {
        includeWorkInProgressEffects = includeWorkInProgressEffects && (0 !== (parentFiber.subtreeFlags & 10256) || 0 !== parentFiber.actualDuration && (null === parentFiber.alternate || parentFiber.alternate.child !== parentFiber.child));
        for (parentFiber = parentFiber.child; null !== parentFiber; ) {
          var nextSibling = parentFiber.sibling;
          reconnectPassiveEffects(
            finishedRoot,
            parentFiber,
            committedLanes,
            committedTransitions,
            includeWorkInProgressEffects,
            null !== nextSibling ? nextSibling.actualStartTime : endTime
          );
          parentFiber = nextSibling;
        }
      }
      function reconnectPassiveEffects(finishedRoot, finishedWork, committedLanes, committedTransitions, includeWorkInProgressEffects, endTime) {
        var prevEffectStart = pushComponentEffectStart(), prevEffectDuration = pushComponentEffectDuration(), prevEffectErrors = pushComponentEffectErrors(), prevEffectDidSpawnUpdate = pushComponentEffectDidSpawnUpdate(), prevDeepEquality = alreadyWarnedForDeepEquality;
        includeWorkInProgressEffects && (finishedWork.mode & ProfileMode) !== NoMode && 0 < finishedWork.actualStartTime && 0 !== (finishedWork.flags & 1) && logComponentRender(
          finishedWork,
          finishedWork.actualStartTime,
          endTime,
          inHydratedSubtree,
          committedLanes
        );
        var flags = finishedWork.flags;
        switch (finishedWork.tag) {
          case 0:
          case 11:
          case 15:
            recursivelyTraverseReconnectPassiveEffects(
              finishedRoot,
              finishedWork,
              committedLanes,
              committedTransitions,
              includeWorkInProgressEffects,
              endTime
            );
            commitHookPassiveMountEffects(finishedWork, Passive);
            break;
          case 23:
            break;
          case 22:
            var _instance2 = finishedWork.stateNode;
            null !== finishedWork.memoizedState ? _instance2._visibility & OffscreenPassiveEffectsConnected ? recursivelyTraverseReconnectPassiveEffects(
              finishedRoot,
              finishedWork,
              committedLanes,
              committedTransitions,
              includeWorkInProgressEffects,
              endTime
            ) : recursivelyTraverseAtomicPassiveEffects(
              finishedRoot,
              finishedWork,
              committedLanes,
              committedTransitions,
              endTime
            ) : (_instance2._visibility |= OffscreenPassiveEffectsConnected, recursivelyTraverseReconnectPassiveEffects(
              finishedRoot,
              finishedWork,
              committedLanes,
              committedTransitions,
              includeWorkInProgressEffects,
              endTime
            ));
            includeWorkInProgressEffects && flags & 2048 && commitOffscreenPassiveMountEffects(
              finishedWork.alternate,
              finishedWork
            );
            break;
          case 24:
            recursivelyTraverseReconnectPassiveEffects(
              finishedRoot,
              finishedWork,
              committedLanes,
              committedTransitions,
              includeWorkInProgressEffects,
              endTime
            );
            includeWorkInProgressEffects && flags & 2048 && commitCachePassiveMountEffect(finishedWork.alternate, finishedWork);
            break;
          default:
            recursivelyTraverseReconnectPassiveEffects(
              finishedRoot,
              finishedWork,
              committedLanes,
              committedTransitions,
              includeWorkInProgressEffects,
              endTime
            );
        }
        (finishedWork.mode & ProfileMode) !== NoMode && 0 <= componentEffectStartTime && 0 <= componentEffectEndTime && (componentEffectSpawnedUpdate || 0.05 < componentEffectDuration) && logComponentEffect(
          finishedWork,
          componentEffectStartTime,
          componentEffectEndTime,
          componentEffectDuration,
          componentEffectErrors
        );
        popComponentEffectStart(prevEffectStart);
        popComponentEffectDuration(prevEffectDuration);
        componentEffectErrors = prevEffectErrors;
        componentEffectSpawnedUpdate = prevEffectDidSpawnUpdate;
        alreadyWarnedForDeepEquality = prevDeepEquality;
      }
      function recursivelyTraverseAtomicPassiveEffects(finishedRoot$jscomp$0, parentFiber, committedLanes$jscomp$0, committedTransitions$jscomp$0, endTime$jscomp$0) {
        if (parentFiber.subtreeFlags & 10256 || 0 !== parentFiber.actualDuration && (null === parentFiber.alternate || parentFiber.alternate.child !== parentFiber.child))
          for (var child = parentFiber.child; null !== child; ) {
            parentFiber = child.sibling;
            var finishedRoot = finishedRoot$jscomp$0, committedLanes = committedLanes$jscomp$0, committedTransitions = committedTransitions$jscomp$0, endTime = null !== parentFiber ? parentFiber.actualStartTime : endTime$jscomp$0, prevDeepEquality = alreadyWarnedForDeepEquality;
            (child.mode & ProfileMode) !== NoMode && 0 < child.actualStartTime && 0 !== (child.flags & 1) && logComponentRender(
              child,
              child.actualStartTime,
              endTime,
              inHydratedSubtree,
              committedLanes
            );
            var flags = child.flags;
            switch (child.tag) {
              case 22:
                recursivelyTraverseAtomicPassiveEffects(
                  finishedRoot,
                  child,
                  committedLanes,
                  committedTransitions,
                  endTime
                );
                flags & 2048 && commitOffscreenPassiveMountEffects(child.alternate, child);
                break;
              case 24:
                recursivelyTraverseAtomicPassiveEffects(
                  finishedRoot,
                  child,
                  committedLanes,
                  committedTransitions,
                  endTime
                );
                flags & 2048 && commitCachePassiveMountEffect(child.alternate, child);
                break;
              default:
                recursivelyTraverseAtomicPassiveEffects(
                  finishedRoot,
                  child,
                  committedLanes,
                  committedTransitions,
                  endTime
                );
            }
            alreadyWarnedForDeepEquality = prevDeepEquality;
            child = parentFiber;
          }
      }
      function recursivelyAccumulateSuspenseyCommit(parentFiber, committedLanes, suspendedState) {
        if (parentFiber.subtreeFlags & suspenseyCommitFlag)
          for (parentFiber = parentFiber.child; null !== parentFiber; )
            accumulateSuspenseyCommitOnFiber(
              parentFiber,
              committedLanes,
              suspendedState
            ), parentFiber = parentFiber.sibling;
      }
      function accumulateSuspenseyCommitOnFiber(fiber, committedLanes, suspendedState) {
        switch (fiber.tag) {
          case 26:
            recursivelyAccumulateSuspenseyCommit(
              fiber,
              committedLanes,
              suspendedState
            );
            fiber.flags & suspenseyCommitFlag && null !== fiber.memoizedState && suspendResource(
              suspendedState,
              currentHoistableRoot,
              fiber.memoizedState,
              fiber.memoizedProps
            );
            break;
          case 5:
            recursivelyAccumulateSuspenseyCommit(
              fiber,
              committedLanes,
              suspendedState
            );
            break;
          case 3:
          case 4:
            var previousHoistableRoot = currentHoistableRoot;
            currentHoistableRoot = getHoistableRoot(
              fiber.stateNode.containerInfo
            );
            recursivelyAccumulateSuspenseyCommit(
              fiber,
              committedLanes,
              suspendedState
            );
            currentHoistableRoot = previousHoistableRoot;
            break;
          case 22:
            null === fiber.memoizedState && (previousHoistableRoot = fiber.alternate, null !== previousHoistableRoot && null !== previousHoistableRoot.memoizedState ? (previousHoistableRoot = suspenseyCommitFlag, suspenseyCommitFlag = 16777216, recursivelyAccumulateSuspenseyCommit(
              fiber,
              committedLanes,
              suspendedState
            ), suspenseyCommitFlag = previousHoistableRoot) : recursivelyAccumulateSuspenseyCommit(
              fiber,
              committedLanes,
              suspendedState
            ));
            break;
          default:
            recursivelyAccumulateSuspenseyCommit(
              fiber,
              committedLanes,
              suspendedState
            );
        }
      }
      function detachAlternateSiblings(parentFiber) {
        var previousFiber = parentFiber.alternate;
        if (null !== previousFiber && (parentFiber = previousFiber.child, null !== parentFiber)) {
          previousFiber.child = null;
          do
            previousFiber = parentFiber.sibling, parentFiber.sibling = null, parentFiber = previousFiber;
          while (null !== parentFiber);
        }
      }
      function recursivelyTraversePassiveUnmountEffects(parentFiber) {
        var deletions = parentFiber.deletions;
        if (0 !== (parentFiber.flags & 16)) {
          if (null !== deletions)
            for (var i = 0; i < deletions.length; i++) {
              var childToDelete = deletions[i], prevEffectStart = pushComponentEffectStart();
              nextEffect = childToDelete;
              commitPassiveUnmountEffectsInsideOfDeletedTree_begin(
                childToDelete,
                parentFiber
              );
              (childToDelete.mode & ProfileMode) !== NoMode && 0 <= componentEffectStartTime && 0 <= componentEffectEndTime && 0.05 < componentEffectEndTime - componentEffectStartTime && logComponentTrigger(
                childToDelete,
                componentEffectStartTime,
                componentEffectEndTime,
                "Unmount"
              );
              popComponentEffectStart(prevEffectStart);
            }
          detachAlternateSiblings(parentFiber);
        }
        if (parentFiber.subtreeFlags & 10256)
          for (parentFiber = parentFiber.child; null !== parentFiber; )
            commitPassiveUnmountOnFiber(parentFiber), parentFiber = parentFiber.sibling;
      }
      function commitPassiveUnmountOnFiber(finishedWork) {
        var prevEffectStart = pushComponentEffectStart(), prevEffectDuration = pushComponentEffectDuration(), prevEffectErrors = pushComponentEffectErrors(), prevEffectDidSpawnUpdate = pushComponentEffectDidSpawnUpdate();
        switch (finishedWork.tag) {
          case 0:
          case 11:
          case 15:
            recursivelyTraversePassiveUnmountEffects(finishedWork);
            finishedWork.flags & 2048 && commitHookPassiveUnmountEffects(
              finishedWork,
              finishedWork.return,
              Passive | HasEffect
            );
            break;
          case 3:
            var prevProfilerEffectDuration = pushNestedEffectDurations();
            recursivelyTraversePassiveUnmountEffects(finishedWork);
            finishedWork.stateNode.passiveEffectDuration += popNestedEffectDurations(prevProfilerEffectDuration);
            break;
          case 12:
            prevProfilerEffectDuration = pushNestedEffectDurations();
            recursivelyTraversePassiveUnmountEffects(finishedWork);
            finishedWork.stateNode.passiveEffectDuration += bubbleNestedEffectDurations(prevProfilerEffectDuration);
            break;
          case 22:
            prevProfilerEffectDuration = finishedWork.stateNode;
            null !== finishedWork.memoizedState && prevProfilerEffectDuration._visibility & OffscreenPassiveEffectsConnected && (null === finishedWork.return || 13 !== finishedWork.return.tag) ? (prevProfilerEffectDuration._visibility &= ~OffscreenPassiveEffectsConnected, recursivelyTraverseDisconnectPassiveEffects(finishedWork), (finishedWork.mode & ProfileMode) !== NoMode && 0 <= componentEffectStartTime && 0 <= componentEffectEndTime && 0.05 < componentEffectEndTime - componentEffectStartTime && logComponentTrigger(
              finishedWork,
              componentEffectStartTime,
              componentEffectEndTime,
              "Disconnect"
            )) : recursivelyTraversePassiveUnmountEffects(finishedWork);
            break;
          default:
            recursivelyTraversePassiveUnmountEffects(finishedWork);
        }
        (finishedWork.mode & ProfileMode) !== NoMode && 0 <= componentEffectStartTime && 0 <= componentEffectEndTime && (componentEffectSpawnedUpdate || 0.05 < componentEffectDuration) && logComponentEffect(
          finishedWork,
          componentEffectStartTime,
          componentEffectEndTime,
          componentEffectDuration,
          componentEffectErrors
        );
        popComponentEffectStart(prevEffectStart);
        popComponentEffectDuration(prevEffectDuration);
        componentEffectSpawnedUpdate = prevEffectDidSpawnUpdate;
        componentEffectErrors = prevEffectErrors;
      }
      function recursivelyTraverseDisconnectPassiveEffects(parentFiber) {
        var deletions = parentFiber.deletions;
        if (0 !== (parentFiber.flags & 16)) {
          if (null !== deletions)
            for (var i = 0; i < deletions.length; i++) {
              var childToDelete = deletions[i], prevEffectStart = pushComponentEffectStart();
              nextEffect = childToDelete;
              commitPassiveUnmountEffectsInsideOfDeletedTree_begin(
                childToDelete,
                parentFiber
              );
              (childToDelete.mode & ProfileMode) !== NoMode && 0 <= componentEffectStartTime && 0 <= componentEffectEndTime && 0.05 < componentEffectEndTime - componentEffectStartTime && logComponentTrigger(
                childToDelete,
                componentEffectStartTime,
                componentEffectEndTime,
                "Unmount"
              );
              popComponentEffectStart(prevEffectStart);
            }
          detachAlternateSiblings(parentFiber);
        }
        for (parentFiber = parentFiber.child; null !== parentFiber; )
          disconnectPassiveEffect(parentFiber), parentFiber = parentFiber.sibling;
      }
      function disconnectPassiveEffect(finishedWork) {
        var prevEffectStart = pushComponentEffectStart(), prevEffectDuration = pushComponentEffectDuration(), prevEffectErrors = pushComponentEffectErrors(), prevEffectDidSpawnUpdate = pushComponentEffectDidSpawnUpdate();
        switch (finishedWork.tag) {
          case 0:
          case 11:
          case 15:
            commitHookPassiveUnmountEffects(
              finishedWork,
              finishedWork.return,
              Passive
            );
            recursivelyTraverseDisconnectPassiveEffects(finishedWork);
            break;
          case 22:
            var instance = finishedWork.stateNode;
            instance._visibility & OffscreenPassiveEffectsConnected && (instance._visibility &= ~OffscreenPassiveEffectsConnected, recursivelyTraverseDisconnectPassiveEffects(finishedWork));
            break;
          default:
            recursivelyTraverseDisconnectPassiveEffects(finishedWork);
        }
        (finishedWork.mode & ProfileMode) !== NoMode && 0 <= componentEffectStartTime && 0 <= componentEffectEndTime && (componentEffectSpawnedUpdate || 0.05 < componentEffectDuration) && logComponentEffect(
          finishedWork,
          componentEffectStartTime,
          componentEffectEndTime,
          componentEffectDuration,
          componentEffectErrors
        );
        popComponentEffectStart(prevEffectStart);
        popComponentEffectDuration(prevEffectDuration);
        componentEffectSpawnedUpdate = prevEffectDidSpawnUpdate;
        componentEffectErrors = prevEffectErrors;
      }
      function commitPassiveUnmountEffectsInsideOfDeletedTree_begin(deletedSubtreeRoot, nearestMountedAncestor$jscomp$0) {
        for (; null !== nextEffect; ) {
          var fiber = nextEffect, current2 = fiber, nearestMountedAncestor = nearestMountedAncestor$jscomp$0, prevEffectStart = pushComponentEffectStart(), prevEffectDuration = pushComponentEffectDuration(), prevEffectErrors = pushComponentEffectErrors(), prevEffectDidSpawnUpdate = pushComponentEffectDidSpawnUpdate();
          switch (current2.tag) {
            case 0:
            case 11:
            case 15:
              commitHookPassiveUnmountEffects(
                current2,
                nearestMountedAncestor,
                Passive
              );
              break;
            case 23:
            case 22:
              null !== current2.memoizedState && null !== current2.memoizedState.cachePool && (nearestMountedAncestor = current2.memoizedState.cachePool.pool, null != nearestMountedAncestor && retainCache(nearestMountedAncestor));
              break;
            case 24:
              releaseCache(current2.memoizedState.cache);
          }
          (current2.mode & ProfileMode) !== NoMode && 0 <= componentEffectStartTime && 0 <= componentEffectEndTime && (componentEffectSpawnedUpdate || 0.05 < componentEffectDuration) && logComponentEffect(
            current2,
            componentEffectStartTime,
            componentEffectEndTime,
            componentEffectDuration,
            componentEffectErrors
          );
          popComponentEffectStart(prevEffectStart);
          popComponentEffectDuration(prevEffectDuration);
          componentEffectSpawnedUpdate = prevEffectDidSpawnUpdate;
          componentEffectErrors = prevEffectErrors;
          current2 = fiber.child;
          if (null !== current2) current2.return = fiber, nextEffect = current2;
          else
            a: for (fiber = deletedSubtreeRoot; null !== nextEffect; ) {
              current2 = nextEffect;
              prevEffectStart = current2.sibling;
              prevEffectDuration = current2.return;
              detachFiberAfterEffects(current2);
              if (current2 === fiber) {
                nextEffect = null;
                break a;
              }
              if (null !== prevEffectStart) {
                prevEffectStart.return = prevEffectDuration;
                nextEffect = prevEffectStart;
                break a;
              }
              nextEffect = prevEffectDuration;
            }
        }
      }
      function onCommitRoot() {
        commitHooks.forEach(function(commitHook) {
          return commitHook();
        });
      }
      function isConcurrentActEnvironment() {
        var isReactActEnvironmentGlobal = "undefined" !== typeof IS_REACT_ACT_ENVIRONMENT ? IS_REACT_ACT_ENVIRONMENT : void 0;
        isReactActEnvironmentGlobal || null === ReactSharedInternals.actQueue || console.error(
          "The current testing environment is not configured to support act(...)"
        );
        return isReactActEnvironmentGlobal;
      }
      function requestUpdateLane(fiber) {
        if ((executionContext & RenderContext) !== NoContext && 0 !== workInProgressRootRenderLanes)
          return workInProgressRootRenderLanes & -workInProgressRootRenderLanes;
        var transition = ReactSharedInternals.T;
        return null !== transition ? (transition._updatedFibers || (transition._updatedFibers = /* @__PURE__ */ new Set()), transition._updatedFibers.add(fiber), requestTransitionLane()) : resolveUpdatePriority();
      }
      function requestDeferredLane() {
        if (0 === workInProgressDeferredLane)
          if (0 === (workInProgressRootRenderLanes & 536870912) || isHydrating) {
            var lane = nextTransitionDeferredLane;
            nextTransitionDeferredLane <<= 1;
            0 === (nextTransitionDeferredLane & 3932160) && (nextTransitionDeferredLane = 262144);
            workInProgressDeferredLane = lane;
          } else workInProgressDeferredLane = 536870912;
        lane = suspenseHandlerStackCursor.current;
        null !== lane && (lane.flags |= 32);
        return workInProgressDeferredLane;
      }
      function scheduleUpdateOnFiber(root2, fiber, lane) {
        isRunningInsertionEffect && console.error("useInsertionEffect must not schedule updates.");
        isFlushingPassiveEffects && (didScheduleUpdateDuringPassiveEffects = true);
        if (root2 === workInProgressRoot && (workInProgressSuspendedReason === SuspendedOnData || workInProgressSuspendedReason === SuspendedOnAction) || null !== root2.cancelPendingCommit)
          prepareFreshStack(root2, 0), markRootSuspended(
            root2,
            workInProgressRootRenderLanes,
            workInProgressDeferredLane,
            false
          );
        markRootUpdated$1(root2, lane);
        if ((executionContext & RenderContext) !== NoContext && root2 === workInProgressRoot) {
          if (isRendering)
            switch (fiber.tag) {
              case 0:
              case 11:
              case 15:
                root2 = workInProgress && getComponentNameFromFiber(workInProgress) || "Unknown";
                didWarnAboutUpdateInRenderForAnotherComponent.has(root2) || (didWarnAboutUpdateInRenderForAnotherComponent.add(root2), fiber = getComponentNameFromFiber(fiber) || "Unknown", console.error(
                  "Cannot update a component (`%s`) while rendering a different component (`%s`). To locate the bad setState() call inside `%s`, follow the stack trace as described in https://react.dev/link/setstate-in-render",
                  fiber,
                  root2,
                  root2
                ));
                break;
              case 1:
                didWarnAboutUpdateInRender || (console.error(
                  "Cannot update during an existing state transition (such as within `render`). Render methods should be a pure function of props and state."
                ), didWarnAboutUpdateInRender = true);
            }
        } else
          isDevToolsPresent && addFiberToLanesMap(root2, fiber, lane), warnIfUpdatesNotWrappedWithActDEV(fiber), root2 === workInProgressRoot && ((executionContext & RenderContext) === NoContext && (workInProgressRootInterleavedUpdatedLanes |= lane), workInProgressRootExitStatus === RootSuspendedWithDelay && markRootSuspended(
            root2,
            workInProgressRootRenderLanes,
            workInProgressDeferredLane,
            false
          )), ensureRootIsScheduled(root2);
      }
      function performWorkOnRoot(root2, lanes, forceSync) {
        if ((executionContext & (RenderContext | CommitContext)) !== NoContext)
          throw Error("Should not already be working.");
        if (0 !== workInProgressRootRenderLanes && null !== workInProgress) {
          var yieldedFiber = workInProgress, yieldEndTime = now$1();
          switch (yieldReason) {
            case SuspendedOnImmediate:
            case SuspendedOnData:
              var startTime = yieldStartTime;
              supportsUserTiming && ((yieldedFiber = yieldedFiber._debugTask) ? yieldedFiber.run(
                console.timeStamp.bind(
                  console,
                  "Suspended",
                  startTime,
                  yieldEndTime,
                  COMPONENTS_TRACK,
                  void 0,
                  "primary-light"
                )
              ) : console.timeStamp(
                "Suspended",
                startTime,
                yieldEndTime,
                COMPONENTS_TRACK,
                void 0,
                "primary-light"
              ));
              break;
            case SuspendedOnAction:
              startTime = yieldStartTime;
              supportsUserTiming && ((yieldedFiber = yieldedFiber._debugTask) ? yieldedFiber.run(
                console.timeStamp.bind(
                  console,
                  "Action",
                  startTime,
                  yieldEndTime,
                  COMPONENTS_TRACK,
                  void 0,
                  "primary-light"
                )
              ) : console.timeStamp(
                "Action",
                startTime,
                yieldEndTime,
                COMPONENTS_TRACK,
                void 0,
                "primary-light"
              ));
              break;
            default:
              supportsUserTiming && (yieldedFiber = yieldEndTime - yieldStartTime, 3 > yieldedFiber || console.timeStamp(
                "Blocked",
                yieldStartTime,
                yieldEndTime,
                COMPONENTS_TRACK,
                void 0,
                5 > yieldedFiber ? "primary-light" : 10 > yieldedFiber ? "primary" : 100 > yieldedFiber ? "primary-dark" : "error"
              ));
          }
        }
        startTime = (forceSync = !forceSync && 0 === (lanes & 127) && 0 === (lanes & root2.expiredLanes) || checkIfRootIsPrerendering(root2, lanes)) ? renderRootConcurrent(root2, lanes) : renderRootSync(root2, lanes, true);
        var renderWasConcurrent = forceSync;
        do {
          if (startTime === RootInProgress) {
            workInProgressRootIsPrerendering && !forceSync && markRootSuspended(root2, lanes, 0, false);
            lanes = workInProgressSuspendedReason;
            yieldStartTime = now();
            yieldReason = lanes;
            break;
          } else {
            yieldedFiber = now$1();
            yieldEndTime = root2.current.alternate;
            if (renderWasConcurrent && !isRenderConsistentWithExternalStores(yieldEndTime)) {
              setCurrentTrackFromLanes(lanes);
              yieldEndTime = renderStartTime;
              startTime = yieldedFiber;
              !supportsUserTiming || startTime <= yieldEndTime || (workInProgressUpdateTask ? workInProgressUpdateTask.run(
                console.timeStamp.bind(
                  console,
                  "Teared Render",
                  yieldEndTime,
                  startTime,
                  currentTrack,
                  LANES_TRACK_GROUP,
                  "error"
                )
              ) : console.timeStamp(
                "Teared Render",
                yieldEndTime,
                startTime,
                currentTrack,
                LANES_TRACK_GROUP,
                "error"
              ));
              finalizeRender(lanes, yieldedFiber);
              startTime = renderRootSync(root2, lanes, false);
              renderWasConcurrent = false;
              continue;
            }
            if (startTime === RootErrored) {
              renderWasConcurrent = lanes;
              if (root2.errorRecoveryDisabledLanes & renderWasConcurrent)
                var errorRetryLanes = 0;
              else
                errorRetryLanes = root2.pendingLanes & -536870913, errorRetryLanes = 0 !== errorRetryLanes ? errorRetryLanes : errorRetryLanes & 536870912 ? 536870912 : 0;
              if (0 !== errorRetryLanes) {
                setCurrentTrackFromLanes(lanes);
                logErroredRenderPhase(
                  renderStartTime,
                  yieldedFiber,
                  lanes,
                  workInProgressUpdateTask
                );
                finalizeRender(lanes, yieldedFiber);
                lanes = errorRetryLanes;
                a: {
                  yieldedFiber = root2;
                  startTime = renderWasConcurrent;
                  renderWasConcurrent = workInProgressRootConcurrentErrors;
                  var wasRootDehydrated = yieldedFiber.current.memoizedState.isDehydrated;
                  wasRootDehydrated && (prepareFreshStack(yieldedFiber, errorRetryLanes).flags |= 256);
                  errorRetryLanes = renderRootSync(
                    yieldedFiber,
                    errorRetryLanes,
                    false
                  );
                  if (errorRetryLanes !== RootErrored) {
                    if (workInProgressRootDidAttachPingListener && !wasRootDehydrated) {
                      yieldedFiber.errorRecoveryDisabledLanes |= startTime;
                      workInProgressRootInterleavedUpdatedLanes |= startTime;
                      startTime = RootSuspendedWithDelay;
                      break a;
                    }
                    yieldedFiber = workInProgressRootRecoverableErrors;
                    workInProgressRootRecoverableErrors = renderWasConcurrent;
                    null !== yieldedFiber && (null === workInProgressRootRecoverableErrors ? workInProgressRootRecoverableErrors = yieldedFiber : workInProgressRootRecoverableErrors.push.apply(
                      workInProgressRootRecoverableErrors,
                      yieldedFiber
                    ));
                  }
                  startTime = errorRetryLanes;
                }
                renderWasConcurrent = false;
                if (startTime !== RootErrored) continue;
                else yieldedFiber = now$1();
              }
            }
            if (startTime === RootFatalErrored) {
              setCurrentTrackFromLanes(lanes);
              logErroredRenderPhase(
                renderStartTime,
                yieldedFiber,
                lanes,
                workInProgressUpdateTask
              );
              finalizeRender(lanes, yieldedFiber);
              prepareFreshStack(root2, 0);
              markRootSuspended(root2, lanes, 0, true);
              break;
            }
            a: {
              forceSync = root2;
              switch (startTime) {
                case RootInProgress:
                case RootFatalErrored:
                  throw Error("Root did not complete. This is a bug in React.");
                case RootSuspendedWithDelay:
                  if ((lanes & 4194048) !== lanes) break;
                case RootSuspendedAtTheShell:
                  setCurrentTrackFromLanes(lanes);
                  logSuspendedRenderPhase(
                    renderStartTime,
                    yieldedFiber,
                    lanes,
                    workInProgressUpdateTask
                  );
                  finalizeRender(lanes, yieldedFiber);
                  yieldEndTime = lanes;
                  0 !== (yieldEndTime & 127) ? blockingSuspendedTime = yieldedFiber : 0 !== (yieldEndTime & 4194048) && (transitionSuspendedTime = yieldedFiber);
                  markRootSuspended(
                    forceSync,
                    lanes,
                    workInProgressDeferredLane,
                    !workInProgressRootDidSkipSuspendedSiblings
                  );
                  break a;
                case RootErrored:
                  workInProgressRootRecoverableErrors = null;
                  break;
                case RootSuspended:
                case RootCompleted:
                  break;
                default:
                  throw Error("Unknown root exit status.");
              }
              if (null !== ReactSharedInternals.actQueue)
                commitRoot(
                  forceSync,
                  yieldEndTime,
                  lanes,
                  workInProgressRootRecoverableErrors,
                  workInProgressTransitions,
                  workInProgressRootDidIncludeRecursiveRenderUpdate,
                  workInProgressDeferredLane,
                  workInProgressRootInterleavedUpdatedLanes,
                  workInProgressSuspendedRetryLanes,
                  startTime,
                  null,
                  null,
                  renderStartTime,
                  yieldedFiber
                );
              else {
                if ((lanes & 62914560) === lanes && (renderWasConcurrent = globalMostRecentFallbackTime + FALLBACK_THROTTLE_MS - now$1(), 10 < renderWasConcurrent)) {
                  markRootSuspended(
                    forceSync,
                    lanes,
                    workInProgressDeferredLane,
                    !workInProgressRootDidSkipSuspendedSiblings
                  );
                  if (0 !== getNextLanes(forceSync, 0, true)) break a;
                  pendingEffectsLanes = lanes;
                  forceSync.timeoutHandle = scheduleTimeout(
                    commitRootWhenReady.bind(
                      null,
                      forceSync,
                      yieldEndTime,
                      workInProgressRootRecoverableErrors,
                      workInProgressTransitions,
                      workInProgressRootDidIncludeRecursiveRenderUpdate,
                      lanes,
                      workInProgressDeferredLane,
                      workInProgressRootInterleavedUpdatedLanes,
                      workInProgressSuspendedRetryLanes,
                      workInProgressRootDidSkipSuspendedSiblings,
                      startTime,
                      "Throttled",
                      renderStartTime,
                      yieldedFiber
                    ),
                    renderWasConcurrent
                  );
                  break a;
                }
                commitRootWhenReady(
                  forceSync,
                  yieldEndTime,
                  workInProgressRootRecoverableErrors,
                  workInProgressTransitions,
                  workInProgressRootDidIncludeRecursiveRenderUpdate,
                  lanes,
                  workInProgressDeferredLane,
                  workInProgressRootInterleavedUpdatedLanes,
                  workInProgressSuspendedRetryLanes,
                  workInProgressRootDidSkipSuspendedSiblings,
                  startTime,
                  null,
                  renderStartTime,
                  yieldedFiber
                );
              }
            }
          }
          break;
        } while (1);
        ensureRootIsScheduled(root2);
      }
      function commitRootWhenReady(root2, finishedWork, recoverableErrors, transitions, didIncludeRenderPhaseUpdate, lanes, spawnedLane, updatedLanes, suspendedRetryLanes, didSkipSuspendedSiblings, exitStatus, suspendedCommitReason, completedRenderStartTime, completedRenderEndTime) {
        root2.timeoutHandle = noTimeout;
        var subtreeFlags = finishedWork.subtreeFlags, suspendedState = null;
        if (subtreeFlags & 8192 || 16785408 === (subtreeFlags & 16785408)) {
          if (suspendedState = {
            stylesheets: null,
            count: 0,
            imgCount: 0,
            imgBytes: 0,
            suspenseyImages: [],
            waitingForImages: true,
            waitingForViewTransition: false,
            unsuspend: noop$1
          }, accumulateSuspenseyCommitOnFiber(finishedWork, lanes, suspendedState), subtreeFlags = (lanes & 62914560) === lanes ? globalMostRecentFallbackTime - now$1() : (lanes & 4194048) === lanes ? globalMostRecentTransitionTime - now$1() : 0, subtreeFlags = waitForCommitToBeReady(suspendedState, subtreeFlags), null !== subtreeFlags) {
            pendingEffectsLanes = lanes;
            root2.cancelPendingCommit = subtreeFlags(
              commitRoot.bind(
                null,
                root2,
                finishedWork,
                lanes,
                recoverableErrors,
                transitions,
                didIncludeRenderPhaseUpdate,
                spawnedLane,
                updatedLanes,
                suspendedRetryLanes,
                exitStatus,
                suspendedState,
                suspendedState.waitingForViewTransition ? "Waiting for the previous Animation" : 0 < suspendedState.count ? 0 < suspendedState.imgCount ? "Suspended on CSS and Images" : "Suspended on CSS" : 1 === suspendedState.imgCount ? "Suspended on an Image" : 0 < suspendedState.imgCount ? "Suspended on Images" : null,
                completedRenderStartTime,
                completedRenderEndTime
              )
            );
            markRootSuspended(
              root2,
              lanes,
              spawnedLane,
              !didSkipSuspendedSiblings
            );
            return;
          }
        }
        commitRoot(
          root2,
          finishedWork,
          lanes,
          recoverableErrors,
          transitions,
          didIncludeRenderPhaseUpdate,
          spawnedLane,
          updatedLanes,
          suspendedRetryLanes,
          exitStatus,
          suspendedState,
          suspendedCommitReason,
          completedRenderStartTime,
          completedRenderEndTime
        );
      }
      function isRenderConsistentWithExternalStores(finishedWork) {
        for (var node = finishedWork; ; ) {
          var tag = node.tag;
          if ((0 === tag || 11 === tag || 15 === tag) && node.flags & 16384 && (tag = node.updateQueue, null !== tag && (tag = tag.stores, null !== tag)))
            for (var i = 0; i < tag.length; i++) {
              var check = tag[i], getSnapshot = check.getSnapshot;
              check = check.value;
              try {
                if (!objectIs(getSnapshot(), check)) return false;
              } catch (error) {
                return false;
              }
            }
          tag = node.child;
          if (node.subtreeFlags & 16384 && null !== tag)
            tag.return = node, node = tag;
          else {
            if (node === finishedWork) break;
            for (; null === node.sibling; ) {
              if (null === node.return || node.return === finishedWork) return true;
              node = node.return;
            }
            node.sibling.return = node.return;
            node = node.sibling;
          }
        }
        return true;
      }
      function markRootSuspended(root2, suspendedLanes, spawnedLane, didAttemptEntireTree) {
        suspendedLanes &= ~workInProgressRootPingedLanes;
        suspendedLanes &= ~workInProgressRootInterleavedUpdatedLanes;
        root2.suspendedLanes |= suspendedLanes;
        root2.pingedLanes &= ~suspendedLanes;
        didAttemptEntireTree && (root2.warmLanes |= suspendedLanes);
        didAttemptEntireTree = root2.expirationTimes;
        for (var lanes = suspendedLanes; 0 < lanes; ) {
          var index = 31 - clz32(lanes), lane = 1 << index;
          didAttemptEntireTree[index] = -1;
          lanes &= ~lane;
        }
        0 !== spawnedLane && markSpawnedDeferredLane(root2, spawnedLane, suspendedLanes);
      }
      function flushSyncWork$1() {
        return (executionContext & (RenderContext | CommitContext)) === NoContext ? (flushSyncWorkAcrossRoots_impl(0, false), false) : true;
      }
      function resetWorkInProgressStack() {
        if (null !== workInProgress) {
          if (workInProgressSuspendedReason === NotSuspended)
            var interruptedWork = workInProgress.return;
          else
            interruptedWork = workInProgress, resetContextDependencies(), resetHooksOnUnwind(interruptedWork), thenableState$1 = null, thenableIndexCounter$1 = 0, interruptedWork = workInProgress;
          for (; null !== interruptedWork; )
            unwindInterruptedWork(interruptedWork.alternate, interruptedWork), interruptedWork = interruptedWork.return;
          workInProgress = null;
        }
      }
      function finalizeRender(lanes, finalizationTime) {
        0 !== (lanes & 127) && (blockingClampTime = finalizationTime);
        0 !== (lanes & 4194048) && (transitionClampTime = finalizationTime);
        0 !== (lanes & 62914560) && (retryClampTime = finalizationTime);
        0 !== (lanes & 2080374784) && (idleClampTime = finalizationTime);
      }
      function prepareFreshStack(root2, lanes) {
        supportsUserTiming && (console.timeStamp(
          "Blocking Track",
          3e-3,
          3e-3,
          "Blocking",
          LANES_TRACK_GROUP,
          "primary-light"
        ), console.timeStamp(
          "Transition Track",
          3e-3,
          3e-3,
          "Transition",
          LANES_TRACK_GROUP,
          "primary-light"
        ), console.timeStamp(
          "Suspense Track",
          3e-3,
          3e-3,
          "Suspense",
          LANES_TRACK_GROUP,
          "primary-light"
        ), console.timeStamp(
          "Idle Track",
          3e-3,
          3e-3,
          "Idle",
          LANES_TRACK_GROUP,
          "primary-light"
        ));
        var previousRenderStartTime = renderStartTime;
        renderStartTime = now();
        if (0 !== workInProgressRootRenderLanes && 0 < previousRenderStartTime) {
          setCurrentTrackFromLanes(workInProgressRootRenderLanes);
          if (workInProgressRootExitStatus === RootSuspended || workInProgressRootExitStatus === RootSuspendedWithDelay)
            logSuspendedRenderPhase(
              previousRenderStartTime,
              renderStartTime,
              lanes,
              workInProgressUpdateTask
            );
          else {
            var endTime = renderStartTime, debugTask = workInProgressUpdateTask;
            if (supportsUserTiming && !(endTime <= previousRenderStartTime)) {
              var color = (lanes & 738197653) === lanes ? "tertiary-dark" : "primary-dark", label = (lanes & 536870912) === lanes ? "Prewarm" : (lanes & 201326741) === lanes ? "Interrupted Hydration" : "Interrupted Render";
              debugTask ? debugTask.run(
                console.timeStamp.bind(
                  console,
                  label,
                  previousRenderStartTime,
                  endTime,
                  currentTrack,
                  LANES_TRACK_GROUP,
                  color
                )
              ) : console.timeStamp(
                label,
                previousRenderStartTime,
                endTime,
                currentTrack,
                LANES_TRACK_GROUP,
                color
              );
            }
          }
          finalizeRender(workInProgressRootRenderLanes, renderStartTime);
        }
        previousRenderStartTime = workInProgressUpdateTask;
        workInProgressUpdateTask = null;
        if (0 !== (lanes & 127)) {
          workInProgressUpdateTask = blockingUpdateTask;
          debugTask = 0 <= blockingUpdateTime && blockingUpdateTime < blockingClampTime ? blockingClampTime : blockingUpdateTime;
          endTime = 0 <= blockingEventTime && blockingEventTime < blockingClampTime ? blockingClampTime : blockingEventTime;
          color = 0 <= endTime ? endTime : 0 <= debugTask ? debugTask : renderStartTime;
          0 <= blockingSuspendedTime ? (setCurrentTrackFromLanes(2), logSuspendedWithDelayPhase(
            blockingSuspendedTime,
            color,
            lanes,
            previousRenderStartTime
          )) : 0 !== (animatingLanes & 127) && (setCurrentTrackFromLanes(2), logAnimatingPhase(blockingClampTime, color, animatingTask));
          previousRenderStartTime = debugTask;
          var eventTime = endTime, eventType = blockingEventType, eventIsRepeat = 0 < blockingEventRepeatTime, isSpawnedUpdate = blockingUpdateType === SPAWNED_UPDATE, isPingedUpdate = blockingUpdateType === PINGED_UPDATE;
          debugTask = renderStartTime;
          endTime = blockingUpdateTask;
          color = blockingUpdateMethodName;
          label = blockingUpdateComponentName;
          if (supportsUserTiming) {
            currentTrack = "Blocking";
            0 < previousRenderStartTime ? previousRenderStartTime > debugTask && (previousRenderStartTime = debugTask) : previousRenderStartTime = debugTask;
            0 < eventTime ? eventTime > previousRenderStartTime && (eventTime = previousRenderStartTime) : eventTime = previousRenderStartTime;
            if (null !== eventType && previousRenderStartTime > eventTime) {
              var color$jscomp$0 = eventIsRepeat ? "secondary-light" : "warning";
              endTime ? endTime.run(
                console.timeStamp.bind(
                  console,
                  eventIsRepeat ? "Consecutive" : "Event: " + eventType,
                  eventTime,
                  previousRenderStartTime,
                  currentTrack,
                  LANES_TRACK_GROUP,
                  color$jscomp$0
                )
              ) : console.timeStamp(
                eventIsRepeat ? "Consecutive" : "Event: " + eventType,
                eventTime,
                previousRenderStartTime,
                currentTrack,
                LANES_TRACK_GROUP,
                color$jscomp$0
              );
            }
            debugTask > previousRenderStartTime && (eventTime = isSpawnedUpdate ? "error" : (lanes & 738197653) === lanes ? "tertiary-light" : "primary-light", isSpawnedUpdate = isPingedUpdate ? "Promise Resolved" : isSpawnedUpdate ? "Cascading Update" : 5 < debugTask - previousRenderStartTime ? "Update Blocked" : "Update", isPingedUpdate = [], null != label && isPingedUpdate.push(["Component name", label]), null != color && isPingedUpdate.push(["Method name", color]), previousRenderStartTime = {
              start: previousRenderStartTime,
              end: debugTask,
              detail: {
                devtools: {
                  properties: isPingedUpdate,
                  track: currentTrack,
                  trackGroup: LANES_TRACK_GROUP,
                  color: eventTime
                }
              }
            }, endTime ? endTime.run(
              performance.measure.bind(
                performance,
                isSpawnedUpdate,
                previousRenderStartTime
              )
            ) : performance.measure(isSpawnedUpdate, previousRenderStartTime));
          }
          blockingUpdateTime = -1.1;
          blockingUpdateType = 0;
          blockingUpdateComponentName = blockingUpdateMethodName = null;
          blockingSuspendedTime = -1.1;
          blockingEventRepeatTime = blockingEventTime;
          blockingEventTime = -1.1;
          blockingClampTime = now();
        }
        0 !== (lanes & 4194048) && (workInProgressUpdateTask = transitionUpdateTask, debugTask = 0 <= transitionStartTime && transitionStartTime < transitionClampTime ? transitionClampTime : transitionStartTime, previousRenderStartTime = 0 <= transitionUpdateTime && transitionUpdateTime < transitionClampTime ? transitionClampTime : transitionUpdateTime, endTime = 0 <= transitionEventTime && transitionEventTime < transitionClampTime ? transitionClampTime : transitionEventTime, color = 0 <= endTime ? endTime : 0 <= previousRenderStartTime ? previousRenderStartTime : renderStartTime, 0 <= transitionSuspendedTime ? (setCurrentTrackFromLanes(256), logSuspendedWithDelayPhase(
          transitionSuspendedTime,
          color,
          lanes,
          workInProgressUpdateTask
        )) : 0 !== (animatingLanes & 4194048) && (setCurrentTrackFromLanes(256), logAnimatingPhase(transitionClampTime, color, animatingTask)), isPingedUpdate = endTime, eventTime = transitionEventType, eventType = 0 < transitionEventRepeatTime, eventIsRepeat = transitionUpdateType === PINGED_UPDATE, color = renderStartTime, endTime = transitionUpdateTask, label = transitionUpdateMethodName, isSpawnedUpdate = transitionUpdateComponentName, supportsUserTiming && (currentTrack = "Transition", 0 < previousRenderStartTime ? previousRenderStartTime > color && (previousRenderStartTime = color) : previousRenderStartTime = color, 0 < debugTask ? debugTask > previousRenderStartTime && (debugTask = previousRenderStartTime) : debugTask = previousRenderStartTime, 0 < isPingedUpdate ? isPingedUpdate > debugTask && (isPingedUpdate = debugTask) : isPingedUpdate = debugTask, debugTask > isPingedUpdate && null !== eventTime && (color$jscomp$0 = eventType ? "secondary-light" : "warning", endTime ? endTime.run(
          console.timeStamp.bind(
            console,
            eventType ? "Consecutive" : "Event: " + eventTime,
            isPingedUpdate,
            debugTask,
            currentTrack,
            LANES_TRACK_GROUP,
            color$jscomp$0
          )
        ) : console.timeStamp(
          eventType ? "Consecutive" : "Event: " + eventTime,
          isPingedUpdate,
          debugTask,
          currentTrack,
          LANES_TRACK_GROUP,
          color$jscomp$0
        )), previousRenderStartTime > debugTask && (endTime ? endTime.run(
          console.timeStamp.bind(
            console,
            "Action",
            debugTask,
            previousRenderStartTime,
            currentTrack,
            LANES_TRACK_GROUP,
            "primary-dark"
          )
        ) : console.timeStamp(
          "Action",
          debugTask,
          previousRenderStartTime,
          currentTrack,
          LANES_TRACK_GROUP,
          "primary-dark"
        )), color > previousRenderStartTime && (debugTask = eventIsRepeat ? "Promise Resolved" : 5 < color - previousRenderStartTime ? "Update Blocked" : "Update", isPingedUpdate = [], null != isSpawnedUpdate && isPingedUpdate.push(["Component name", isSpawnedUpdate]), null != label && isPingedUpdate.push(["Method name", label]), previousRenderStartTime = {
          start: previousRenderStartTime,
          end: color,
          detail: {
            devtools: {
              properties: isPingedUpdate,
              track: currentTrack,
              trackGroup: LANES_TRACK_GROUP,
              color: "primary-light"
            }
          }
        }, endTime ? endTime.run(
          performance.measure.bind(
            performance,
            debugTask,
            previousRenderStartTime
          )
        ) : performance.measure(debugTask, previousRenderStartTime))), transitionUpdateTime = transitionStartTime = -1.1, transitionUpdateType = 0, transitionSuspendedTime = -1.1, transitionEventRepeatTime = transitionEventTime, transitionEventTime = -1.1, transitionClampTime = now());
        0 !== (lanes & 62914560) && 0 !== (animatingLanes & 62914560) && (setCurrentTrackFromLanes(4194304), logAnimatingPhase(retryClampTime, renderStartTime, animatingTask));
        0 !== (lanes & 2080374784) && 0 !== (animatingLanes & 2080374784) && (setCurrentTrackFromLanes(268435456), logAnimatingPhase(idleClampTime, renderStartTime, animatingTask));
        previousRenderStartTime = root2.timeoutHandle;
        previousRenderStartTime !== noTimeout && (root2.timeoutHandle = noTimeout, cancelTimeout(previousRenderStartTime));
        previousRenderStartTime = root2.cancelPendingCommit;
        null !== previousRenderStartTime && (root2.cancelPendingCommit = null, previousRenderStartTime());
        pendingEffectsLanes = 0;
        resetWorkInProgressStack();
        workInProgressRoot = root2;
        workInProgress = previousRenderStartTime = createWorkInProgress(
          root2.current,
          null
        );
        workInProgressRootRenderLanes = lanes;
        workInProgressSuspendedReason = NotSuspended;
        workInProgressThrownValue = null;
        workInProgressRootDidSkipSuspendedSiblings = false;
        workInProgressRootIsPrerendering = checkIfRootIsPrerendering(root2, lanes);
        workInProgressRootDidAttachPingListener = false;
        workInProgressRootExitStatus = RootInProgress;
        workInProgressSuspendedRetryLanes = workInProgressDeferredLane = workInProgressRootPingedLanes = workInProgressRootInterleavedUpdatedLanes = workInProgressRootSkippedLanes = 0;
        workInProgressRootRecoverableErrors = workInProgressRootConcurrentErrors = null;
        workInProgressRootDidIncludeRecursiveRenderUpdate = false;
        0 !== (lanes & 8) && (lanes |= lanes & 32);
        endTime = root2.entangledLanes;
        if (0 !== endTime)
          for (root2 = root2.entanglements, endTime &= lanes; 0 < endTime; )
            debugTask = 31 - clz32(endTime), color = 1 << debugTask, lanes |= root2[debugTask], endTime &= ~color;
        entangledRenderLanes = lanes;
        finishQueueingConcurrentUpdates();
        root2 = getCurrentTime();
        1e3 < root2 - lastResetTime && (ReactSharedInternals.recentlyCreatedOwnerStacks = 0, lastResetTime = root2);
        ReactStrictModeWarnings.discardPendingWarnings();
        return previousRenderStartTime;
      }
      function handleThrow(root2, thrownValue) {
        currentlyRenderingFiber = null;
        ReactSharedInternals.H = ContextOnlyDispatcher;
        ReactSharedInternals.getCurrentStack = null;
        isRendering = false;
        current = null;
        thrownValue === SuspenseException || thrownValue === SuspenseActionException ? (thrownValue = getSuspendedThenable(), workInProgressSuspendedReason = SuspendedOnImmediate) : thrownValue === SuspenseyCommitException ? (thrownValue = getSuspendedThenable(), workInProgressSuspendedReason = SuspendedOnInstance) : workInProgressSuspendedReason = thrownValue === SelectiveHydrationException ? SuspendedOnHydration : null !== thrownValue && "object" === typeof thrownValue && "function" === typeof thrownValue.then ? SuspendedOnDeprecatedThrowPromise : SuspendedOnError;
        workInProgressThrownValue = thrownValue;
        var erroredWork = workInProgress;
        null === erroredWork ? (workInProgressRootExitStatus = RootFatalErrored, logUncaughtError(
          root2,
          createCapturedValueAtFiber(thrownValue, root2.current)
        )) : erroredWork.mode & ProfileMode && stopProfilerTimerIfRunningAndRecordDuration(erroredWork);
      }
      function shouldRemainOnPreviousScreen() {
        var handler = suspenseHandlerStackCursor.current;
        return null === handler ? true : (workInProgressRootRenderLanes & 4194048) === workInProgressRootRenderLanes ? null === shellBoundary ? true : false : (workInProgressRootRenderLanes & 62914560) === workInProgressRootRenderLanes || 0 !== (workInProgressRootRenderLanes & 536870912) ? handler === shellBoundary : false;
      }
      function pushDispatcher() {
        var prevDispatcher = ReactSharedInternals.H;
        ReactSharedInternals.H = ContextOnlyDispatcher;
        return null === prevDispatcher ? ContextOnlyDispatcher : prevDispatcher;
      }
      function pushAsyncDispatcher() {
        var prevAsyncDispatcher = ReactSharedInternals.A;
        ReactSharedInternals.A = DefaultAsyncDispatcher;
        return prevAsyncDispatcher;
      }
      function markRenderDerivedCause(fiber) {
        null === workInProgressUpdateTask && (workInProgressUpdateTask = null == fiber._debugTask ? null : fiber._debugTask);
      }
      function renderDidSuspendDelayIfPossible() {
        workInProgressRootExitStatus = RootSuspendedWithDelay;
        workInProgressRootDidSkipSuspendedSiblings || (workInProgressRootRenderLanes & 4194048) !== workInProgressRootRenderLanes && null !== suspenseHandlerStackCursor.current || (workInProgressRootIsPrerendering = true);
        0 === (workInProgressRootSkippedLanes & 134217727) && 0 === (workInProgressRootInterleavedUpdatedLanes & 134217727) || null === workInProgressRoot || markRootSuspended(
          workInProgressRoot,
          workInProgressRootRenderLanes,
          workInProgressDeferredLane,
          false
        );
      }
      function renderRootSync(root2, lanes, shouldYieldForPrerendering) {
        var prevExecutionContext = executionContext;
        executionContext |= RenderContext;
        var prevDispatcher = pushDispatcher(), prevAsyncDispatcher = pushAsyncDispatcher();
        if (workInProgressRoot !== root2 || workInProgressRootRenderLanes !== lanes) {
          if (isDevToolsPresent) {
            var memoizedUpdaters = root2.memoizedUpdaters;
            0 < memoizedUpdaters.size && (restorePendingUpdaters(root2, workInProgressRootRenderLanes), memoizedUpdaters.clear());
            movePendingFibersToMemoized(root2, lanes);
          }
          workInProgressTransitions = null;
          prepareFreshStack(root2, lanes);
        }
        lanes = false;
        memoizedUpdaters = workInProgressRootExitStatus;
        a: do
          try {
            if (workInProgressSuspendedReason !== NotSuspended && null !== workInProgress) {
              var unitOfWork = workInProgress, thrownValue = workInProgressThrownValue;
              switch (workInProgressSuspendedReason) {
                case SuspendedOnHydration:
                  resetWorkInProgressStack();
                  memoizedUpdaters = RootSuspendedAtTheShell;
                  break a;
                case SuspendedOnImmediate:
                case SuspendedOnData:
                case SuspendedOnAction:
                case SuspendedOnDeprecatedThrowPromise:
                  null === suspenseHandlerStackCursor.current && (lanes = true);
                  var reason = workInProgressSuspendedReason;
                  workInProgressSuspendedReason = NotSuspended;
                  workInProgressThrownValue = null;
                  throwAndUnwindWorkLoop(root2, unitOfWork, thrownValue, reason);
                  if (shouldYieldForPrerendering && workInProgressRootIsPrerendering) {
                    memoizedUpdaters = RootInProgress;
                    break a;
                  }
                  break;
                default:
                  reason = workInProgressSuspendedReason, workInProgressSuspendedReason = NotSuspended, workInProgressThrownValue = null, throwAndUnwindWorkLoop(root2, unitOfWork, thrownValue, reason);
              }
            }
            workLoopSync();
            memoizedUpdaters = workInProgressRootExitStatus;
            break;
          } catch (thrownValue$8) {
            handleThrow(root2, thrownValue$8);
          }
        while (1);
        lanes && root2.shellSuspendCounter++;
        resetContextDependencies();
        executionContext = prevExecutionContext;
        ReactSharedInternals.H = prevDispatcher;
        ReactSharedInternals.A = prevAsyncDispatcher;
        null === workInProgress && (workInProgressRoot = null, workInProgressRootRenderLanes = 0, finishQueueingConcurrentUpdates());
        return memoizedUpdaters;
      }
      function workLoopSync() {
        for (; null !== workInProgress; ) performUnitOfWork(workInProgress);
      }
      function renderRootConcurrent(root2, lanes) {
        var prevExecutionContext = executionContext;
        executionContext |= RenderContext;
        var prevDispatcher = pushDispatcher(), prevAsyncDispatcher = pushAsyncDispatcher();
        if (workInProgressRoot !== root2 || workInProgressRootRenderLanes !== lanes) {
          if (isDevToolsPresent) {
            var memoizedUpdaters = root2.memoizedUpdaters;
            0 < memoizedUpdaters.size && (restorePendingUpdaters(root2, workInProgressRootRenderLanes), memoizedUpdaters.clear());
            movePendingFibersToMemoized(root2, lanes);
          }
          workInProgressTransitions = null;
          workInProgressRootRenderTargetTime = now$1() + RENDER_TIMEOUT_MS;
          prepareFreshStack(root2, lanes);
        } else
          workInProgressRootIsPrerendering = checkIfRootIsPrerendering(
            root2,
            lanes
          );
        a: do
          try {
            if (workInProgressSuspendedReason !== NotSuspended && null !== workInProgress)
              b: switch (lanes = workInProgress, memoizedUpdaters = workInProgressThrownValue, workInProgressSuspendedReason) {
                case SuspendedOnError:
                  workInProgressSuspendedReason = NotSuspended;
                  workInProgressThrownValue = null;
                  throwAndUnwindWorkLoop(
                    root2,
                    lanes,
                    memoizedUpdaters,
                    SuspendedOnError
                  );
                  break;
                case SuspendedOnData:
                case SuspendedOnAction:
                  if (isThenableResolved(memoizedUpdaters)) {
                    workInProgressSuspendedReason = NotSuspended;
                    workInProgressThrownValue = null;
                    replaySuspendedUnitOfWork(lanes);
                    break;
                  }
                  lanes = function() {
                    workInProgressSuspendedReason !== SuspendedOnData && workInProgressSuspendedReason !== SuspendedOnAction || workInProgressRoot !== root2 || (workInProgressSuspendedReason = SuspendedAndReadyToContinue);
                    ensureRootIsScheduled(root2);
                  };
                  memoizedUpdaters.then(lanes, lanes);
                  break a;
                case SuspendedOnImmediate:
                  workInProgressSuspendedReason = SuspendedAndReadyToContinue;
                  break a;
                case SuspendedOnInstance:
                  workInProgressSuspendedReason = SuspendedOnInstanceAndReadyToContinue;
                  break a;
                case SuspendedAndReadyToContinue:
                  isThenableResolved(memoizedUpdaters) ? (workInProgressSuspendedReason = NotSuspended, workInProgressThrownValue = null, replaySuspendedUnitOfWork(lanes)) : (workInProgressSuspendedReason = NotSuspended, workInProgressThrownValue = null, throwAndUnwindWorkLoop(
                    root2,
                    lanes,
                    memoizedUpdaters,
                    SuspendedAndReadyToContinue
                  ));
                  break;
                case SuspendedOnInstanceAndReadyToContinue:
                  var resource = null;
                  switch (workInProgress.tag) {
                    case 26:
                      resource = workInProgress.memoizedState;
                    case 5:
                    case 27:
                      var hostFiber = workInProgress;
                      if (resource ? preloadResource(resource) : hostFiber.stateNode.complete) {
                        workInProgressSuspendedReason = NotSuspended;
                        workInProgressThrownValue = null;
                        var sibling = hostFiber.sibling;
                        if (null !== sibling) workInProgress = sibling;
                        else {
                          var returnFiber = hostFiber.return;
                          null !== returnFiber ? (workInProgress = returnFiber, completeUnitOfWork(returnFiber)) : workInProgress = null;
                        }
                        break b;
                      }
                      break;
                    default:
                      console.error(
                        "Unexpected type of fiber triggered a suspensey commit. This is a bug in React."
                      );
                  }
                  workInProgressSuspendedReason = NotSuspended;
                  workInProgressThrownValue = null;
                  throwAndUnwindWorkLoop(
                    root2,
                    lanes,
                    memoizedUpdaters,
                    SuspendedOnInstanceAndReadyToContinue
                  );
                  break;
                case SuspendedOnDeprecatedThrowPromise:
                  workInProgressSuspendedReason = NotSuspended;
                  workInProgressThrownValue = null;
                  throwAndUnwindWorkLoop(
                    root2,
                    lanes,
                    memoizedUpdaters,
                    SuspendedOnDeprecatedThrowPromise
                  );
                  break;
                case SuspendedOnHydration:
                  resetWorkInProgressStack();
                  workInProgressRootExitStatus = RootSuspendedAtTheShell;
                  break a;
                default:
                  throw Error(
                    "Unexpected SuspendedReason. This is a bug in React."
                  );
              }
            null !== ReactSharedInternals.actQueue ? workLoopSync() : workLoopConcurrentByScheduler();
            break;
          } catch (thrownValue$9) {
            handleThrow(root2, thrownValue$9);
          }
        while (1);
        resetContextDependencies();
        ReactSharedInternals.H = prevDispatcher;
        ReactSharedInternals.A = prevAsyncDispatcher;
        executionContext = prevExecutionContext;
        if (null !== workInProgress) return RootInProgress;
        workInProgressRoot = null;
        workInProgressRootRenderLanes = 0;
        finishQueueingConcurrentUpdates();
        return workInProgressRootExitStatus;
      }
      function workLoopConcurrentByScheduler() {
        for (; null !== workInProgress && !shouldYield(); )
          performUnitOfWork(workInProgress);
      }
      function performUnitOfWork(unitOfWork) {
        var current2 = unitOfWork.alternate;
        (unitOfWork.mode & ProfileMode) !== NoMode ? (startProfilerTimer(unitOfWork), current2 = runWithFiberInDEV(
          unitOfWork,
          beginWork,
          current2,
          unitOfWork,
          entangledRenderLanes
        ), stopProfilerTimerIfRunningAndRecordDuration(unitOfWork)) : current2 = runWithFiberInDEV(
          unitOfWork,
          beginWork,
          current2,
          unitOfWork,
          entangledRenderLanes
        );
        unitOfWork.memoizedProps = unitOfWork.pendingProps;
        null === current2 ? completeUnitOfWork(unitOfWork) : workInProgress = current2;
      }
      function replaySuspendedUnitOfWork(unitOfWork) {
        var next = runWithFiberInDEV(unitOfWork, replayBeginWork, unitOfWork);
        unitOfWork.memoizedProps = unitOfWork.pendingProps;
        null === next ? completeUnitOfWork(unitOfWork) : workInProgress = next;
      }
      function replayBeginWork(unitOfWork) {
        var current2 = unitOfWork.alternate, isProfilingMode = (unitOfWork.mode & ProfileMode) !== NoMode;
        isProfilingMode && startProfilerTimer(unitOfWork);
        switch (unitOfWork.tag) {
          case 15:
          case 0:
            current2 = replayFunctionComponent(
              current2,
              unitOfWork,
              unitOfWork.pendingProps,
              unitOfWork.type,
              void 0,
              workInProgressRootRenderLanes
            );
            break;
          case 11:
            current2 = replayFunctionComponent(
              current2,
              unitOfWork,
              unitOfWork.pendingProps,
              unitOfWork.type.render,
              unitOfWork.ref,
              workInProgressRootRenderLanes
            );
            break;
          case 5:
            resetHooksOnUnwind(unitOfWork);
          default:
            unwindInterruptedWork(current2, unitOfWork), unitOfWork = workInProgress = resetWorkInProgress(unitOfWork, entangledRenderLanes), current2 = beginWork(current2, unitOfWork, entangledRenderLanes);
        }
        isProfilingMode && stopProfilerTimerIfRunningAndRecordDuration(unitOfWork);
        return current2;
      }
      function throwAndUnwindWorkLoop(root2, unitOfWork, thrownValue, suspendedReason) {
        resetContextDependencies();
        resetHooksOnUnwind(unitOfWork);
        thenableState$1 = null;
        thenableIndexCounter$1 = 0;
        var returnFiber = unitOfWork.return;
        try {
          if (throwException(
            root2,
            returnFiber,
            unitOfWork,
            thrownValue,
            workInProgressRootRenderLanes
          )) {
            workInProgressRootExitStatus = RootFatalErrored;
            logUncaughtError(
              root2,
              createCapturedValueAtFiber(thrownValue, root2.current)
            );
            workInProgress = null;
            return;
          }
        } catch (error) {
          if (null !== returnFiber) throw workInProgress = returnFiber, error;
          workInProgressRootExitStatus = RootFatalErrored;
          logUncaughtError(
            root2,
            createCapturedValueAtFiber(thrownValue, root2.current)
          );
          workInProgress = null;
          return;
        }
        if (unitOfWork.flags & 32768) {
          if (isHydrating || suspendedReason === SuspendedOnError) root2 = true;
          else if (workInProgressRootIsPrerendering || 0 !== (workInProgressRootRenderLanes & 536870912))
            root2 = false;
          else if (workInProgressRootDidSkipSuspendedSiblings = root2 = true, suspendedReason === SuspendedOnData || suspendedReason === SuspendedOnAction || suspendedReason === SuspendedOnImmediate || suspendedReason === SuspendedOnDeprecatedThrowPromise)
            suspendedReason = suspenseHandlerStackCursor.current, null !== suspendedReason && 13 === suspendedReason.tag && (suspendedReason.flags |= 16384);
          unwindUnitOfWork(unitOfWork, root2);
        } else completeUnitOfWork(unitOfWork);
      }
      function completeUnitOfWork(unitOfWork) {
        var completedWork = unitOfWork;
        do {
          if (0 !== (completedWork.flags & 32768)) {
            unwindUnitOfWork(
              completedWork,
              workInProgressRootDidSkipSuspendedSiblings
            );
            return;
          }
          var current2 = completedWork.alternate;
          unitOfWork = completedWork.return;
          startProfilerTimer(completedWork);
          current2 = runWithFiberInDEV(
            completedWork,
            completeWork,
            current2,
            completedWork,
            entangledRenderLanes
          );
          (completedWork.mode & ProfileMode) !== NoMode && stopProfilerTimerIfRunningAndRecordIncompleteDuration(completedWork);
          if (null !== current2) {
            workInProgress = current2;
            return;
          }
          completedWork = completedWork.sibling;
          if (null !== completedWork) {
            workInProgress = completedWork;
            return;
          }
          workInProgress = completedWork = unitOfWork;
        } while (null !== completedWork);
        workInProgressRootExitStatus === RootInProgress && (workInProgressRootExitStatus = RootCompleted);
      }
      function unwindUnitOfWork(unitOfWork, skipSiblings) {
        do {
          var next = unwindWork(unitOfWork.alternate, unitOfWork);
          if (null !== next) {
            next.flags &= 32767;
            workInProgress = next;
            return;
          }
          if ((unitOfWork.mode & ProfileMode) !== NoMode) {
            stopProfilerTimerIfRunningAndRecordIncompleteDuration(unitOfWork);
            next = unitOfWork.actualDuration;
            for (var child = unitOfWork.child; null !== child; )
              next += child.actualDuration, child = child.sibling;
            unitOfWork.actualDuration = next;
          }
          next = unitOfWork.return;
          null !== next && (next.flags |= 32768, next.subtreeFlags = 0, next.deletions = null);
          if (!skipSiblings && (unitOfWork = unitOfWork.sibling, null !== unitOfWork)) {
            workInProgress = unitOfWork;
            return;
          }
          workInProgress = unitOfWork = next;
        } while (null !== unitOfWork);
        workInProgressRootExitStatus = RootSuspendedAtTheShell;
        workInProgress = null;
      }
      function commitRoot(root2, finishedWork, lanes, recoverableErrors, transitions, didIncludeRenderPhaseUpdate, spawnedLane, updatedLanes, suspendedRetryLanes, exitStatus, suspendedState, suspendedCommitReason, completedRenderStartTime, completedRenderEndTime) {
        root2.cancelPendingCommit = null;
        do
          flushPendingEffects();
        while (pendingEffectsStatus !== NO_PENDING_EFFECTS);
        ReactStrictModeWarnings.flushLegacyContextWarning();
        ReactStrictModeWarnings.flushPendingUnsafeLifecycleWarnings();
        if ((executionContext & (RenderContext | CommitContext)) !== NoContext)
          throw Error("Should not already be working.");
        setCurrentTrackFromLanes(lanes);
        exitStatus === RootErrored ? logErroredRenderPhase(
          completedRenderStartTime,
          completedRenderEndTime,
          lanes,
          workInProgressUpdateTask
        ) : null !== recoverableErrors ? logRecoveredRenderPhase(
          completedRenderStartTime,
          completedRenderEndTime,
          lanes,
          recoverableErrors,
          null !== finishedWork && null !== finishedWork.alternate && finishedWork.alternate.memoizedState.isDehydrated && 0 !== (finishedWork.flags & 256),
          workInProgressUpdateTask
        ) : logRenderPhase(
          completedRenderStartTime,
          completedRenderEndTime,
          lanes,
          workInProgressUpdateTask
        );
        if (null !== finishedWork) {
          0 === lanes && console.error(
            "finishedLanes should not be empty during a commit. This is a bug in React."
          );
          if (finishedWork === root2.current)
            throw Error(
              "Cannot commit the same tree as before. This error is likely caused by a bug in React. Please file an issue."
            );
          didIncludeRenderPhaseUpdate = finishedWork.lanes | finishedWork.childLanes;
          didIncludeRenderPhaseUpdate |= concurrentlyUpdatedLanes;
          markRootFinished(
            root2,
            lanes,
            didIncludeRenderPhaseUpdate,
            spawnedLane,
            updatedLanes,
            suspendedRetryLanes
          );
          root2 === workInProgressRoot && (workInProgress = workInProgressRoot = null, workInProgressRootRenderLanes = 0);
          pendingFinishedWork = finishedWork;
          pendingEffectsRoot = root2;
          pendingEffectsLanes = lanes;
          pendingEffectsRemainingLanes = didIncludeRenderPhaseUpdate;
          pendingPassiveTransitions = transitions;
          pendingRecoverableErrors = recoverableErrors;
          pendingEffectsRenderEndTime = completedRenderEndTime;
          pendingSuspendedCommitReason = suspendedCommitReason;
          pendingDelayedCommitReason = IMMEDIATE_COMMIT;
          pendingSuspendedViewTransitionReason = null;
          0 !== finishedWork.actualDuration || 0 !== (finishedWork.subtreeFlags & 10256) || 0 !== (finishedWork.flags & 10256) ? (root2.callbackNode = null, root2.callbackPriority = 0, scheduleCallback$1(NormalPriority$1, function() {
            schedulerEvent = window.event;
            pendingDelayedCommitReason === IMMEDIATE_COMMIT && (pendingDelayedCommitReason = DELAYED_PASSIVE_COMMIT);
            flushPassiveEffects();
            return null;
          })) : (root2.callbackNode = null, root2.callbackPriority = 0);
          commitErrors = null;
          commitStartTime = now();
          null !== suspendedCommitReason && logSuspendedCommitPhase(
            completedRenderEndTime,
            commitStartTime,
            suspendedCommitReason,
            workInProgressUpdateTask
          );
          recoverableErrors = 0 !== (finishedWork.flags & 13878);
          if (0 !== (finishedWork.subtreeFlags & 13878) || recoverableErrors) {
            recoverableErrors = ReactSharedInternals.T;
            ReactSharedInternals.T = null;
            transitions = ReactDOMSharedInternals.p;
            ReactDOMSharedInternals.p = DiscreteEventPriority;
            spawnedLane = executionContext;
            executionContext |= CommitContext;
            try {
              commitBeforeMutationEffects(root2, finishedWork, lanes);
            } finally {
              executionContext = spawnedLane, ReactDOMSharedInternals.p = transitions, ReactSharedInternals.T = recoverableErrors;
            }
          }
          pendingEffectsStatus = PENDING_MUTATION_PHASE;
          flushMutationEffects();
          flushLayoutEffects();
          flushSpawnedWork();
        }
      }
      function flushMutationEffects() {
        if (pendingEffectsStatus === PENDING_MUTATION_PHASE) {
          pendingEffectsStatus = NO_PENDING_EFFECTS;
          var root2 = pendingEffectsRoot, finishedWork = pendingFinishedWork, lanes = pendingEffectsLanes, rootMutationHasEffect = 0 !== (finishedWork.flags & 13878);
          if (0 !== (finishedWork.subtreeFlags & 13878) || rootMutationHasEffect) {
            rootMutationHasEffect = ReactSharedInternals.T;
            ReactSharedInternals.T = null;
            var previousPriority = ReactDOMSharedInternals.p;
            ReactDOMSharedInternals.p = DiscreteEventPriority;
            var prevExecutionContext = executionContext;
            executionContext |= CommitContext;
            try {
              inProgressLanes = lanes;
              inProgressRoot = root2;
              resetComponentEffectTimers();
              commitMutationEffectsOnFiber(finishedWork, root2);
              inProgressRoot = inProgressLanes = null;
              lanes = selectionInformation;
              var curFocusedElem = getActiveElementDeep(root2.containerInfo), priorFocusedElem = lanes.focusedElem, priorSelectionRange = lanes.selectionRange;
              if (curFocusedElem !== priorFocusedElem && priorFocusedElem && priorFocusedElem.ownerDocument && containsNode(
                priorFocusedElem.ownerDocument.documentElement,
                priorFocusedElem
              )) {
                if (null !== priorSelectionRange && hasSelectionCapabilities(priorFocusedElem)) {
                  var start = priorSelectionRange.start, end = priorSelectionRange.end;
                  void 0 === end && (end = start);
                  if ("selectionStart" in priorFocusedElem)
                    priorFocusedElem.selectionStart = start, priorFocusedElem.selectionEnd = Math.min(
                      end,
                      priorFocusedElem.value.length
                    );
                  else {
                    var doc3 = priorFocusedElem.ownerDocument || document, win = doc3 && doc3.defaultView || window;
                    if (win.getSelection) {
                      var selection = win.getSelection(), length = priorFocusedElem.textContent.length, start$jscomp$0 = Math.min(
                        priorSelectionRange.start,
                        length
                      ), end$jscomp$0 = void 0 === priorSelectionRange.end ? start$jscomp$0 : Math.min(priorSelectionRange.end, length);
                      !selection.extend && start$jscomp$0 > end$jscomp$0 && (curFocusedElem = end$jscomp$0, end$jscomp$0 = start$jscomp$0, start$jscomp$0 = curFocusedElem);
                      var startMarker = getNodeForCharacterOffset(
                        priorFocusedElem,
                        start$jscomp$0
                      ), endMarker = getNodeForCharacterOffset(
                        priorFocusedElem,
                        end$jscomp$0
                      );
                      if (startMarker && endMarker && (1 !== selection.rangeCount || selection.anchorNode !== startMarker.node || selection.anchorOffset !== startMarker.offset || selection.focusNode !== endMarker.node || selection.focusOffset !== endMarker.offset)) {
                        var range = doc3.createRange();
                        range.setStart(startMarker.node, startMarker.offset);
                        selection.removeAllRanges();
                        start$jscomp$0 > end$jscomp$0 ? (selection.addRange(range), selection.extend(endMarker.node, endMarker.offset)) : (range.setEnd(endMarker.node, endMarker.offset), selection.addRange(range));
                      }
                    }
                  }
                }
                doc3 = [];
                for (selection = priorFocusedElem; selection = selection.parentNode; )
                  1 === selection.nodeType && doc3.push({
                    element: selection,
                    left: selection.scrollLeft,
                    top: selection.scrollTop
                  });
                "function" === typeof priorFocusedElem.focus && priorFocusedElem.focus();
                for (priorFocusedElem = 0; priorFocusedElem < doc3.length; priorFocusedElem++) {
                  var info = doc3[priorFocusedElem];
                  info.element.scrollLeft = info.left;
                  info.element.scrollTop = info.top;
                }
              }
              _enabled = !!eventsEnabled;
              selectionInformation = eventsEnabled = null;
            } finally {
              executionContext = prevExecutionContext, ReactDOMSharedInternals.p = previousPriority, ReactSharedInternals.T = rootMutationHasEffect;
            }
          }
          root2.current = finishedWork;
          pendingEffectsStatus = PENDING_LAYOUT_PHASE;
        }
      }
      function flushLayoutEffects() {
        if (pendingEffectsStatus === PENDING_LAYOUT_PHASE) {
          pendingEffectsStatus = NO_PENDING_EFFECTS;
          var suspendedViewTransitionReason = pendingSuspendedViewTransitionReason;
          if (null !== suspendedViewTransitionReason) {
            commitStartTime = now();
            var startTime = commitEndTime, endTime = commitStartTime;
            !supportsUserTiming || endTime <= startTime || (animatingTask ? animatingTask.run(
              console.timeStamp.bind(
                console,
                suspendedViewTransitionReason,
                startTime,
                endTime,
                currentTrack,
                LANES_TRACK_GROUP,
                "secondary-light"
              )
            ) : console.timeStamp(
              suspendedViewTransitionReason,
              startTime,
              endTime,
              currentTrack,
              LANES_TRACK_GROUP,
              "secondary-light"
            ));
          }
          suspendedViewTransitionReason = pendingEffectsRoot;
          startTime = pendingFinishedWork;
          endTime = pendingEffectsLanes;
          var rootHasLayoutEffect = 0 !== (startTime.flags & 8772);
          if (0 !== (startTime.subtreeFlags & 8772) || rootHasLayoutEffect) {
            rootHasLayoutEffect = ReactSharedInternals.T;
            ReactSharedInternals.T = null;
            var _previousPriority = ReactDOMSharedInternals.p;
            ReactDOMSharedInternals.p = DiscreteEventPriority;
            var _prevExecutionContext = executionContext;
            executionContext |= CommitContext;
            try {
              inProgressLanes = endTime, inProgressRoot = suspendedViewTransitionReason, resetComponentEffectTimers(), commitLayoutEffectOnFiber(
                suspendedViewTransitionReason,
                startTime.alternate,
                startTime
              ), inProgressRoot = inProgressLanes = null;
            } finally {
              executionContext = _prevExecutionContext, ReactDOMSharedInternals.p = _previousPriority, ReactSharedInternals.T = rootHasLayoutEffect;
            }
          }
          suspendedViewTransitionReason = pendingEffectsRenderEndTime;
          startTime = pendingSuspendedCommitReason;
          commitEndTime = now();
          suspendedViewTransitionReason = null === startTime ? suspendedViewTransitionReason : commitStartTime;
          startTime = commitEndTime;
          endTime = pendingDelayedCommitReason === ABORTED_VIEW_TRANSITION_COMMIT;
          rootHasLayoutEffect = workInProgressUpdateTask;
          null !== commitErrors ? logCommitErrored(
            suspendedViewTransitionReason,
            startTime,
            commitErrors,
            false,
            rootHasLayoutEffect
          ) : !supportsUserTiming || startTime <= suspendedViewTransitionReason || (rootHasLayoutEffect ? rootHasLayoutEffect.run(
            console.timeStamp.bind(
              console,
              endTime ? "Commit Interrupted View Transition" : "Commit",
              suspendedViewTransitionReason,
              startTime,
              currentTrack,
              LANES_TRACK_GROUP,
              endTime ? "error" : "secondary-dark"
            )
          ) : console.timeStamp(
            endTime ? "Commit Interrupted View Transition" : "Commit",
            suspendedViewTransitionReason,
            startTime,
            currentTrack,
            LANES_TRACK_GROUP,
            endTime ? "error" : "secondary-dark"
          ));
          pendingEffectsStatus = PENDING_AFTER_MUTATION_PHASE;
        }
      }
      function flushSpawnedWork() {
        if (pendingEffectsStatus === PENDING_SPAWNED_WORK || pendingEffectsStatus === PENDING_AFTER_MUTATION_PHASE) {
          if (pendingEffectsStatus === PENDING_SPAWNED_WORK) {
            var startViewTransitionStartTime = commitEndTime;
            commitEndTime = now();
            var endTime = commitEndTime, abortedViewTransition = pendingDelayedCommitReason === ABORTED_VIEW_TRANSITION_COMMIT;
            !supportsUserTiming || endTime <= startViewTransitionStartTime || (animatingTask ? animatingTask.run(
              console.timeStamp.bind(
                console,
                abortedViewTransition ? "Interrupted View Transition" : "Starting Animation",
                startViewTransitionStartTime,
                endTime,
                currentTrack,
                LANES_TRACK_GROUP,
                abortedViewTransition ? "error" : "secondary-light"
              )
            ) : console.timeStamp(
              abortedViewTransition ? "Interrupted View Transition" : "Starting Animation",
              startViewTransitionStartTime,
              endTime,
              currentTrack,
              LANES_TRACK_GROUP,
              abortedViewTransition ? " error" : "secondary-light"
            ));
            pendingDelayedCommitReason !== ABORTED_VIEW_TRANSITION_COMMIT && (pendingDelayedCommitReason = ANIMATION_STARTED_COMMIT);
          }
          pendingEffectsStatus = NO_PENDING_EFFECTS;
          requestPaint();
          startViewTransitionStartTime = pendingEffectsRoot;
          var finishedWork = pendingFinishedWork;
          endTime = pendingEffectsLanes;
          abortedViewTransition = pendingRecoverableErrors;
          var rootDidHavePassiveEffects = 0 !== finishedWork.actualDuration || 0 !== (finishedWork.subtreeFlags & 10256) || 0 !== (finishedWork.flags & 10256);
          rootDidHavePassiveEffects ? pendingEffectsStatus = PENDING_PASSIVE_PHASE : (pendingEffectsStatus = NO_PENDING_EFFECTS, pendingFinishedWork = pendingEffectsRoot = null, releaseRootPooledCache(
            startViewTransitionStartTime,
            startViewTransitionStartTime.pendingLanes
          ), nestedPassiveUpdateCount = 0, rootWithPassiveNestedUpdates = null);
          var remainingLanes = startViewTransitionStartTime.pendingLanes;
          0 === remainingLanes && (legacyErrorBoundariesThatAlreadyFailed = null);
          rootDidHavePassiveEffects || commitDoubleInvokeEffectsInDEV(startViewTransitionStartTime);
          remainingLanes = lanesToEventPriority(endTime);
          finishedWork = finishedWork.stateNode;
          if (injectedHook && "function" === typeof injectedHook.onCommitFiberRoot)
            try {
              var didError = 128 === (finishedWork.current.flags & 128);
              switch (remainingLanes) {
                case DiscreteEventPriority:
                  var schedulerPriority = ImmediatePriority;
                  break;
                case ContinuousEventPriority:
                  schedulerPriority = UserBlockingPriority;
                  break;
                case DefaultEventPriority:
                  schedulerPriority = NormalPriority$1;
                  break;
                case IdleEventPriority:
                  schedulerPriority = IdlePriority;
                  break;
                default:
                  schedulerPriority = NormalPriority$1;
              }
              injectedHook.onCommitFiberRoot(
                rendererID,
                finishedWork,
                schedulerPriority,
                didError
              );
            } catch (err) {
              hasLoggedError || (hasLoggedError = true, console.error(
                "React instrumentation encountered an error: %o",
                err
              ));
            }
          isDevToolsPresent && startViewTransitionStartTime.memoizedUpdaters.clear();
          onCommitRoot();
          if (null !== abortedViewTransition) {
            didError = ReactSharedInternals.T;
            schedulerPriority = ReactDOMSharedInternals.p;
            ReactDOMSharedInternals.p = DiscreteEventPriority;
            ReactSharedInternals.T = null;
            try {
              var onRecoverableError = startViewTransitionStartTime.onRecoverableError;
              for (finishedWork = 0; finishedWork < abortedViewTransition.length; finishedWork++) {
                var recoverableError = abortedViewTransition[finishedWork], errorInfo = makeErrorInfo(recoverableError.stack);
                runWithFiberInDEV(
                  recoverableError.source,
                  onRecoverableError,
                  recoverableError.value,
                  errorInfo
                );
              }
            } finally {
              ReactSharedInternals.T = didError, ReactDOMSharedInternals.p = schedulerPriority;
            }
          }
          0 !== (pendingEffectsLanes & 3) && flushPendingEffects();
          ensureRootIsScheduled(startViewTransitionStartTime);
          remainingLanes = startViewTransitionStartTime.pendingLanes;
          0 !== (endTime & 261930) && 0 !== (remainingLanes & 42) ? (nestedUpdateScheduled = true, startViewTransitionStartTime === rootWithNestedUpdates ? nestedUpdateCount++ : (nestedUpdateCount = 0, rootWithNestedUpdates = startViewTransitionStartTime)) : nestedUpdateCount = 0;
          rootDidHavePassiveEffects || finalizeRender(endTime, commitEndTime);
          flushSyncWorkAcrossRoots_impl(0, false);
        }
      }
      function makeErrorInfo(componentStack) {
        componentStack = { componentStack };
        Object.defineProperty(componentStack, "digest", {
          get: function() {
            console.error(
              'You are accessing "digest" from the errorInfo object passed to onRecoverableError. This property is no longer provided as part of errorInfo but can be accessed as a property of the Error instance itself.'
            );
          }
        });
        return componentStack;
      }
      function releaseRootPooledCache(root2, remainingLanes) {
        0 === (root2.pooledCacheLanes &= remainingLanes) && (remainingLanes = root2.pooledCache, null != remainingLanes && (root2.pooledCache = null, releaseCache(remainingLanes)));
      }
      function flushPendingEffects() {
        flushMutationEffects();
        flushLayoutEffects();
        flushSpawnedWork();
        return flushPassiveEffects();
      }
      function flushPassiveEffects() {
        if (pendingEffectsStatus !== PENDING_PASSIVE_PHASE) return false;
        var root2 = pendingEffectsRoot, remainingLanes = pendingEffectsRemainingLanes;
        pendingEffectsRemainingLanes = 0;
        var renderPriority = lanesToEventPriority(pendingEffectsLanes), priority = 0 === DefaultEventPriority || DefaultEventPriority > renderPriority ? DefaultEventPriority : renderPriority;
        renderPriority = ReactSharedInternals.T;
        var previousPriority = ReactDOMSharedInternals.p;
        try {
          ReactDOMSharedInternals.p = priority;
          ReactSharedInternals.T = null;
          var transitions = pendingPassiveTransitions;
          pendingPassiveTransitions = null;
          priority = pendingEffectsRoot;
          var lanes = pendingEffectsLanes;
          pendingEffectsStatus = NO_PENDING_EFFECTS;
          pendingFinishedWork = pendingEffectsRoot = null;
          pendingEffectsLanes = 0;
          if ((executionContext & (RenderContext | CommitContext)) !== NoContext)
            throw Error("Cannot flush passive effects while already rendering.");
          setCurrentTrackFromLanes(lanes);
          isFlushingPassiveEffects = true;
          didScheduleUpdateDuringPassiveEffects = false;
          var passiveEffectStartTime = 0;
          commitErrors = null;
          passiveEffectStartTime = now$1();
          if (pendingDelayedCommitReason === ANIMATION_STARTED_COMMIT)
            logAnimatingPhase(
              commitEndTime,
              passiveEffectStartTime,
              animatingTask
            );
          else {
            var startTime = commitEndTime, endTime = passiveEffectStartTime, delayedUntilPaint = pendingDelayedCommitReason === DELAYED_PASSIVE_COMMIT;
            !supportsUserTiming || endTime <= startTime || (workInProgressUpdateTask ? workInProgressUpdateTask.run(
              console.timeStamp.bind(
                console,
                delayedUntilPaint ? "Waiting for Paint" : "Waiting",
                startTime,
                endTime,
                currentTrack,
                LANES_TRACK_GROUP,
                "secondary-light"
              )
            ) : console.timeStamp(
              delayedUntilPaint ? "Waiting for Paint" : "Waiting",
              startTime,
              endTime,
              currentTrack,
              LANES_TRACK_GROUP,
              "secondary-light"
            ));
          }
          startTime = executionContext;
          executionContext |= CommitContext;
          var finishedWork = priority.current;
          resetComponentEffectTimers();
          commitPassiveUnmountOnFiber(finishedWork);
          var finishedWork$jscomp$0 = priority.current;
          finishedWork = pendingEffectsRenderEndTime;
          resetComponentEffectTimers();
          commitPassiveMountOnFiber(
            priority,
            finishedWork$jscomp$0,
            lanes,
            transitions,
            finishedWork
          );
          commitDoubleInvokeEffectsInDEV(priority);
          executionContext = startTime;
          var passiveEffectsEndTime = now$1();
          finishedWork$jscomp$0 = passiveEffectStartTime;
          finishedWork = workInProgressUpdateTask;
          null !== commitErrors ? logCommitErrored(
            finishedWork$jscomp$0,
            passiveEffectsEndTime,
            commitErrors,
            true,
            finishedWork
          ) : !supportsUserTiming || passiveEffectsEndTime <= finishedWork$jscomp$0 || (finishedWork ? finishedWork.run(
            console.timeStamp.bind(
              console,
              "Remaining Effects",
              finishedWork$jscomp$0,
              passiveEffectsEndTime,
              currentTrack,
              LANES_TRACK_GROUP,
              "secondary-dark"
            )
          ) : console.timeStamp(
            "Remaining Effects",
            finishedWork$jscomp$0,
            passiveEffectsEndTime,
            currentTrack,
            LANES_TRACK_GROUP,
            "secondary-dark"
          ));
          finalizeRender(lanes, passiveEffectsEndTime);
          flushSyncWorkAcrossRoots_impl(0, false);
          didScheduleUpdateDuringPassiveEffects ? priority === rootWithPassiveNestedUpdates ? nestedPassiveUpdateCount++ : (nestedPassiveUpdateCount = 0, rootWithPassiveNestedUpdates = priority) : nestedPassiveUpdateCount = 0;
          didScheduleUpdateDuringPassiveEffects = isFlushingPassiveEffects = false;
          if (injectedHook && "function" === typeof injectedHook.onPostCommitFiberRoot)
            try {
              injectedHook.onPostCommitFiberRoot(rendererID, priority);
            } catch (err) {
              hasLoggedError || (hasLoggedError = true, console.error(
                "React instrumentation encountered an error: %o",
                err
              ));
            }
          var stateNode = priority.current.stateNode;
          stateNode.effectDuration = 0;
          stateNode.passiveEffectDuration = 0;
          return true;
        } finally {
          ReactDOMSharedInternals.p = previousPriority, ReactSharedInternals.T = renderPriority, releaseRootPooledCache(root2, remainingLanes);
        }
      }
      function captureCommitPhaseErrorOnRoot(rootFiber, sourceFiber, error) {
        sourceFiber = createCapturedValueAtFiber(error, sourceFiber);
        recordEffectError(sourceFiber);
        sourceFiber = createRootErrorUpdate(rootFiber.stateNode, sourceFiber, 2);
        rootFiber = enqueueUpdate(rootFiber, sourceFiber, 2);
        null !== rootFiber && (markRootUpdated$1(rootFiber, 2), ensureRootIsScheduled(rootFiber));
      }
      function captureCommitPhaseError(sourceFiber, nearestMountedAncestor, error) {
        isRunningInsertionEffect = false;
        if (3 === sourceFiber.tag)
          captureCommitPhaseErrorOnRoot(sourceFiber, sourceFiber, error);
        else {
          for (; null !== nearestMountedAncestor; ) {
            if (3 === nearestMountedAncestor.tag) {
              captureCommitPhaseErrorOnRoot(
                nearestMountedAncestor,
                sourceFiber,
                error
              );
              return;
            }
            if (1 === nearestMountedAncestor.tag) {
              var instance = nearestMountedAncestor.stateNode;
              if ("function" === typeof nearestMountedAncestor.type.getDerivedStateFromError || "function" === typeof instance.componentDidCatch && (null === legacyErrorBoundariesThatAlreadyFailed || !legacyErrorBoundariesThatAlreadyFailed.has(instance))) {
                sourceFiber = createCapturedValueAtFiber(error, sourceFiber);
                recordEffectError(sourceFiber);
                error = createClassErrorUpdate(2);
                instance = enqueueUpdate(nearestMountedAncestor, error, 2);
                null !== instance && (initializeClassErrorUpdate(
                  error,
                  instance,
                  nearestMountedAncestor,
                  sourceFiber
                ), markRootUpdated$1(instance, 2), ensureRootIsScheduled(instance));
                return;
              }
            }
            nearestMountedAncestor = nearestMountedAncestor.return;
          }
          console.error(
            "Internal React error: Attempted to capture a commit phase error inside a detached tree. This indicates a bug in React. Potential causes include deleting the same fiber more than once, committing an already-finished tree, or an inconsistent return pointer.\n\nError message:\n\n%s",
            error
          );
        }
      }
      function attachPingListener(root2, wakeable, lanes) {
        var pingCache = root2.pingCache;
        if (null === pingCache) {
          pingCache = root2.pingCache = new PossiblyWeakMap();
          var threadIDs = /* @__PURE__ */ new Set();
          pingCache.set(wakeable, threadIDs);
        } else
          threadIDs = pingCache.get(wakeable), void 0 === threadIDs && (threadIDs = /* @__PURE__ */ new Set(), pingCache.set(wakeable, threadIDs));
        threadIDs.has(lanes) || (workInProgressRootDidAttachPingListener = true, threadIDs.add(lanes), pingCache = pingSuspendedRoot.bind(null, root2, wakeable, lanes), isDevToolsPresent && restorePendingUpdaters(root2, lanes), wakeable.then(pingCache, pingCache));
      }
      function pingSuspendedRoot(root2, wakeable, pingedLanes) {
        var pingCache = root2.pingCache;
        null !== pingCache && pingCache.delete(wakeable);
        root2.pingedLanes |= root2.suspendedLanes & pingedLanes;
        root2.warmLanes &= ~pingedLanes;
        0 !== (pingedLanes & 127) ? 0 > blockingUpdateTime && (blockingClampTime = blockingUpdateTime = now(), blockingUpdateTask = createTask("Promise Resolved"), blockingUpdateType = PINGED_UPDATE) : 0 !== (pingedLanes & 4194048) && 0 > transitionUpdateTime && (transitionClampTime = transitionUpdateTime = now(), transitionUpdateTask = createTask("Promise Resolved"), transitionUpdateType = PINGED_UPDATE);
        isConcurrentActEnvironment() && null === ReactSharedInternals.actQueue && console.error(
          "A suspended resource finished loading inside a test, but the event was not wrapped in act(...).\n\nWhen testing, code that resolves suspended data should be wrapped into act(...):\n\nact(() => {\n  /* finish loading suspended data */\n});\n/* assert on the output */\n\nThis ensures that you're testing the behavior the user would see in the browser. Learn more at https://react.dev/link/wrap-tests-with-act"
        );
        workInProgressRoot === root2 && (workInProgressRootRenderLanes & pingedLanes) === pingedLanes && (workInProgressRootExitStatus === RootSuspendedWithDelay || workInProgressRootExitStatus === RootSuspended && (workInProgressRootRenderLanes & 62914560) === workInProgressRootRenderLanes && now$1() - globalMostRecentFallbackTime < FALLBACK_THROTTLE_MS ? (executionContext & RenderContext) === NoContext && prepareFreshStack(root2, 0) : workInProgressRootPingedLanes |= pingedLanes, workInProgressSuspendedRetryLanes === workInProgressRootRenderLanes && (workInProgressSuspendedRetryLanes = 0));
        ensureRootIsScheduled(root2);
      }
      function retryTimedOutBoundary(boundaryFiber, retryLane) {
        0 === retryLane && (retryLane = claimNextRetryLane());
        boundaryFiber = enqueueConcurrentRenderForLane(boundaryFiber, retryLane);
        null !== boundaryFiber && (markRootUpdated$1(boundaryFiber, retryLane), ensureRootIsScheduled(boundaryFiber));
      }
      function retryDehydratedSuspenseBoundary(boundaryFiber) {
        var suspenseState = boundaryFiber.memoizedState, retryLane = 0;
        null !== suspenseState && (retryLane = suspenseState.retryLane);
        retryTimedOutBoundary(boundaryFiber, retryLane);
      }
      function resolveRetryWakeable(boundaryFiber, wakeable) {
        var retryLane = 0;
        switch (boundaryFiber.tag) {
          case 31:
          case 13:
            var retryCache = boundaryFiber.stateNode;
            var suspenseState = boundaryFiber.memoizedState;
            null !== suspenseState && (retryLane = suspenseState.retryLane);
            break;
          case 19:
            retryCache = boundaryFiber.stateNode;
            break;
          case 22:
            retryCache = boundaryFiber.stateNode._retryCache;
            break;
          default:
            throw Error(
              "Pinged unknown suspense boundary type. This is probably a bug in React."
            );
        }
        null !== retryCache && retryCache.delete(wakeable);
        retryTimedOutBoundary(boundaryFiber, retryLane);
      }
      function recursivelyTraverseAndDoubleInvokeEffectsInDEV(root$jscomp$0, parentFiber, isInStrictMode) {
        if (0 !== (parentFiber.subtreeFlags & 67117056))
          for (parentFiber = parentFiber.child; null !== parentFiber; ) {
            var root2 = root$jscomp$0, fiber = parentFiber, isStrictModeFiber = fiber.type === REACT_STRICT_MODE_TYPE;
            isStrictModeFiber = isInStrictMode || isStrictModeFiber;
            22 !== fiber.tag ? fiber.flags & 67108864 ? isStrictModeFiber && runWithFiberInDEV(
              fiber,
              doubleInvokeEffectsOnFiber,
              root2,
              fiber
            ) : recursivelyTraverseAndDoubleInvokeEffectsInDEV(
              root2,
              fiber,
              isStrictModeFiber
            ) : null === fiber.memoizedState && (isStrictModeFiber && fiber.flags & 8192 ? runWithFiberInDEV(
              fiber,
              doubleInvokeEffectsOnFiber,
              root2,
              fiber
            ) : fiber.subtreeFlags & 67108864 && runWithFiberInDEV(
              fiber,
              recursivelyTraverseAndDoubleInvokeEffectsInDEV,
              root2,
              fiber,
              isStrictModeFiber
            ));
            parentFiber = parentFiber.sibling;
          }
      }
      function doubleInvokeEffectsOnFiber(root2, fiber) {
        setIsStrictModeForDevtools(true);
        try {
          disappearLayoutEffects(fiber), disconnectPassiveEffect(fiber), reappearLayoutEffects(root2, fiber.alternate, fiber, false), reconnectPassiveEffects(root2, fiber, 0, null, false, 0);
        } finally {
          setIsStrictModeForDevtools(false);
        }
      }
      function commitDoubleInvokeEffectsInDEV(root2) {
        var doubleInvokeEffects = true;
        root2.current.mode & (StrictLegacyMode | StrictEffectsMode) || (doubleInvokeEffects = false);
        recursivelyTraverseAndDoubleInvokeEffectsInDEV(
          root2,
          root2.current,
          doubleInvokeEffects
        );
      }
      function warnAboutUpdateOnNotYetMountedFiberInDEV(fiber) {
        if ((executionContext & RenderContext) === NoContext) {
          var tag = fiber.tag;
          if (3 === tag || 1 === tag || 0 === tag || 11 === tag || 14 === tag || 15 === tag) {
            tag = getComponentNameFromFiber(fiber) || "ReactComponent";
            if (null !== didWarnStateUpdateForNotYetMountedComponent) {
              if (didWarnStateUpdateForNotYetMountedComponent.has(tag)) return;
              didWarnStateUpdateForNotYetMountedComponent.add(tag);
            } else didWarnStateUpdateForNotYetMountedComponent = /* @__PURE__ */ new Set([tag]);
            runWithFiberInDEV(fiber, function() {
              console.error(
                "Can't perform a React state update on a component that hasn't mounted yet. This indicates that you have a side-effect in your render function that asynchronously tries to update the component. Move this work to useEffect instead."
              );
            });
          }
        }
      }
      function restorePendingUpdaters(root2, lanes) {
        isDevToolsPresent && root2.memoizedUpdaters.forEach(function(schedulingFiber) {
          addFiberToLanesMap(root2, schedulingFiber, lanes);
        });
      }
      function scheduleCallback$1(priorityLevel, callback) {
        var actQueue = ReactSharedInternals.actQueue;
        return null !== actQueue ? (actQueue.push(callback), fakeActCallbackNode$1) : scheduleCallback$3(priorityLevel, callback);
      }
      function warnIfUpdatesNotWrappedWithActDEV(fiber) {
        isConcurrentActEnvironment() && null === ReactSharedInternals.actQueue && runWithFiberInDEV(fiber, function() {
          console.error(
            "An update to %s inside a test was not wrapped in act(...).\n\nWhen testing, code that causes React state updates should be wrapped into act(...):\n\nact(() => {\n  /* fire events that update state */\n});\n/* assert on the output */\n\nThis ensures that you're testing the behavior the user would see in the browser. Learn more at https://react.dev/link/wrap-tests-with-act",
            getComponentNameFromFiber(fiber)
          );
        });
      }
      function ensureRootIsScheduled(root2) {
        root2 !== lastScheduledRoot && null === root2.next && (null === lastScheduledRoot ? firstScheduledRoot = lastScheduledRoot = root2 : lastScheduledRoot = lastScheduledRoot.next = root2);
        mightHavePendingSyncWork = true;
        null !== ReactSharedInternals.actQueue ? didScheduleMicrotask_act || (didScheduleMicrotask_act = true, scheduleImmediateRootScheduleTask()) : didScheduleMicrotask || (didScheduleMicrotask = true, scheduleImmediateRootScheduleTask());
      }
      function flushSyncWorkAcrossRoots_impl(syncTransitionLanes, onlyLegacy) {
        if (!isFlushingWork && mightHavePendingSyncWork) {
          isFlushingWork = true;
          do {
            var didPerformSomeWork = false;
            for (var root2 = firstScheduledRoot; null !== root2; ) {
              if (!onlyLegacy)
                if (0 !== syncTransitionLanes) {
                  var pendingLanes = root2.pendingLanes;
                  if (0 === pendingLanes) var nextLanes = 0;
                  else {
                    var suspendedLanes = root2.suspendedLanes, pingedLanes = root2.pingedLanes;
                    nextLanes = (1 << 31 - clz32(42 | syncTransitionLanes) + 1) - 1;
                    nextLanes &= pendingLanes & ~(suspendedLanes & ~pingedLanes);
                    nextLanes = nextLanes & 201326741 ? nextLanes & 201326741 | 1 : nextLanes ? nextLanes | 2 : 0;
                  }
                  0 !== nextLanes && (didPerformSomeWork = true, performSyncWorkOnRoot(root2, nextLanes));
                } else
                  nextLanes = workInProgressRootRenderLanes, nextLanes = getNextLanes(
                    root2,
                    root2 === workInProgressRoot ? nextLanes : 0,
                    null !== root2.cancelPendingCommit || root2.timeoutHandle !== noTimeout
                  ), 0 === (nextLanes & 3) || checkIfRootIsPrerendering(root2, nextLanes) || (didPerformSomeWork = true, performSyncWorkOnRoot(root2, nextLanes));
              root2 = root2.next;
            }
          } while (didPerformSomeWork);
          isFlushingWork = false;
        }
      }
      function processRootScheduleInImmediateTask() {
        schedulerEvent = window.event;
        processRootScheduleInMicrotask();
      }
      function processRootScheduleInMicrotask() {
        mightHavePendingSyncWork = didScheduleMicrotask_act = didScheduleMicrotask = false;
        var syncTransitionLanes = 0;
        0 !== currentEventTransitionLane && shouldAttemptEagerTransition() && (syncTransitionLanes = currentEventTransitionLane);
        for (var currentTime = now$1(), prev = null, root2 = firstScheduledRoot; null !== root2; ) {
          var next = root2.next, nextLanes = scheduleTaskForRootDuringMicrotask(root2, currentTime);
          if (0 === nextLanes)
            root2.next = null, null === prev ? firstScheduledRoot = next : prev.next = next, null === next && (lastScheduledRoot = prev);
          else if (prev = root2, 0 !== syncTransitionLanes || 0 !== (nextLanes & 3))
            mightHavePendingSyncWork = true;
          root2 = next;
        }
        pendingEffectsStatus !== NO_PENDING_EFFECTS && pendingEffectsStatus !== PENDING_PASSIVE_PHASE || flushSyncWorkAcrossRoots_impl(syncTransitionLanes, false);
        0 !== currentEventTransitionLane && (currentEventTransitionLane = 0);
      }
      function scheduleTaskForRootDuringMicrotask(root2, currentTime) {
        for (var suspendedLanes = root2.suspendedLanes, pingedLanes = root2.pingedLanes, expirationTimes = root2.expirationTimes, lanes = root2.pendingLanes & -62914561; 0 < lanes; ) {
          var index = 31 - clz32(lanes), lane = 1 << index, expirationTime = expirationTimes[index];
          if (-1 === expirationTime) {
            if (0 === (lane & suspendedLanes) || 0 !== (lane & pingedLanes))
              expirationTimes[index] = computeExpirationTime(lane, currentTime);
          } else expirationTime <= currentTime && (root2.expiredLanes |= lane);
          lanes &= ~lane;
        }
        currentTime = workInProgressRoot;
        suspendedLanes = workInProgressRootRenderLanes;
        suspendedLanes = getNextLanes(
          root2,
          root2 === currentTime ? suspendedLanes : 0,
          null !== root2.cancelPendingCommit || root2.timeoutHandle !== noTimeout
        );
        pingedLanes = root2.callbackNode;
        if (0 === suspendedLanes || root2 === currentTime && (workInProgressSuspendedReason === SuspendedOnData || workInProgressSuspendedReason === SuspendedOnAction) || null !== root2.cancelPendingCommit)
          return null !== pingedLanes && cancelCallback(pingedLanes), root2.callbackNode = null, root2.callbackPriority = 0;
        if (0 === (suspendedLanes & 3) || checkIfRootIsPrerendering(root2, suspendedLanes)) {
          currentTime = suspendedLanes & -suspendedLanes;
          if (currentTime !== root2.callbackPriority || null !== ReactSharedInternals.actQueue && pingedLanes !== fakeActCallbackNode)
            cancelCallback(pingedLanes);
          else return currentTime;
          switch (lanesToEventPriority(suspendedLanes)) {
            case DiscreteEventPriority:
            case ContinuousEventPriority:
              suspendedLanes = UserBlockingPriority;
              break;
            case DefaultEventPriority:
              suspendedLanes = NormalPriority$1;
              break;
            case IdleEventPriority:
              suspendedLanes = IdlePriority;
              break;
            default:
              suspendedLanes = NormalPriority$1;
          }
          pingedLanes = performWorkOnRootViaSchedulerTask.bind(null, root2);
          null !== ReactSharedInternals.actQueue ? (ReactSharedInternals.actQueue.push(pingedLanes), suspendedLanes = fakeActCallbackNode) : suspendedLanes = scheduleCallback$3(suspendedLanes, pingedLanes);
          root2.callbackPriority = currentTime;
          root2.callbackNode = suspendedLanes;
          return currentTime;
        }
        null !== pingedLanes && cancelCallback(pingedLanes);
        root2.callbackPriority = 2;
        root2.callbackNode = null;
        return 2;
      }
      function performWorkOnRootViaSchedulerTask(root2, didTimeout) {
        nestedUpdateScheduled = currentUpdateIsNested = false;
        schedulerEvent = window.event;
        if (pendingEffectsStatus !== NO_PENDING_EFFECTS && pendingEffectsStatus !== PENDING_PASSIVE_PHASE)
          return root2.callbackNode = null, root2.callbackPriority = 0, null;
        var originalCallbackNode = root2.callbackNode;
        pendingDelayedCommitReason === IMMEDIATE_COMMIT && (pendingDelayedCommitReason = DELAYED_PASSIVE_COMMIT);
        if (flushPendingEffects() && root2.callbackNode !== originalCallbackNode)
          return null;
        var workInProgressRootRenderLanes$jscomp$0 = workInProgressRootRenderLanes;
        workInProgressRootRenderLanes$jscomp$0 = getNextLanes(
          root2,
          root2 === workInProgressRoot ? workInProgressRootRenderLanes$jscomp$0 : 0,
          null !== root2.cancelPendingCommit || root2.timeoutHandle !== noTimeout
        );
        if (0 === workInProgressRootRenderLanes$jscomp$0) return null;
        performWorkOnRoot(
          root2,
          workInProgressRootRenderLanes$jscomp$0,
          didTimeout
        );
        scheduleTaskForRootDuringMicrotask(root2, now$1());
        return null != root2.callbackNode && root2.callbackNode === originalCallbackNode ? performWorkOnRootViaSchedulerTask.bind(null, root2) : null;
      }
      function performSyncWorkOnRoot(root2, lanes) {
        if (flushPendingEffects()) return null;
        currentUpdateIsNested = nestedUpdateScheduled;
        nestedUpdateScheduled = false;
        performWorkOnRoot(root2, lanes, true);
      }
      function cancelCallback(callbackNode) {
        callbackNode !== fakeActCallbackNode && null !== callbackNode && cancelCallback$1(callbackNode);
      }
      function scheduleImmediateRootScheduleTask() {
        null !== ReactSharedInternals.actQueue && ReactSharedInternals.actQueue.push(function() {
          processRootScheduleInMicrotask();
          return null;
        });
        scheduleMicrotask(function() {
          (executionContext & (RenderContext | CommitContext)) !== NoContext ? scheduleCallback$3(
            ImmediatePriority,
            processRootScheduleInImmediateTask
          ) : processRootScheduleInMicrotask();
        });
      }
      function requestTransitionLane() {
        if (0 === currentEventTransitionLane) {
          var actionScopeLane = currentEntangledLane;
          0 === actionScopeLane && (actionScopeLane = nextTransitionUpdateLane, nextTransitionUpdateLane <<= 1, 0 === (nextTransitionUpdateLane & 261888) && (nextTransitionUpdateLane = 256));
          currentEventTransitionLane = actionScopeLane;
        }
        return currentEventTransitionLane;
      }
      function coerceFormActionProp(actionProp) {
        if (null == actionProp || "symbol" === typeof actionProp || "boolean" === typeof actionProp)
          return null;
        if ("function" === typeof actionProp) return actionProp;
        checkAttributeStringCoercion(actionProp, "action");
        return sanitizeURL("" + actionProp);
      }
      function createFormDataWithSubmitter(form, submitter) {
        var temp = submitter.ownerDocument.createElement("input");
        temp.name = submitter.name;
        temp.value = submitter.value;
        form.id && temp.setAttribute("form", form.id);
        submitter.parentNode.insertBefore(temp, submitter);
        form = new FormData(form);
        temp.parentNode.removeChild(temp);
        return form;
      }
      function extractEvents$1(dispatchQueue, domEventName, maybeTargetInst, nativeEvent, nativeEventTarget) {
        if ("submit" === domEventName && maybeTargetInst && maybeTargetInst.stateNode === nativeEventTarget) {
          var action = coerceFormActionProp(
            (nativeEventTarget[internalPropsKey] || null).action
          ), submitter = nativeEvent.submitter;
          submitter && (domEventName = (domEventName = submitter[internalPropsKey] || null) ? coerceFormActionProp(domEventName.formAction) : submitter.getAttribute("formAction"), null !== domEventName && (action = domEventName, submitter = null));
          var event = new SyntheticEvent(
            "action",
            "action",
            null,
            nativeEvent,
            nativeEventTarget
          );
          dispatchQueue.push({
            event,
            listeners: [
              {
                instance: null,
                listener: function() {
                  if (nativeEvent.defaultPrevented) {
                    if (0 !== currentEventTransitionLane) {
                      var formData = submitter ? createFormDataWithSubmitter(
                        nativeEventTarget,
                        submitter
                      ) : new FormData(nativeEventTarget), pendingState = {
                        pending: true,
                        data: formData,
                        method: nativeEventTarget.method,
                        action
                      };
                      Object.freeze(pendingState);
                      startHostTransition(
                        maybeTargetInst,
                        pendingState,
                        null,
                        formData
                      );
                    }
                  } else
                    "function" === typeof action && (event.preventDefault(), formData = submitter ? createFormDataWithSubmitter(
                      nativeEventTarget,
                      submitter
                    ) : new FormData(nativeEventTarget), pendingState = {
                      pending: true,
                      data: formData,
                      method: nativeEventTarget.method,
                      action
                    }, Object.freeze(pendingState), startHostTransition(
                      maybeTargetInst,
                      pendingState,
                      action,
                      formData
                    ));
                },
                currentTarget: nativeEventTarget
              }
            ]
          });
        }
      }
      function executeDispatch(event, listener, currentTarget) {
        event.currentTarget = currentTarget;
        try {
          listener(event);
        } catch (error) {
          reportGlobalError(error);
        }
        event.currentTarget = null;
      }
      function processDispatchQueue(dispatchQueue, eventSystemFlags) {
        eventSystemFlags = 0 !== (eventSystemFlags & 4);
        for (var i = 0; i < dispatchQueue.length; i++) {
          var _dispatchQueue$i = dispatchQueue[i];
          a: {
            var previousInstance = void 0, event = _dispatchQueue$i.event;
            _dispatchQueue$i = _dispatchQueue$i.listeners;
            if (eventSystemFlags)
              for (var i$jscomp$0 = _dispatchQueue$i.length - 1; 0 <= i$jscomp$0; i$jscomp$0--) {
                var _dispatchListeners$i = _dispatchQueue$i[i$jscomp$0], instance = _dispatchListeners$i.instance, currentTarget = _dispatchListeners$i.currentTarget;
                _dispatchListeners$i = _dispatchListeners$i.listener;
                if (instance !== previousInstance && event.isPropagationStopped())
                  break a;
                null !== instance ? runWithFiberInDEV(
                  instance,
                  executeDispatch,
                  event,
                  _dispatchListeners$i,
                  currentTarget
                ) : executeDispatch(event, _dispatchListeners$i, currentTarget);
                previousInstance = instance;
              }
            else
              for (i$jscomp$0 = 0; i$jscomp$0 < _dispatchQueue$i.length; i$jscomp$0++) {
                _dispatchListeners$i = _dispatchQueue$i[i$jscomp$0];
                instance = _dispatchListeners$i.instance;
                currentTarget = _dispatchListeners$i.currentTarget;
                _dispatchListeners$i = _dispatchListeners$i.listener;
                if (instance !== previousInstance && event.isPropagationStopped())
                  break a;
                null !== instance ? runWithFiberInDEV(
                  instance,
                  executeDispatch,
                  event,
                  _dispatchListeners$i,
                  currentTarget
                ) : executeDispatch(event, _dispatchListeners$i, currentTarget);
                previousInstance = instance;
              }
          }
        }
      }
      function listenToNonDelegatedEvent(domEventName, targetElement) {
        nonDelegatedEvents.has(domEventName) || console.error(
          'Did not expect a listenToNonDelegatedEvent() call for "%s". This is a bug in React. Please file an issue.',
          domEventName
        );
        var listenerSet = targetElement[internalEventHandlersKey];
        void 0 === listenerSet && (listenerSet = targetElement[internalEventHandlersKey] = /* @__PURE__ */ new Set());
        var listenerSetKey = domEventName + "__bubble";
        listenerSet.has(listenerSetKey) || (addTrappedEventListener(targetElement, domEventName, 2, false), listenerSet.add(listenerSetKey));
      }
      function listenToNativeEvent(domEventName, isCapturePhaseListener, target2) {
        nonDelegatedEvents.has(domEventName) && !isCapturePhaseListener && console.error(
          'Did not expect a listenToNativeEvent() call for "%s" in the bubble phase. This is a bug in React. Please file an issue.',
          domEventName
        );
        var eventSystemFlags = 0;
        isCapturePhaseListener && (eventSystemFlags |= 4);
        addTrappedEventListener(
          target2,
          domEventName,
          eventSystemFlags,
          isCapturePhaseListener
        );
      }
      function listenToAllSupportedEvents(rootContainerElement) {
        if (!rootContainerElement[listeningMarker]) {
          rootContainerElement[listeningMarker] = true;
          allNativeEvents.forEach(function(domEventName) {
            "selectionchange" !== domEventName && (nonDelegatedEvents.has(domEventName) || listenToNativeEvent(domEventName, false, rootContainerElement), listenToNativeEvent(domEventName, true, rootContainerElement));
          });
          var ownerDocument = 9 === rootContainerElement.nodeType ? rootContainerElement : rootContainerElement.ownerDocument;
          null === ownerDocument || ownerDocument[listeningMarker] || (ownerDocument[listeningMarker] = true, listenToNativeEvent("selectionchange", false, ownerDocument));
        }
      }
      function addTrappedEventListener(targetContainer, domEventName, eventSystemFlags, isCapturePhaseListener) {
        switch (getEventPriority(domEventName)) {
          case DiscreteEventPriority:
            var listenerWrapper = dispatchDiscreteEvent;
            break;
          case ContinuousEventPriority:
            listenerWrapper = dispatchContinuousEvent;
            break;
          default:
            listenerWrapper = dispatchEvent2;
        }
        eventSystemFlags = listenerWrapper.bind(
          null,
          domEventName,
          eventSystemFlags,
          targetContainer
        );
        listenerWrapper = void 0;
        !passiveBrowserEventsSupported || "touchstart" !== domEventName && "touchmove" !== domEventName && "wheel" !== domEventName || (listenerWrapper = true);
        isCapturePhaseListener ? void 0 !== listenerWrapper ? targetContainer.addEventListener(domEventName, eventSystemFlags, {
          capture: true,
          passive: listenerWrapper
        }) : targetContainer.addEventListener(domEventName, eventSystemFlags, true) : void 0 !== listenerWrapper ? targetContainer.addEventListener(domEventName, eventSystemFlags, {
          passive: listenerWrapper
        }) : targetContainer.addEventListener(
          domEventName,
          eventSystemFlags,
          false
        );
      }
      function dispatchEventForPluginEventSystem(domEventName, eventSystemFlags, nativeEvent, targetInst$jscomp$0, targetContainer) {
        var ancestorInst = targetInst$jscomp$0;
        if (0 === (eventSystemFlags & 1) && 0 === (eventSystemFlags & 2) && null !== targetInst$jscomp$0)
          a: for (; ; ) {
            if (null === targetInst$jscomp$0) return;
            var nodeTag = targetInst$jscomp$0.tag;
            if (3 === nodeTag || 4 === nodeTag) {
              var container = targetInst$jscomp$0.stateNode.containerInfo;
              if (container === targetContainer) break;
              if (4 === nodeTag)
                for (nodeTag = targetInst$jscomp$0.return; null !== nodeTag; ) {
                  var grandTag = nodeTag.tag;
                  if ((3 === grandTag || 4 === grandTag) && nodeTag.stateNode.containerInfo === targetContainer)
                    return;
                  nodeTag = nodeTag.return;
                }
              for (; null !== container; ) {
                nodeTag = getClosestInstanceFromNode(container);
                if (null === nodeTag) return;
                grandTag = nodeTag.tag;
                if (5 === grandTag || 6 === grandTag || 26 === grandTag || 27 === grandTag) {
                  targetInst$jscomp$0 = ancestorInst = nodeTag;
                  continue a;
                }
                container = container.parentNode;
              }
            }
            targetInst$jscomp$0 = targetInst$jscomp$0.return;
          }
        batchedUpdates$1(function() {
          var targetInst = ancestorInst, nativeEventTarget = getEventTarget(nativeEvent), dispatchQueue = [];
          a: {
            var reactName = topLevelEventsToReactNames.get(domEventName);
            if (void 0 !== reactName) {
              var SyntheticEventCtor = SyntheticEvent, reactEventType = domEventName;
              switch (domEventName) {
                case "keypress":
                  if (0 === getEventCharCode(nativeEvent)) break a;
                case "keydown":
                case "keyup":
                  SyntheticEventCtor = SyntheticKeyboardEvent;
                  break;
                case "focusin":
                  reactEventType = "focus";
                  SyntheticEventCtor = SyntheticFocusEvent;
                  break;
                case "focusout":
                  reactEventType = "blur";
                  SyntheticEventCtor = SyntheticFocusEvent;
                  break;
                case "beforeblur":
                case "afterblur":
                  SyntheticEventCtor = SyntheticFocusEvent;
                  break;
                case "click":
                  if (2 === nativeEvent.button) break a;
                case "auxclick":
                case "dblclick":
                case "mousedown":
                case "mousemove":
                case "mouseup":
                case "mouseout":
                case "mouseover":
                case "contextmenu":
                  SyntheticEventCtor = SyntheticMouseEvent;
                  break;
                case "drag":
                case "dragend":
                case "dragenter":
                case "dragexit":
                case "dragleave":
                case "dragover":
                case "dragstart":
                case "drop":
                  SyntheticEventCtor = SyntheticDragEvent;
                  break;
                case "touchcancel":
                case "touchend":
                case "touchmove":
                case "touchstart":
                  SyntheticEventCtor = SyntheticTouchEvent;
                  break;
                case ANIMATION_END:
                case ANIMATION_ITERATION:
                case ANIMATION_START:
                  SyntheticEventCtor = SyntheticAnimationEvent;
                  break;
                case TRANSITION_END:
                  SyntheticEventCtor = SyntheticTransitionEvent;
                  break;
                case "scroll":
                case "scrollend":
                  SyntheticEventCtor = SyntheticUIEvent;
                  break;
                case "wheel":
                  SyntheticEventCtor = SyntheticWheelEvent;
                  break;
                case "copy":
                case "cut":
                case "paste":
                  SyntheticEventCtor = SyntheticClipboardEvent;
                  break;
                case "gotpointercapture":
                case "lostpointercapture":
                case "pointercancel":
                case "pointerdown":
                case "pointermove":
                case "pointerout":
                case "pointerover":
                case "pointerup":
                  SyntheticEventCtor = SyntheticPointerEvent;
                  break;
                case "toggle":
                case "beforetoggle":
                  SyntheticEventCtor = SyntheticToggleEvent;
              }
              var inCapturePhase = 0 !== (eventSystemFlags & 4), accumulateTargetOnly = !inCapturePhase && ("scroll" === domEventName || "scrollend" === domEventName), reactEventName = inCapturePhase ? null !== reactName ? reactName + "Capture" : null : reactName;
              inCapturePhase = [];
              for (var instance = targetInst, lastHostComponent; null !== instance; ) {
                var _instance2 = instance;
                lastHostComponent = _instance2.stateNode;
                _instance2 = _instance2.tag;
                5 !== _instance2 && 26 !== _instance2 && 27 !== _instance2 || null === lastHostComponent || null === reactEventName || (_instance2 = getListener(instance, reactEventName), null != _instance2 && inCapturePhase.push(
                  createDispatchListener(
                    instance,
                    _instance2,
                    lastHostComponent
                  )
                ));
                if (accumulateTargetOnly) break;
                instance = instance.return;
              }
              0 < inCapturePhase.length && (reactName = new SyntheticEventCtor(
                reactName,
                reactEventType,
                null,
                nativeEvent,
                nativeEventTarget
              ), dispatchQueue.push({
                event: reactName,
                listeners: inCapturePhase
              }));
            }
          }
          if (0 === (eventSystemFlags & 7)) {
            a: {
              reactName = "mouseover" === domEventName || "pointerover" === domEventName;
              SyntheticEventCtor = "mouseout" === domEventName || "pointerout" === domEventName;
              if (reactName && nativeEvent !== currentReplayingEvent && (reactEventType = nativeEvent.relatedTarget || nativeEvent.fromElement) && (getClosestInstanceFromNode(reactEventType) || reactEventType[internalContainerInstanceKey]))
                break a;
              if (SyntheticEventCtor || reactName) {
                reactName = nativeEventTarget.window === nativeEventTarget ? nativeEventTarget : (reactName = nativeEventTarget.ownerDocument) ? reactName.defaultView || reactName.parentWindow : window;
                if (SyntheticEventCtor) {
                  if (reactEventType = nativeEvent.relatedTarget || nativeEvent.toElement, SyntheticEventCtor = targetInst, reactEventType = reactEventType ? getClosestInstanceFromNode(reactEventType) : null, null !== reactEventType && (accumulateTargetOnly = getNearestMountedFiber(reactEventType), inCapturePhase = reactEventType.tag, reactEventType !== accumulateTargetOnly || 5 !== inCapturePhase && 27 !== inCapturePhase && 6 !== inCapturePhase))
                    reactEventType = null;
                } else SyntheticEventCtor = null, reactEventType = targetInst;
                if (SyntheticEventCtor !== reactEventType) {
                  inCapturePhase = SyntheticMouseEvent;
                  _instance2 = "onMouseLeave";
                  reactEventName = "onMouseEnter";
                  instance = "mouse";
                  if ("pointerout" === domEventName || "pointerover" === domEventName)
                    inCapturePhase = SyntheticPointerEvent, _instance2 = "onPointerLeave", reactEventName = "onPointerEnter", instance = "pointer";
                  accumulateTargetOnly = null == SyntheticEventCtor ? reactName : getNodeFromInstance(SyntheticEventCtor);
                  lastHostComponent = null == reactEventType ? reactName : getNodeFromInstance(reactEventType);
                  reactName = new inCapturePhase(
                    _instance2,
                    instance + "leave",
                    SyntheticEventCtor,
                    nativeEvent,
                    nativeEventTarget
                  );
                  reactName.target = accumulateTargetOnly;
                  reactName.relatedTarget = lastHostComponent;
                  _instance2 = null;
                  getClosestInstanceFromNode(nativeEventTarget) === targetInst && (inCapturePhase = new inCapturePhase(
                    reactEventName,
                    instance + "enter",
                    reactEventType,
                    nativeEvent,
                    nativeEventTarget
                  ), inCapturePhase.target = lastHostComponent, inCapturePhase.relatedTarget = accumulateTargetOnly, _instance2 = inCapturePhase);
                  accumulateTargetOnly = _instance2;
                  if (SyntheticEventCtor && reactEventType)
                    b: {
                      inCapturePhase = getParent;
                      reactEventName = SyntheticEventCtor;
                      instance = reactEventType;
                      lastHostComponent = 0;
                      for (_instance2 = reactEventName; _instance2; _instance2 = inCapturePhase(_instance2))
                        lastHostComponent++;
                      _instance2 = 0;
                      for (var tempB = instance; tempB; tempB = inCapturePhase(tempB))
                        _instance2++;
                      for (; 0 < lastHostComponent - _instance2; )
                        reactEventName = inCapturePhase(reactEventName), lastHostComponent--;
                      for (; 0 < _instance2 - lastHostComponent; )
                        instance = inCapturePhase(instance), _instance2--;
                      for (; lastHostComponent--; ) {
                        if (reactEventName === instance || null !== instance && reactEventName === instance.alternate) {
                          inCapturePhase = reactEventName;
                          break b;
                        }
                        reactEventName = inCapturePhase(reactEventName);
                        instance = inCapturePhase(instance);
                      }
                      inCapturePhase = null;
                    }
                  else inCapturePhase = null;
                  null !== SyntheticEventCtor && accumulateEnterLeaveListenersForEvent(
                    dispatchQueue,
                    reactName,
                    SyntheticEventCtor,
                    inCapturePhase,
                    false
                  );
                  null !== reactEventType && null !== accumulateTargetOnly && accumulateEnterLeaveListenersForEvent(
                    dispatchQueue,
                    accumulateTargetOnly,
                    reactEventType,
                    inCapturePhase,
                    true
                  );
                }
              }
            }
            a: {
              reactName = targetInst ? getNodeFromInstance(targetInst) : window;
              SyntheticEventCtor = reactName.nodeName && reactName.nodeName.toLowerCase();
              if ("select" === SyntheticEventCtor || "input" === SyntheticEventCtor && "file" === reactName.type)
                var getTargetInstFunc = getTargetInstForChangeEvent;
              else if (isTextInputElement(reactName))
                if (isInputEventSupported)
                  getTargetInstFunc = getTargetInstForInputOrChangeEvent;
                else {
                  getTargetInstFunc = getTargetInstForInputEventPolyfill;
                  var handleEventFunc = handleEventsForInputEventPolyfill;
                }
              else
                SyntheticEventCtor = reactName.nodeName, !SyntheticEventCtor || "input" !== SyntheticEventCtor.toLowerCase() || "checkbox" !== reactName.type && "radio" !== reactName.type ? targetInst && isCustomElement(targetInst.elementType) && (getTargetInstFunc = getTargetInstForChangeEvent) : getTargetInstFunc = getTargetInstForClickEvent;
              if (getTargetInstFunc && (getTargetInstFunc = getTargetInstFunc(domEventName, targetInst))) {
                createAndAccumulateChangeEvent(
                  dispatchQueue,
                  getTargetInstFunc,
                  nativeEvent,
                  nativeEventTarget
                );
                break a;
              }
              handleEventFunc && handleEventFunc(domEventName, reactName, targetInst);
              "focusout" === domEventName && targetInst && "number" === reactName.type && null != targetInst.memoizedProps.value && setDefaultValue(reactName, "number", reactName.value);
            }
            handleEventFunc = targetInst ? getNodeFromInstance(targetInst) : window;
            switch (domEventName) {
              case "focusin":
                if (isTextInputElement(handleEventFunc) || "true" === handleEventFunc.contentEditable)
                  activeElement = handleEventFunc, activeElementInst = targetInst, lastSelection = null;
                break;
              case "focusout":
                lastSelection = activeElementInst = activeElement = null;
                break;
              case "mousedown":
                mouseDown = true;
                break;
              case "contextmenu":
              case "mouseup":
              case "dragend":
                mouseDown = false;
                constructSelectEvent(
                  dispatchQueue,
                  nativeEvent,
                  nativeEventTarget
                );
                break;
              case "selectionchange":
                if (skipSelectionChangeEvent) break;
              case "keydown":
              case "keyup":
                constructSelectEvent(
                  dispatchQueue,
                  nativeEvent,
                  nativeEventTarget
                );
            }
            var fallbackData;
            if (canUseCompositionEvent)
              b: {
                switch (domEventName) {
                  case "compositionstart":
                    var eventType = "onCompositionStart";
                    break b;
                  case "compositionend":
                    eventType = "onCompositionEnd";
                    break b;
                  case "compositionupdate":
                    eventType = "onCompositionUpdate";
                    break b;
                }
                eventType = void 0;
              }
            else
              isComposing ? isFallbackCompositionEnd(domEventName, nativeEvent) && (eventType = "onCompositionEnd") : "keydown" === domEventName && nativeEvent.keyCode === START_KEYCODE && (eventType = "onCompositionStart");
            eventType && (useFallbackCompositionData && "ko" !== nativeEvent.locale && (isComposing || "onCompositionStart" !== eventType ? "onCompositionEnd" === eventType && isComposing && (fallbackData = getData()) : (root = nativeEventTarget, startText = "value" in root ? root.value : root.textContent, isComposing = true)), handleEventFunc = accumulateTwoPhaseListeners(
              targetInst,
              eventType
            ), 0 < handleEventFunc.length && (eventType = new SyntheticCompositionEvent(
              eventType,
              domEventName,
              null,
              nativeEvent,
              nativeEventTarget
            ), dispatchQueue.push({
              event: eventType,
              listeners: handleEventFunc
            }), fallbackData ? eventType.data = fallbackData : (fallbackData = getDataFromCustomEvent(nativeEvent), null !== fallbackData && (eventType.data = fallbackData))));
            if (fallbackData = canUseTextInputEvent ? getNativeBeforeInputChars(domEventName, nativeEvent) : getFallbackBeforeInputChars(domEventName, nativeEvent))
              eventType = accumulateTwoPhaseListeners(
                targetInst,
                "onBeforeInput"
              ), 0 < eventType.length && (handleEventFunc = new SyntheticInputEvent(
                "onBeforeInput",
                "beforeinput",
                null,
                nativeEvent,
                nativeEventTarget
              ), dispatchQueue.push({
                event: handleEventFunc,
                listeners: eventType
              }), handleEventFunc.data = fallbackData);
            extractEvents$1(
              dispatchQueue,
              domEventName,
              targetInst,
              nativeEvent,
              nativeEventTarget
            );
          }
          processDispatchQueue(dispatchQueue, eventSystemFlags);
        });
      }
      function createDispatchListener(instance, listener, currentTarget) {
        return {
          instance,
          listener,
          currentTarget
        };
      }
      function accumulateTwoPhaseListeners(targetFiber, reactName) {
        for (var captureName = reactName + "Capture", listeners2 = []; null !== targetFiber; ) {
          var _instance3 = targetFiber, stateNode = _instance3.stateNode;
          _instance3 = _instance3.tag;
          5 !== _instance3 && 26 !== _instance3 && 27 !== _instance3 || null === stateNode || (_instance3 = getListener(targetFiber, captureName), null != _instance3 && listeners2.unshift(
            createDispatchListener(targetFiber, _instance3, stateNode)
          ), _instance3 = getListener(targetFiber, reactName), null != _instance3 && listeners2.push(
            createDispatchListener(targetFiber, _instance3, stateNode)
          ));
          if (3 === targetFiber.tag) return listeners2;
          targetFiber = targetFiber.return;
        }
        return [];
      }
      function getParent(inst) {
        if (null === inst) return null;
        do
          inst = inst.return;
        while (inst && 5 !== inst.tag && 27 !== inst.tag);
        return inst ? inst : null;
      }
      function accumulateEnterLeaveListenersForEvent(dispatchQueue, event, target2, common, inCapturePhase) {
        for (var registrationName = event._reactName, listeners2 = []; null !== target2 && target2 !== common; ) {
          var _instance4 = target2, alternate = _instance4.alternate, stateNode = _instance4.stateNode;
          _instance4 = _instance4.tag;
          if (null !== alternate && alternate === common) break;
          5 !== _instance4 && 26 !== _instance4 && 27 !== _instance4 || null === stateNode || (alternate = stateNode, inCapturePhase ? (stateNode = getListener(target2, registrationName), null != stateNode && listeners2.unshift(
            createDispatchListener(target2, stateNode, alternate)
          )) : inCapturePhase || (stateNode = getListener(target2, registrationName), null != stateNode && listeners2.push(
            createDispatchListener(target2, stateNode, alternate)
          )));
          target2 = target2.return;
        }
        0 !== listeners2.length && dispatchQueue.push({ event, listeners: listeners2 });
      }
      function validatePropertiesInDevelopment(type, props) {
        validateProperties$2(type, props);
        "input" !== type && "textarea" !== type && "select" !== type || null == props || null !== props.value || didWarnValueNull || (didWarnValueNull = true, "select" === type && props.multiple ? console.error(
          "`value` prop on `%s` should not be null. Consider using an empty array when `multiple` is set to `true` to clear the component or `undefined` for uncontrolled components.",
          type
        ) : console.error(
          "`value` prop on `%s` should not be null. Consider using an empty string to clear the component or `undefined` for uncontrolled components.",
          type
        ));
        var eventRegistry = {
          registrationNameDependencies,
          possibleRegistrationNames
        };
        isCustomElement(type) || "string" === typeof props.is || warnUnknownProperties(type, props, eventRegistry);
        props.contentEditable && !props.suppressContentEditableWarning && null != props.children && console.error(
          "A component is `contentEditable` and contains `children` managed by React. It is now your responsibility to guarantee that none of those nodes are unexpectedly modified or duplicated. This is probably not intentional."
        );
      }
      function warnForPropDifference(propName, serverValue, clientValue, serverDifferences) {
        serverValue !== clientValue && (clientValue = normalizeMarkupForTextOrAttribute(clientValue), normalizeMarkupForTextOrAttribute(serverValue) !== clientValue && (serverDifferences[propName] = serverValue));
      }
      function warnForExtraAttributes(domElement, attributeNames, serverDifferences) {
        attributeNames.forEach(function(attributeName) {
          serverDifferences[getPropNameFromAttributeName(attributeName)] = "style" === attributeName ? getStylesObjectFromElement(domElement) : domElement.getAttribute(attributeName);
        });
      }
      function warnForInvalidEventListener(registrationName, listener) {
        false === listener ? console.error(
          "Expected `%s` listener to be a function, instead got `false`.\n\nIf you used to conditionally omit it with %s={condition && value}, pass %s={condition ? value : undefined} instead.",
          registrationName,
          registrationName,
          registrationName
        ) : console.error(
          "Expected `%s` listener to be a function, instead got a value of `%s` type.",
          registrationName,
          typeof listener
        );
      }
      function normalizeHTML(parent, html) {
        parent = parent.namespaceURI === MATH_NAMESPACE || parent.namespaceURI === SVG_NAMESPACE ? parent.ownerDocument.createElementNS(
          parent.namespaceURI,
          parent.tagName
        ) : parent.ownerDocument.createElement(parent.tagName);
        parent.innerHTML = html;
        return parent.innerHTML;
      }
      function normalizeMarkupForTextOrAttribute(markup) {
        willCoercionThrow(markup) && (console.error(
          "The provided HTML markup uses a value of unsupported type %s. This value must be coerced to a string before using it here.",
          typeName(markup)
        ), testStringCoercion(markup));
        return ("string" === typeof markup ? markup : "" + markup).replace(NORMALIZE_NEWLINES_REGEX, "\n").replace(NORMALIZE_NULL_AND_REPLACEMENT_REGEX, "");
      }
      function checkForUnmatchedText(serverText, clientText) {
        clientText = normalizeMarkupForTextOrAttribute(clientText);
        return normalizeMarkupForTextOrAttribute(serverText) === clientText ? true : false;
      }
      function setProp(domElement, tag, key, value, props, prevValue) {
        switch (key) {
          case "children":
            if ("string" === typeof value)
              validateTextNesting(value, tag, false), "body" === tag || "textarea" === tag && "" === value || setTextContent(domElement, value);
            else if ("number" === typeof value || "bigint" === typeof value)
              validateTextNesting("" + value, tag, false), "body" !== tag && setTextContent(domElement, "" + value);
            break;
          case "className":
            setValueForKnownAttribute(domElement, "class", value);
            break;
          case "tabIndex":
            setValueForKnownAttribute(domElement, "tabindex", value);
            break;
          case "dir":
          case "role":
          case "viewBox":
          case "width":
          case "height":
            setValueForKnownAttribute(domElement, key, value);
            break;
          case "style":
            setValueForStyles(domElement, value, prevValue);
            break;
          case "data":
            if ("object" !== tag) {
              setValueForKnownAttribute(domElement, "data", value);
              break;
            }
          case "src":
          case "href":
            if ("" === value && ("a" !== tag || "href" !== key)) {
              "src" === key ? console.error(
                'An empty string ("") was passed to the %s attribute. This may cause the browser to download the whole page again over the network. To fix this, either do not render the element at all or pass null to %s instead of an empty string.',
                key,
                key
              ) : console.error(
                'An empty string ("") was passed to the %s attribute. To fix this, either do not render the element at all or pass null to %s instead of an empty string.',
                key,
                key
              );
              domElement.removeAttribute(key);
              break;
            }
            if (null == value || "function" === typeof value || "symbol" === typeof value || "boolean" === typeof value) {
              domElement.removeAttribute(key);
              break;
            }
            checkAttributeStringCoercion(value, key);
            value = sanitizeURL("" + value);
            domElement.setAttribute(key, value);
            break;
          case "action":
          case "formAction":
            null != value && ("form" === tag ? "formAction" === key ? console.error(
              "You can only pass the formAction prop to <input> or <button>. Use the action prop on <form>."
            ) : "function" === typeof value && (null == props.encType && null == props.method || didWarnFormActionMethod || (didWarnFormActionMethod = true, console.error(
              "Cannot specify a encType or method for a form that specifies a function as the action. React provides those automatically. They will get overridden."
            )), null == props.target || didWarnFormActionTarget || (didWarnFormActionTarget = true, console.error(
              "Cannot specify a target for a form that specifies a function as the action. The function will always be executed in the same window."
            ))) : "input" === tag || "button" === tag ? "action" === key ? console.error(
              "You can only pass the action prop to <form>. Use the formAction prop on <input> or <button>."
            ) : "input" !== tag || "submit" === props.type || "image" === props.type || didWarnFormActionType ? "button" !== tag || null == props.type || "submit" === props.type || didWarnFormActionType ? "function" === typeof value && (null == props.name || didWarnFormActionName || (didWarnFormActionName = true, console.error(
              'Cannot specify a "name" prop for a button that specifies a function as a formAction. React needs it to encode which action should be invoked. It will get overridden.'
            )), null == props.formEncType && null == props.formMethod || didWarnFormActionMethod || (didWarnFormActionMethod = true, console.error(
              "Cannot specify a formEncType or formMethod for a button that specifies a function as a formAction. React provides those automatically. They will get overridden."
            )), null == props.formTarget || didWarnFormActionTarget || (didWarnFormActionTarget = true, console.error(
              "Cannot specify a formTarget for a button that specifies a function as a formAction. The function will always be executed in the same window."
            ))) : (didWarnFormActionType = true, console.error(
              'A button can only specify a formAction along with type="submit" or no type.'
            )) : (didWarnFormActionType = true, console.error(
              'An input can only specify a formAction along with type="submit" or type="image".'
            )) : "action" === key ? console.error(
              "You can only pass the action prop to <form>."
            ) : console.error(
              "You can only pass the formAction prop to <input> or <button>."
            ));
            if ("function" === typeof value) {
              domElement.setAttribute(
                key,
                "javascript:throw new Error('A React form was unexpectedly submitted. If you called form.submit() manually, consider using form.requestSubmit() instead. If you\\'re trying to use event.stopPropagation() in a submit event handler, consider also calling event.preventDefault().')"
              );
              break;
            } else
              "function" === typeof prevValue && ("formAction" === key ? ("input" !== tag && setProp(domElement, tag, "name", props.name, props, null), setProp(
                domElement,
                tag,
                "formEncType",
                props.formEncType,
                props,
                null
              ), setProp(
                domElement,
                tag,
                "formMethod",
                props.formMethod,
                props,
                null
              ), setProp(
                domElement,
                tag,
                "formTarget",
                props.formTarget,
                props,
                null
              )) : (setProp(
                domElement,
                tag,
                "encType",
                props.encType,
                props,
                null
              ), setProp(domElement, tag, "method", props.method, props, null), setProp(
                domElement,
                tag,
                "target",
                props.target,
                props,
                null
              )));
            if (null == value || "symbol" === typeof value || "boolean" === typeof value) {
              domElement.removeAttribute(key);
              break;
            }
            checkAttributeStringCoercion(value, key);
            value = sanitizeURL("" + value);
            domElement.setAttribute(key, value);
            break;
          case "onClick":
            null != value && ("function" !== typeof value && warnForInvalidEventListener(key, value), domElement.onclick = noop$1);
            break;
          case "onScroll":
            null != value && ("function" !== typeof value && warnForInvalidEventListener(key, value), listenToNonDelegatedEvent("scroll", domElement));
            break;
          case "onScrollEnd":
            null != value && ("function" !== typeof value && warnForInvalidEventListener(key, value), listenToNonDelegatedEvent("scrollend", domElement));
            break;
          case "dangerouslySetInnerHTML":
            if (null != value) {
              if ("object" !== typeof value || !("__html" in value))
                throw Error(
                  "`props.dangerouslySetInnerHTML` must be in the form `{__html: ...}`. Please visit https://react.dev/link/dangerously-set-inner-html for more information."
                );
              key = value.__html;
              if (null != key) {
                if (null != props.children)
                  throw Error(
                    "Can only set one of `children` or `props.dangerouslySetInnerHTML`."
                  );
                domElement.innerHTML = key;
              }
            }
            break;
          case "multiple":
            domElement.multiple = value && "function" !== typeof value && "symbol" !== typeof value;
            break;
          case "muted":
            domElement.muted = value && "function" !== typeof value && "symbol" !== typeof value;
            break;
          case "suppressContentEditableWarning":
          case "suppressHydrationWarning":
          case "defaultValue":
          case "defaultChecked":
          case "innerHTML":
          case "ref":
            break;
          case "autoFocus":
            break;
          case "xlinkHref":
            if (null == value || "function" === typeof value || "boolean" === typeof value || "symbol" === typeof value) {
              domElement.removeAttribute("xlink:href");
              break;
            }
            checkAttributeStringCoercion(value, key);
            key = sanitizeURL("" + value);
            domElement.setAttributeNS(xlinkNamespace, "xlink:href", key);
            break;
          case "contentEditable":
          case "spellCheck":
          case "draggable":
          case "value":
          case "autoReverse":
          case "externalResourcesRequired":
          case "focusable":
          case "preserveAlpha":
            null != value && "function" !== typeof value && "symbol" !== typeof value ? (checkAttributeStringCoercion(value, key), domElement.setAttribute(key, "" + value)) : domElement.removeAttribute(key);
            break;
          case "inert":
            "" !== value || didWarnForNewBooleanPropsWithEmptyValue[key] || (didWarnForNewBooleanPropsWithEmptyValue[key] = true, console.error(
              "Received an empty string for a boolean attribute `%s`. This will treat the attribute as if it were false. Either pass `false` to silence this warning, or pass `true` if you used an empty string in earlier versions of React to indicate this attribute is true.",
              key
            ));
          case "allowFullScreen":
          case "async":
          case "autoPlay":
          case "controls":
          case "default":
          case "defer":
          case "disabled":
          case "disablePictureInPicture":
          case "disableRemotePlayback":
          case "formNoValidate":
          case "hidden":
          case "loop":
          case "noModule":
          case "noValidate":
          case "open":
          case "playsInline":
          case "readOnly":
          case "required":
          case "reversed":
          case "scoped":
          case "seamless":
          case "itemScope":
            value && "function" !== typeof value && "symbol" !== typeof value ? domElement.setAttribute(key, "") : domElement.removeAttribute(key);
            break;
          case "capture":
          case "download":
            true === value ? domElement.setAttribute(key, "") : false !== value && null != value && "function" !== typeof value && "symbol" !== typeof value ? (checkAttributeStringCoercion(value, key), domElement.setAttribute(key, value)) : domElement.removeAttribute(key);
            break;
          case "cols":
          case "rows":
          case "size":
          case "span":
            null != value && "function" !== typeof value && "symbol" !== typeof value && !isNaN(value) && 1 <= value ? (checkAttributeStringCoercion(value, key), domElement.setAttribute(key, value)) : domElement.removeAttribute(key);
            break;
          case "rowSpan":
          case "start":
            null == value || "function" === typeof value || "symbol" === typeof value || isNaN(value) ? domElement.removeAttribute(key) : (checkAttributeStringCoercion(value, key), domElement.setAttribute(key, value));
            break;
          case "popover":
            listenToNonDelegatedEvent("beforetoggle", domElement);
            listenToNonDelegatedEvent("toggle", domElement);
            setValueForAttribute(domElement, "popover", value);
            break;
          case "xlinkActuate":
            setValueForNamespacedAttribute(
              domElement,
              xlinkNamespace,
              "xlink:actuate",
              value
            );
            break;
          case "xlinkArcrole":
            setValueForNamespacedAttribute(
              domElement,
              xlinkNamespace,
              "xlink:arcrole",
              value
            );
            break;
          case "xlinkRole":
            setValueForNamespacedAttribute(
              domElement,
              xlinkNamespace,
              "xlink:role",
              value
            );
            break;
          case "xlinkShow":
            setValueForNamespacedAttribute(
              domElement,
              xlinkNamespace,
              "xlink:show",
              value
            );
            break;
          case "xlinkTitle":
            setValueForNamespacedAttribute(
              domElement,
              xlinkNamespace,
              "xlink:title",
              value
            );
            break;
          case "xlinkType":
            setValueForNamespacedAttribute(
              domElement,
              xlinkNamespace,
              "xlink:type",
              value
            );
            break;
          case "xmlBase":
            setValueForNamespacedAttribute(
              domElement,
              xmlNamespace,
              "xml:base",
              value
            );
            break;
          case "xmlLang":
            setValueForNamespacedAttribute(
              domElement,
              xmlNamespace,
              "xml:lang",
              value
            );
            break;
          case "xmlSpace":
            setValueForNamespacedAttribute(
              domElement,
              xmlNamespace,
              "xml:space",
              value
            );
            break;
          case "is":
            null != prevValue && console.error(
              'Cannot update the "is" prop after it has been initialized.'
            );
            setValueForAttribute(domElement, "is", value);
            break;
          case "innerText":
          case "textContent":
            break;
          case "popoverTarget":
            didWarnPopoverTargetObject || null == value || "object" !== typeof value || (didWarnPopoverTargetObject = true, console.error(
              "The `popoverTarget` prop expects the ID of an Element as a string. Received %s instead.",
              value
            ));
          default:
            !(2 < key.length) || "o" !== key[0] && "O" !== key[0] || "n" !== key[1] && "N" !== key[1] ? (key = getAttributeAlias(key), setValueForAttribute(domElement, key, value)) : registrationNameDependencies.hasOwnProperty(key) && null != value && "function" !== typeof value && warnForInvalidEventListener(key, value);
        }
      }
      function setPropOnCustomElement(domElement, tag, key, value, props, prevValue) {
        switch (key) {
          case "style":
            setValueForStyles(domElement, value, prevValue);
            break;
          case "dangerouslySetInnerHTML":
            if (null != value) {
              if ("object" !== typeof value || !("__html" in value))
                throw Error(
                  "`props.dangerouslySetInnerHTML` must be in the form `{__html: ...}`. Please visit https://react.dev/link/dangerously-set-inner-html for more information."
                );
              key = value.__html;
              if (null != key) {
                if (null != props.children)
                  throw Error(
                    "Can only set one of `children` or `props.dangerouslySetInnerHTML`."
                  );
                domElement.innerHTML = key;
              }
            }
            break;
          case "children":
            "string" === typeof value ? setTextContent(domElement, value) : ("number" === typeof value || "bigint" === typeof value) && setTextContent(domElement, "" + value);
            break;
          case "onScroll":
            null != value && ("function" !== typeof value && warnForInvalidEventListener(key, value), listenToNonDelegatedEvent("scroll", domElement));
            break;
          case "onScrollEnd":
            null != value && ("function" !== typeof value && warnForInvalidEventListener(key, value), listenToNonDelegatedEvent("scrollend", domElement));
            break;
          case "onClick":
            null != value && ("function" !== typeof value && warnForInvalidEventListener(key, value), domElement.onclick = noop$1);
            break;
          case "suppressContentEditableWarning":
          case "suppressHydrationWarning":
          case "innerHTML":
          case "ref":
            break;
          case "innerText":
          case "textContent":
            break;
          default:
            if (registrationNameDependencies.hasOwnProperty(key))
              null != value && "function" !== typeof value && warnForInvalidEventListener(key, value);
            else
              a: {
                if ("o" === key[0] && "n" === key[1] && (props = key.endsWith("Capture"), tag = key.slice(2, props ? key.length - 7 : void 0), prevValue = domElement[internalPropsKey] || null, prevValue = null != prevValue ? prevValue[key] : null, "function" === typeof prevValue && domElement.removeEventListener(tag, prevValue, props), "function" === typeof value)) {
                  "function" !== typeof prevValue && null !== prevValue && (key in domElement ? domElement[key] = null : domElement.hasAttribute(key) && domElement.removeAttribute(key));
                  domElement.addEventListener(tag, value, props);
                  break a;
                }
                key in domElement ? domElement[key] = value : true === value ? domElement.setAttribute(key, "") : setValueForAttribute(domElement, key, value);
              }
        }
      }
      function setInitialProperties(domElement, tag, props) {
        validatePropertiesInDevelopment(tag, props);
        switch (tag) {
          case "div":
          case "span":
          case "svg":
          case "path":
          case "a":
          case "g":
          case "p":
          case "li":
            break;
          case "img":
            listenToNonDelegatedEvent("error", domElement);
            listenToNonDelegatedEvent("load", domElement);
            var hasSrc = false, hasSrcSet = false, propKey;
            for (propKey in props)
              if (props.hasOwnProperty(propKey)) {
                var propValue = props[propKey];
                if (null != propValue)
                  switch (propKey) {
                    case "src":
                      hasSrc = true;
                      break;
                    case "srcSet":
                      hasSrcSet = true;
                      break;
                    case "children":
                    case "dangerouslySetInnerHTML":
                      throw Error(
                        tag + " is a void element tag and must neither have `children` nor use `dangerouslySetInnerHTML`."
                      );
                    default:
                      setProp(domElement, tag, propKey, propValue, props, null);
                  }
              }
            hasSrcSet && setProp(domElement, tag, "srcSet", props.srcSet, props, null);
            hasSrc && setProp(domElement, tag, "src", props.src, props, null);
            return;
          case "input":
            checkControlledValueProps("input", props);
            listenToNonDelegatedEvent("invalid", domElement);
            var defaultValue = propKey = propValue = hasSrcSet = null, checked = null, defaultChecked = null;
            for (hasSrc in props)
              if (props.hasOwnProperty(hasSrc)) {
                var _propValue = props[hasSrc];
                if (null != _propValue)
                  switch (hasSrc) {
                    case "name":
                      hasSrcSet = _propValue;
                      break;
                    case "type":
                      propValue = _propValue;
                      break;
                    case "checked":
                      checked = _propValue;
                      break;
                    case "defaultChecked":
                      defaultChecked = _propValue;
                      break;
                    case "value":
                      propKey = _propValue;
                      break;
                    case "defaultValue":
                      defaultValue = _propValue;
                      break;
                    case "children":
                    case "dangerouslySetInnerHTML":
                      if (null != _propValue)
                        throw Error(
                          tag + " is a void element tag and must neither have `children` nor use `dangerouslySetInnerHTML`."
                        );
                      break;
                    default:
                      setProp(domElement, tag, hasSrc, _propValue, props, null);
                  }
              }
            validateInputProps(domElement, props);
            initInput2(
              domElement,
              propKey,
              defaultValue,
              checked,
              defaultChecked,
              propValue,
              hasSrcSet,
              false
            );
            return;
          case "select":
            checkControlledValueProps("select", props);
            listenToNonDelegatedEvent("invalid", domElement);
            hasSrc = propValue = propKey = null;
            for (hasSrcSet in props)
              if (props.hasOwnProperty(hasSrcSet) && (defaultValue = props[hasSrcSet], null != defaultValue))
                switch (hasSrcSet) {
                  case "value":
                    propKey = defaultValue;
                    break;
                  case "defaultValue":
                    propValue = defaultValue;
                    break;
                  case "multiple":
                    hasSrc = defaultValue;
                  default:
                    setProp(
                      domElement,
                      tag,
                      hasSrcSet,
                      defaultValue,
                      props,
                      null
                    );
                }
            validateSelectProps(domElement, props);
            tag = propKey;
            props = propValue;
            domElement.multiple = !!hasSrc;
            null != tag ? updateOptions(domElement, !!hasSrc, tag, false) : null != props && updateOptions(domElement, !!hasSrc, props, true);
            return;
          case "textarea":
            checkControlledValueProps("textarea", props);
            listenToNonDelegatedEvent("invalid", domElement);
            propKey = hasSrcSet = hasSrc = null;
            for (propValue in props)
              if (props.hasOwnProperty(propValue) && (defaultValue = props[propValue], null != defaultValue))
                switch (propValue) {
                  case "value":
                    hasSrc = defaultValue;
                    break;
                  case "defaultValue":
                    hasSrcSet = defaultValue;
                    break;
                  case "children":
                    propKey = defaultValue;
                    break;
                  case "dangerouslySetInnerHTML":
                    if (null != defaultValue)
                      throw Error(
                        "`dangerouslySetInnerHTML` does not make sense on <textarea>."
                      );
                    break;
                  default:
                    setProp(
                      domElement,
                      tag,
                      propValue,
                      defaultValue,
                      props,
                      null
                    );
                }
            validateTextareaProps(domElement, props);
            initTextarea(domElement, hasSrc, hasSrcSet, propKey);
            return;
          case "option":
            validateOptionProps(domElement, props);
            for (checked in props)
              if (props.hasOwnProperty(checked) && (hasSrc = props[checked], null != hasSrc))
                switch (checked) {
                  case "selected":
                    domElement.selected = hasSrc && "function" !== typeof hasSrc && "symbol" !== typeof hasSrc;
                    break;
                  default:
                    setProp(domElement, tag, checked, hasSrc, props, null);
                }
            return;
          case "dialog":
            listenToNonDelegatedEvent("beforetoggle", domElement);
            listenToNonDelegatedEvent("toggle", domElement);
            listenToNonDelegatedEvent("cancel", domElement);
            listenToNonDelegatedEvent("close", domElement);
            break;
          case "iframe":
          case "object":
            listenToNonDelegatedEvent("load", domElement);
            break;
          case "video":
          case "audio":
            for (hasSrc = 0; hasSrc < mediaEventTypes.length; hasSrc++)
              listenToNonDelegatedEvent(mediaEventTypes[hasSrc], domElement);
            break;
          case "image":
            listenToNonDelegatedEvent("error", domElement);
            listenToNonDelegatedEvent("load", domElement);
            break;
          case "details":
            listenToNonDelegatedEvent("toggle", domElement);
            break;
          case "embed":
          case "source":
          case "link":
            listenToNonDelegatedEvent("error", domElement), listenToNonDelegatedEvent("load", domElement);
          case "area":
          case "base":
          case "br":
          case "col":
          case "hr":
          case "keygen":
          case "meta":
          case "param":
          case "track":
          case "wbr":
          case "menuitem":
            for (defaultChecked in props)
              if (props.hasOwnProperty(defaultChecked) && (hasSrc = props[defaultChecked], null != hasSrc))
                switch (defaultChecked) {
                  case "children":
                  case "dangerouslySetInnerHTML":
                    throw Error(
                      tag + " is a void element tag and must neither have `children` nor use `dangerouslySetInnerHTML`."
                    );
                  default:
                    setProp(domElement, tag, defaultChecked, hasSrc, props, null);
                }
            return;
          default:
            if (isCustomElement(tag)) {
              for (_propValue in props)
                props.hasOwnProperty(_propValue) && (hasSrc = props[_propValue], void 0 !== hasSrc && setPropOnCustomElement(
                  domElement,
                  tag,
                  _propValue,
                  hasSrc,
                  props,
                  void 0
                ));
              return;
            }
        }
        for (defaultValue in props)
          props.hasOwnProperty(defaultValue) && (hasSrc = props[defaultValue], null != hasSrc && setProp(domElement, tag, defaultValue, hasSrc, props, null));
      }
      function updateProperties(domElement, tag, lastProps, nextProps) {
        validatePropertiesInDevelopment(tag, nextProps);
        switch (tag) {
          case "div":
          case "span":
          case "svg":
          case "path":
          case "a":
          case "g":
          case "p":
          case "li":
            break;
          case "input":
            var name = null, type = null, value = null, defaultValue = null, lastDefaultValue = null, checked = null, defaultChecked = null;
            for (propKey in lastProps) {
              var lastProp = lastProps[propKey];
              if (lastProps.hasOwnProperty(propKey) && null != lastProp)
                switch (propKey) {
                  case "checked":
                    break;
                  case "value":
                    break;
                  case "defaultValue":
                    lastDefaultValue = lastProp;
                  default:
                    nextProps.hasOwnProperty(propKey) || setProp(
                      domElement,
                      tag,
                      propKey,
                      null,
                      nextProps,
                      lastProp
                    );
                }
            }
            for (var _propKey8 in nextProps) {
              var propKey = nextProps[_propKey8];
              lastProp = lastProps[_propKey8];
              if (nextProps.hasOwnProperty(_propKey8) && (null != propKey || null != lastProp))
                switch (_propKey8) {
                  case "type":
                    type = propKey;
                    break;
                  case "name":
                    name = propKey;
                    break;
                  case "checked":
                    checked = propKey;
                    break;
                  case "defaultChecked":
                    defaultChecked = propKey;
                    break;
                  case "value":
                    value = propKey;
                    break;
                  case "defaultValue":
                    defaultValue = propKey;
                    break;
                  case "children":
                  case "dangerouslySetInnerHTML":
                    if (null != propKey)
                      throw Error(
                        tag + " is a void element tag and must neither have `children` nor use `dangerouslySetInnerHTML`."
                      );
                    break;
                  default:
                    propKey !== lastProp && setProp(
                      domElement,
                      tag,
                      _propKey8,
                      propKey,
                      nextProps,
                      lastProp
                    );
                }
            }
            tag = "checkbox" === lastProps.type || "radio" === lastProps.type ? null != lastProps.checked : null != lastProps.value;
            nextProps = "checkbox" === nextProps.type || "radio" === nextProps.type ? null != nextProps.checked : null != nextProps.value;
            tag || !nextProps || didWarnUncontrolledToControlled || (console.error(
              "A component is changing an uncontrolled input to be controlled. This is likely caused by the value changing from undefined to a defined value, which should not happen. Decide between using a controlled or uncontrolled input element for the lifetime of the component. More info: https://react.dev/link/controlled-components"
            ), didWarnUncontrolledToControlled = true);
            !tag || nextProps || didWarnControlledToUncontrolled || (console.error(
              "A component is changing a controlled input to be uncontrolled. This is likely caused by the value changing from a defined to undefined, which should not happen. Decide between using a controlled or uncontrolled input element for the lifetime of the component. More info: https://react.dev/link/controlled-components"
            ), didWarnControlledToUncontrolled = true);
            updateInput(
              domElement,
              value,
              defaultValue,
              lastDefaultValue,
              checked,
              defaultChecked,
              type,
              name
            );
            return;
          case "select":
            propKey = value = defaultValue = _propKey8 = null;
            for (type in lastProps)
              if (lastDefaultValue = lastProps[type], lastProps.hasOwnProperty(type) && null != lastDefaultValue)
                switch (type) {
                  case "value":
                    break;
                  case "multiple":
                    propKey = lastDefaultValue;
                  default:
                    nextProps.hasOwnProperty(type) || setProp(
                      domElement,
                      tag,
                      type,
                      null,
                      nextProps,
                      lastDefaultValue
                    );
                }
            for (name in nextProps)
              if (type = nextProps[name], lastDefaultValue = lastProps[name], nextProps.hasOwnProperty(name) && (null != type || null != lastDefaultValue))
                switch (name) {
                  case "value":
                    _propKey8 = type;
                    break;
                  case "defaultValue":
                    defaultValue = type;
                    break;
                  case "multiple":
                    value = type;
                  default:
                    type !== lastDefaultValue && setProp(
                      domElement,
                      tag,
                      name,
                      type,
                      nextProps,
                      lastDefaultValue
                    );
                }
            nextProps = defaultValue;
            tag = value;
            lastProps = propKey;
            null != _propKey8 ? updateOptions(domElement, !!tag, _propKey8, false) : !!lastProps !== !!tag && (null != nextProps ? updateOptions(domElement, !!tag, nextProps, true) : updateOptions(domElement, !!tag, tag ? [] : "", false));
            return;
          case "textarea":
            propKey = _propKey8 = null;
            for (defaultValue in lastProps)
              if (name = lastProps[defaultValue], lastProps.hasOwnProperty(defaultValue) && null != name && !nextProps.hasOwnProperty(defaultValue))
                switch (defaultValue) {
                  case "value":
                    break;
                  case "children":
                    break;
                  default:
                    setProp(domElement, tag, defaultValue, null, nextProps, name);
                }
            for (value in nextProps)
              if (name = nextProps[value], type = lastProps[value], nextProps.hasOwnProperty(value) && (null != name || null != type))
                switch (value) {
                  case "value":
                    _propKey8 = name;
                    break;
                  case "defaultValue":
                    propKey = name;
                    break;
                  case "children":
                    break;
                  case "dangerouslySetInnerHTML":
                    if (null != name)
                      throw Error(
                        "`dangerouslySetInnerHTML` does not make sense on <textarea>."
                      );
                    break;
                  default:
                    name !== type && setProp(domElement, tag, value, name, nextProps, type);
                }
            updateTextarea(domElement, _propKey8, propKey);
            return;
          case "option":
            for (var _propKey13 in lastProps)
              if (_propKey8 = lastProps[_propKey13], lastProps.hasOwnProperty(_propKey13) && null != _propKey8 && !nextProps.hasOwnProperty(_propKey13))
                switch (_propKey13) {
                  case "selected":
                    domElement.selected = false;
                    break;
                  default:
                    setProp(
                      domElement,
                      tag,
                      _propKey13,
                      null,
                      nextProps,
                      _propKey8
                    );
                }
            for (lastDefaultValue in nextProps)
              if (_propKey8 = nextProps[lastDefaultValue], propKey = lastProps[lastDefaultValue], nextProps.hasOwnProperty(lastDefaultValue) && _propKey8 !== propKey && (null != _propKey8 || null != propKey))
                switch (lastDefaultValue) {
                  case "selected":
                    domElement.selected = _propKey8 && "function" !== typeof _propKey8 && "symbol" !== typeof _propKey8;
                    break;
                  default:
                    setProp(
                      domElement,
                      tag,
                      lastDefaultValue,
                      _propKey8,
                      nextProps,
                      propKey
                    );
                }
            return;
          case "img":
          case "link":
          case "area":
          case "base":
          case "br":
          case "col":
          case "embed":
          case "hr":
          case "keygen":
          case "meta":
          case "param":
          case "source":
          case "track":
          case "wbr":
          case "menuitem":
            for (var _propKey15 in lastProps)
              _propKey8 = lastProps[_propKey15], lastProps.hasOwnProperty(_propKey15) && null != _propKey8 && !nextProps.hasOwnProperty(_propKey15) && setProp(
                domElement,
                tag,
                _propKey15,
                null,
                nextProps,
                _propKey8
              );
            for (checked in nextProps)
              if (_propKey8 = nextProps[checked], propKey = lastProps[checked], nextProps.hasOwnProperty(checked) && _propKey8 !== propKey && (null != _propKey8 || null != propKey))
                switch (checked) {
                  case "children":
                  case "dangerouslySetInnerHTML":
                    if (null != _propKey8)
                      throw Error(
                        tag + " is a void element tag and must neither have `children` nor use `dangerouslySetInnerHTML`."
                      );
                    break;
                  default:
                    setProp(
                      domElement,
                      tag,
                      checked,
                      _propKey8,
                      nextProps,
                      propKey
                    );
                }
            return;
          default:
            if (isCustomElement(tag)) {
              for (var _propKey17 in lastProps)
                _propKey8 = lastProps[_propKey17], lastProps.hasOwnProperty(_propKey17) && void 0 !== _propKey8 && !nextProps.hasOwnProperty(_propKey17) && setPropOnCustomElement(
                  domElement,
                  tag,
                  _propKey17,
                  void 0,
                  nextProps,
                  _propKey8
                );
              for (defaultChecked in nextProps)
                _propKey8 = nextProps[defaultChecked], propKey = lastProps[defaultChecked], !nextProps.hasOwnProperty(defaultChecked) || _propKey8 === propKey || void 0 === _propKey8 && void 0 === propKey || setPropOnCustomElement(
                  domElement,
                  tag,
                  defaultChecked,
                  _propKey8,
                  nextProps,
                  propKey
                );
              return;
            }
        }
        for (var _propKey19 in lastProps)
          _propKey8 = lastProps[_propKey19], lastProps.hasOwnProperty(_propKey19) && null != _propKey8 && !nextProps.hasOwnProperty(_propKey19) && setProp(domElement, tag, _propKey19, null, nextProps, _propKey8);
        for (lastProp in nextProps)
          _propKey8 = nextProps[lastProp], propKey = lastProps[lastProp], !nextProps.hasOwnProperty(lastProp) || _propKey8 === propKey || null == _propKey8 && null == propKey || setProp(domElement, tag, lastProp, _propKey8, nextProps, propKey);
      }
      function getPropNameFromAttributeName(attrName) {
        switch (attrName) {
          case "class":
            return "className";
          case "for":
            return "htmlFor";
          default:
            return attrName;
        }
      }
      function getStylesObjectFromElement(domElement) {
        var serverValueInObjectForm = {};
        domElement = domElement.style;
        for (var i = 0; i < domElement.length; i++) {
          var styleName = domElement[i];
          serverValueInObjectForm[styleName] = domElement.getPropertyValue(styleName);
        }
        return serverValueInObjectForm;
      }
      function diffHydratedStyles(domElement, value$jscomp$0, serverDifferences) {
        if (null != value$jscomp$0 && "object" !== typeof value$jscomp$0)
          console.error(
            "The `style` prop expects a mapping from style properties to values, not a string. For example, style={{marginRight: spacing + 'em'}} when using JSX."
          );
        else {
          var clientValue;
          var delimiter2 = clientValue = "", styleName;
          for (styleName in value$jscomp$0)
            if (value$jscomp$0.hasOwnProperty(styleName)) {
              var value = value$jscomp$0[styleName];
              null != value && "boolean" !== typeof value && "" !== value && (0 === styleName.indexOf("--") ? (checkCSSPropertyStringCoercion(value, styleName), clientValue += delimiter2 + styleName + ":" + ("" + value).trim()) : "number" !== typeof value || 0 === value || unitlessNumbers.has(styleName) ? (checkCSSPropertyStringCoercion(value, styleName), clientValue += delimiter2 + styleName.replace(uppercasePattern, "-$1").toLowerCase().replace(msPattern$1, "-ms-") + ":" + ("" + value).trim()) : clientValue += delimiter2 + styleName.replace(uppercasePattern, "-$1").toLowerCase().replace(msPattern$1, "-ms-") + ":" + value + "px", delimiter2 = ";");
            }
          clientValue = clientValue || null;
          value$jscomp$0 = domElement.getAttribute("style");
          value$jscomp$0 !== clientValue && (clientValue = normalizeMarkupForTextOrAttribute(clientValue), normalizeMarkupForTextOrAttribute(value$jscomp$0) !== clientValue && (serverDifferences.style = getStylesObjectFromElement(domElement)));
        }
      }
      function hydrateAttribute(domElement, propKey, attributeName, value, extraAttributes, serverDifferences) {
        extraAttributes.delete(attributeName);
        domElement = domElement.getAttribute(attributeName);
        if (null === domElement)
          switch (typeof value) {
            case "undefined":
            case "function":
            case "symbol":
            case "boolean":
              return;
          }
        else if (null != value)
          switch (typeof value) {
            case "function":
            case "symbol":
            case "boolean":
              break;
            default:
              if (checkAttributeStringCoercion(value, propKey), domElement === "" + value)
                return;
          }
        warnForPropDifference(propKey, domElement, value, serverDifferences);
      }
      function hydrateBooleanAttribute(domElement, propKey, attributeName, value, extraAttributes, serverDifferences) {
        extraAttributes.delete(attributeName);
        domElement = domElement.getAttribute(attributeName);
        if (null === domElement) {
          switch (typeof value) {
            case "function":
            case "symbol":
              return;
          }
          if (!value) return;
        } else
          switch (typeof value) {
            case "function":
            case "symbol":
              break;
            default:
              if (value) return;
          }
        warnForPropDifference(propKey, domElement, value, serverDifferences);
      }
      function hydrateBooleanishAttribute(domElement, propKey, attributeName, value, extraAttributes, serverDifferences) {
        extraAttributes.delete(attributeName);
        domElement = domElement.getAttribute(attributeName);
        if (null === domElement)
          switch (typeof value) {
            case "undefined":
            case "function":
            case "symbol":
              return;
          }
        else if (null != value)
          switch (typeof value) {
            case "function":
            case "symbol":
              break;
            default:
              if (checkAttributeStringCoercion(value, attributeName), domElement === "" + value)
                return;
          }
        warnForPropDifference(propKey, domElement, value, serverDifferences);
      }
      function hydrateNumericAttribute(domElement, propKey, attributeName, value, extraAttributes, serverDifferences) {
        extraAttributes.delete(attributeName);
        domElement = domElement.getAttribute(attributeName);
        if (null === domElement)
          switch (typeof value) {
            case "undefined":
            case "function":
            case "symbol":
            case "boolean":
              return;
            default:
              if (isNaN(value)) return;
          }
        else if (null != value)
          switch (typeof value) {
            case "function":
            case "symbol":
            case "boolean":
              break;
            default:
              if (!isNaN(value) && (checkAttributeStringCoercion(value, propKey), domElement === "" + value))
                return;
          }
        warnForPropDifference(propKey, domElement, value, serverDifferences);
      }
      function hydrateSanitizedAttribute(domElement, propKey, attributeName, value, extraAttributes, serverDifferences) {
        extraAttributes.delete(attributeName);
        domElement = domElement.getAttribute(attributeName);
        if (null === domElement)
          switch (typeof value) {
            case "undefined":
            case "function":
            case "symbol":
            case "boolean":
              return;
          }
        else if (null != value)
          switch (typeof value) {
            case "function":
            case "symbol":
            case "boolean":
              break;
            default:
              if (checkAttributeStringCoercion(value, propKey), attributeName = sanitizeURL("" + value), domElement === attributeName)
                return;
          }
        warnForPropDifference(propKey, domElement, value, serverDifferences);
      }
      function diffHydratedProperties(domElement, tag, props, hostContext) {
        for (var serverDifferences = {}, extraAttributes = /* @__PURE__ */ new Set(), attributes = domElement.attributes, i = 0; i < attributes.length; i++)
          switch (attributes[i].name.toLowerCase()) {
            case "value":
              break;
            case "checked":
              break;
            case "selected":
              break;
            default:
              extraAttributes.add(attributes[i].name);
          }
        if (isCustomElement(tag))
          for (var propKey in props) {
            if (props.hasOwnProperty(propKey)) {
              var value = props[propKey];
              if (null != value) {
                if (registrationNameDependencies.hasOwnProperty(propKey))
                  "function" !== typeof value && warnForInvalidEventListener(propKey, value);
                else if (true !== props.suppressHydrationWarning)
                  switch (propKey) {
                    case "children":
                      "string" !== typeof value && "number" !== typeof value || warnForPropDifference(
                        "children",
                        domElement.textContent,
                        value,
                        serverDifferences
                      );
                      continue;
                    case "suppressContentEditableWarning":
                    case "suppressHydrationWarning":
                    case "defaultValue":
                    case "defaultChecked":
                    case "innerHTML":
                    case "ref":
                      continue;
                    case "dangerouslySetInnerHTML":
                      attributes = domElement.innerHTML;
                      value = value ? value.__html : void 0;
                      null != value && (value = normalizeHTML(domElement, value), warnForPropDifference(
                        propKey,
                        attributes,
                        value,
                        serverDifferences
                      ));
                      continue;
                    case "style":
                      extraAttributes.delete(propKey);
                      diffHydratedStyles(domElement, value, serverDifferences);
                      continue;
                    case "offsetParent":
                    case "offsetTop":
                    case "offsetLeft":
                    case "offsetWidth":
                    case "offsetHeight":
                    case "isContentEditable":
                    case "outerText":
                    case "outerHTML":
                      extraAttributes.delete(propKey.toLowerCase());
                      console.error(
                        "Assignment to read-only property will result in a no-op: `%s`",
                        propKey
                      );
                      continue;
                    case "className":
                      extraAttributes.delete("class");
                      attributes = getValueForAttributeOnCustomComponent(
                        domElement,
                        "class",
                        value
                      );
                      warnForPropDifference(
                        "className",
                        attributes,
                        value,
                        serverDifferences
                      );
                      continue;
                    default:
                      hostContext.context === HostContextNamespaceNone && "svg" !== tag && "math" !== tag ? extraAttributes.delete(propKey.toLowerCase()) : extraAttributes.delete(propKey), attributes = getValueForAttributeOnCustomComponent(
                        domElement,
                        propKey,
                        value
                      ), warnForPropDifference(
                        propKey,
                        attributes,
                        value,
                        serverDifferences
                      );
                  }
              }
            }
          }
        else
          for (value in props)
            if (props.hasOwnProperty(value) && (propKey = props[value], null != propKey)) {
              if (registrationNameDependencies.hasOwnProperty(value))
                "function" !== typeof propKey && warnForInvalidEventListener(value, propKey);
              else if (true !== props.suppressHydrationWarning)
                switch (value) {
                  case "children":
                    "string" !== typeof propKey && "number" !== typeof propKey || warnForPropDifference(
                      "children",
                      domElement.textContent,
                      propKey,
                      serverDifferences
                    );
                    continue;
                  case "suppressContentEditableWarning":
                  case "suppressHydrationWarning":
                  case "value":
                  case "checked":
                  case "selected":
                  case "defaultValue":
                  case "defaultChecked":
                  case "innerHTML":
                  case "ref":
                    continue;
                  case "dangerouslySetInnerHTML":
                    attributes = domElement.innerHTML;
                    propKey = propKey ? propKey.__html : void 0;
                    null != propKey && (propKey = normalizeHTML(domElement, propKey), attributes !== propKey && (serverDifferences[value] = { __html: attributes }));
                    continue;
                  case "className":
                    hydrateAttribute(
                      domElement,
                      value,
                      "class",
                      propKey,
                      extraAttributes,
                      serverDifferences
                    );
                    continue;
                  case "tabIndex":
                    hydrateAttribute(
                      domElement,
                      value,
                      "tabindex",
                      propKey,
                      extraAttributes,
                      serverDifferences
                    );
                    continue;
                  case "style":
                    extraAttributes.delete(value);
                    diffHydratedStyles(domElement, propKey, serverDifferences);
                    continue;
                  case "multiple":
                    extraAttributes.delete(value);
                    warnForPropDifference(
                      value,
                      domElement.multiple,
                      propKey,
                      serverDifferences
                    );
                    continue;
                  case "muted":
                    extraAttributes.delete(value);
                    warnForPropDifference(
                      value,
                      domElement.muted,
                      propKey,
                      serverDifferences
                    );
                    continue;
                  case "autoFocus":
                    extraAttributes.delete("autofocus");
                    warnForPropDifference(
                      value,
                      domElement.autofocus,
                      propKey,
                      serverDifferences
                    );
                    continue;
                  case "data":
                    if ("object" !== tag) {
                      extraAttributes.delete(value);
                      attributes = domElement.getAttribute("data");
                      warnForPropDifference(
                        value,
                        attributes,
                        propKey,
                        serverDifferences
                      );
                      continue;
                    }
                  case "src":
                  case "href":
                    if (!("" !== propKey || "a" === tag && "href" === value || "object" === tag && "data" === value)) {
                      "src" === value ? console.error(
                        'An empty string ("") was passed to the %s attribute. This may cause the browser to download the whole page again over the network. To fix this, either do not render the element at all or pass null to %s instead of an empty string.',
                        value,
                        value
                      ) : console.error(
                        'An empty string ("") was passed to the %s attribute. To fix this, either do not render the element at all or pass null to %s instead of an empty string.',
                        value,
                        value
                      );
                      continue;
                    }
                    hydrateSanitizedAttribute(
                      domElement,
                      value,
                      value,
                      propKey,
                      extraAttributes,
                      serverDifferences
                    );
                    continue;
                  case "action":
                  case "formAction":
                    attributes = domElement.getAttribute(value);
                    if ("function" === typeof propKey) {
                      extraAttributes.delete(value.toLowerCase());
                      "formAction" === value ? (extraAttributes.delete("name"), extraAttributes.delete("formenctype"), extraAttributes.delete("formmethod"), extraAttributes.delete("formtarget")) : (extraAttributes.delete("enctype"), extraAttributes.delete("method"), extraAttributes.delete("target"));
                      continue;
                    } else if (attributes === EXPECTED_FORM_ACTION_URL) {
                      extraAttributes.delete(value.toLowerCase());
                      warnForPropDifference(
                        value,
                        "function",
                        propKey,
                        serverDifferences
                      );
                      continue;
                    }
                    hydrateSanitizedAttribute(
                      domElement,
                      value,
                      value.toLowerCase(),
                      propKey,
                      extraAttributes,
                      serverDifferences
                    );
                    continue;
                  case "xlinkHref":
                    hydrateSanitizedAttribute(
                      domElement,
                      value,
                      "xlink:href",
                      propKey,
                      extraAttributes,
                      serverDifferences
                    );
                    continue;
                  case "contentEditable":
                    hydrateBooleanishAttribute(
                      domElement,
                      value,
                      "contenteditable",
                      propKey,
                      extraAttributes,
                      serverDifferences
                    );
                    continue;
                  case "spellCheck":
                    hydrateBooleanishAttribute(
                      domElement,
                      value,
                      "spellcheck",
                      propKey,
                      extraAttributes,
                      serverDifferences
                    );
                    continue;
                  case "draggable":
                  case "autoReverse":
                  case "externalResourcesRequired":
                  case "focusable":
                  case "preserveAlpha":
                    hydrateBooleanishAttribute(
                      domElement,
                      value,
                      value,
                      propKey,
                      extraAttributes,
                      serverDifferences
                    );
                    continue;
                  case "allowFullScreen":
                  case "async":
                  case "autoPlay":
                  case "controls":
                  case "default":
                  case "defer":
                  case "disabled":
                  case "disablePictureInPicture":
                  case "disableRemotePlayback":
                  case "formNoValidate":
                  case "hidden":
                  case "loop":
                  case "noModule":
                  case "noValidate":
                  case "open":
                  case "playsInline":
                  case "readOnly":
                  case "required":
                  case "reversed":
                  case "scoped":
                  case "seamless":
                  case "itemScope":
                    hydrateBooleanAttribute(
                      domElement,
                      value,
                      value.toLowerCase(),
                      propKey,
                      extraAttributes,
                      serverDifferences
                    );
                    continue;
                  case "capture":
                  case "download":
                    a: {
                      i = domElement;
                      var attributeName = attributes = value, serverDifferences$jscomp$0 = serverDifferences;
                      extraAttributes.delete(attributeName);
                      i = i.getAttribute(attributeName);
                      if (null === i)
                        switch (typeof propKey) {
                          case "undefined":
                          case "function":
                          case "symbol":
                            break a;
                          default:
                            if (false === propKey) break a;
                        }
                      else if (null != propKey)
                        switch (typeof propKey) {
                          case "function":
                          case "symbol":
                            break;
                          case "boolean":
                            if (true === propKey && "" === i) break a;
                            break;
                          default:
                            if (checkAttributeStringCoercion(propKey, attributes), i === "" + propKey)
                              break a;
                        }
                      warnForPropDifference(
                        attributes,
                        i,
                        propKey,
                        serverDifferences$jscomp$0
                      );
                    }
                    continue;
                  case "cols":
                  case "rows":
                  case "size":
                  case "span":
                    a: {
                      i = domElement;
                      attributeName = attributes = value;
                      serverDifferences$jscomp$0 = serverDifferences;
                      extraAttributes.delete(attributeName);
                      i = i.getAttribute(attributeName);
                      if (null === i)
                        switch (typeof propKey) {
                          case "undefined":
                          case "function":
                          case "symbol":
                          case "boolean":
                            break a;
                          default:
                            if (isNaN(propKey) || 1 > propKey) break a;
                        }
                      else if (null != propKey)
                        switch (typeof propKey) {
                          case "function":
                          case "symbol":
                          case "boolean":
                            break;
                          default:
                            if (!(isNaN(propKey) || 1 > propKey) && (checkAttributeStringCoercion(propKey, attributes), i === "" + propKey))
                              break a;
                        }
                      warnForPropDifference(
                        attributes,
                        i,
                        propKey,
                        serverDifferences$jscomp$0
                      );
                    }
                    continue;
                  case "rowSpan":
                    hydrateNumericAttribute(
                      domElement,
                      value,
                      "rowspan",
                      propKey,
                      extraAttributes,
                      serverDifferences
                    );
                    continue;
                  case "start":
                    hydrateNumericAttribute(
                      domElement,
                      value,
                      value,
                      propKey,
                      extraAttributes,
                      serverDifferences
                    );
                    continue;
                  case "xHeight":
                    hydrateAttribute(
                      domElement,
                      value,
                      "x-height",
                      propKey,
                      extraAttributes,
                      serverDifferences
                    );
                    continue;
                  case "xlinkActuate":
                    hydrateAttribute(
                      domElement,
                      value,
                      "xlink:actuate",
                      propKey,
                      extraAttributes,
                      serverDifferences
                    );
                    continue;
                  case "xlinkArcrole":
                    hydrateAttribute(
                      domElement,
                      value,
                      "xlink:arcrole",
                      propKey,
                      extraAttributes,
                      serverDifferences
                    );
                    continue;
                  case "xlinkRole":
                    hydrateAttribute(
                      domElement,
                      value,
                      "xlink:role",
                      propKey,
                      extraAttributes,
                      serverDifferences
                    );
                    continue;
                  case "xlinkShow":
                    hydrateAttribute(
                      domElement,
                      value,
                      "xlink:show",
                      propKey,
                      extraAttributes,
                      serverDifferences
                    );
                    continue;
                  case "xlinkTitle":
                    hydrateAttribute(
                      domElement,
                      value,
                      "xlink:title",
                      propKey,
                      extraAttributes,
                      serverDifferences
                    );
                    continue;
                  case "xlinkType":
                    hydrateAttribute(
                      domElement,
                      value,
                      "xlink:type",
                      propKey,
                      extraAttributes,
                      serverDifferences
                    );
                    continue;
                  case "xmlBase":
                    hydrateAttribute(
                      domElement,
                      value,
                      "xml:base",
                      propKey,
                      extraAttributes,
                      serverDifferences
                    );
                    continue;
                  case "xmlLang":
                    hydrateAttribute(
                      domElement,
                      value,
                      "xml:lang",
                      propKey,
                      extraAttributes,
                      serverDifferences
                    );
                    continue;
                  case "xmlSpace":
                    hydrateAttribute(
                      domElement,
                      value,
                      "xml:space",
                      propKey,
                      extraAttributes,
                      serverDifferences
                    );
                    continue;
                  case "inert":
                    "" !== propKey || didWarnForNewBooleanPropsWithEmptyValue[value] || (didWarnForNewBooleanPropsWithEmptyValue[value] = true, console.error(
                      "Received an empty string for a boolean attribute `%s`. This will treat the attribute as if it were false. Either pass `false` to silence this warning, or pass `true` if you used an empty string in earlier versions of React to indicate this attribute is true.",
                      value
                    ));
                    hydrateBooleanAttribute(
                      domElement,
                      value,
                      value,
                      propKey,
                      extraAttributes,
                      serverDifferences
                    );
                    continue;
                  default:
                    if (!(2 < value.length) || "o" !== value[0] && "O" !== value[0] || "n" !== value[1] && "N" !== value[1]) {
                      i = getAttributeAlias(value);
                      attributes = false;
                      hostContext.context === HostContextNamespaceNone && "svg" !== tag && "math" !== tag ? extraAttributes.delete(i.toLowerCase()) : (attributeName = value.toLowerCase(), attributeName = possibleStandardNames.hasOwnProperty(
                        attributeName
                      ) ? possibleStandardNames[attributeName] || null : null, null !== attributeName && attributeName !== value && (attributes = true, extraAttributes.delete(attributeName)), extraAttributes.delete(i));
                      a: if (attributeName = domElement, serverDifferences$jscomp$0 = i, i = propKey, isAttributeNameSafe(serverDifferences$jscomp$0))
                        if (attributeName.hasAttribute(serverDifferences$jscomp$0))
                          attributeName = attributeName.getAttribute(
                            serverDifferences$jscomp$0
                          ), checkAttributeStringCoercion(
                            i,
                            serverDifferences$jscomp$0
                          ), i = attributeName === "" + i ? i : attributeName;
                        else {
                          switch (typeof i) {
                            case "function":
                            case "symbol":
                              break a;
                            case "boolean":
                              if (attributeName = serverDifferences$jscomp$0.toLowerCase().slice(0, 5), "data-" !== attributeName && "aria-" !== attributeName)
                                break a;
                          }
                          i = void 0 === i ? void 0 : null;
                        }
                      else i = void 0;
                      attributes || warnForPropDifference(
                        value,
                        i,
                        propKey,
                        serverDifferences
                      );
                    }
                }
            }
        0 < extraAttributes.size && true !== props.suppressHydrationWarning && warnForExtraAttributes(domElement, extraAttributes, serverDifferences);
        return 0 === Object.keys(serverDifferences).length ? null : serverDifferences;
      }
      function propNamesListJoin(list, combinator) {
        switch (list.length) {
          case 0:
            return "";
          case 1:
            return list[0];
          case 2:
            return list[0] + " " + combinator + " " + list[1];
          default:
            return list.slice(0, -1).join(", ") + ", " + combinator + " " + list[list.length - 1];
        }
      }
      function isLikelyStaticResource(initiatorType) {
        switch (initiatorType) {
          case "css":
          case "script":
          case "font":
          case "img":
          case "image":
          case "input":
          case "link":
            return true;
          default:
            return false;
        }
      }
      function estimateBandwidth() {
        if ("function" === typeof performance.getEntriesByType) {
          for (var count = 0, bits = 0, resourceEntries = performance.getEntriesByType("resource"), i = 0; i < resourceEntries.length; i++) {
            var entry = resourceEntries[i], transferSize = entry.transferSize, initiatorType = entry.initiatorType, duration = entry.duration;
            if (transferSize && duration && isLikelyStaticResource(initiatorType)) {
              initiatorType = 0;
              duration = entry.responseEnd;
              for (i += 1; i < resourceEntries.length; i++) {
                var overlapEntry = resourceEntries[i], overlapStartTime = overlapEntry.startTime;
                if (overlapStartTime > duration) break;
                var overlapTransferSize = overlapEntry.transferSize, overlapInitiatorType = overlapEntry.initiatorType;
                overlapTransferSize && isLikelyStaticResource(overlapInitiatorType) && (overlapEntry = overlapEntry.responseEnd, initiatorType += overlapTransferSize * (overlapEntry < duration ? 1 : (duration - overlapStartTime) / (overlapEntry - overlapStartTime)));
              }
              --i;
              bits += 8 * (transferSize + initiatorType) / (entry.duration / 1e3);
              count++;
              if (10 < count) break;
            }
          }
          if (0 < count) return bits / count / 1e6;
        }
        return navigator.connection && (count = navigator.connection.downlink, "number" === typeof count) ? count : 5;
      }
      function getOwnerDocumentFromRootContainer(rootContainerElement) {
        return 9 === rootContainerElement.nodeType ? rootContainerElement : rootContainerElement.ownerDocument;
      }
      function getOwnHostContext(namespaceURI) {
        switch (namespaceURI) {
          case SVG_NAMESPACE:
            return HostContextNamespaceSvg;
          case MATH_NAMESPACE:
            return HostContextNamespaceMath;
          default:
            return HostContextNamespaceNone;
        }
      }
      function getChildHostContextProd(parentNamespace, type) {
        if (parentNamespace === HostContextNamespaceNone)
          switch (type) {
            case "svg":
              return HostContextNamespaceSvg;
            case "math":
              return HostContextNamespaceMath;
            default:
              return HostContextNamespaceNone;
          }
        return parentNamespace === HostContextNamespaceSvg && "foreignObject" === type ? HostContextNamespaceNone : parentNamespace;
      }
      function shouldSetTextContent(type, props) {
        return "textarea" === type || "noscript" === type || "string" === typeof props.children || "number" === typeof props.children || "bigint" === typeof props.children || "object" === typeof props.dangerouslySetInnerHTML && null !== props.dangerouslySetInnerHTML && null != props.dangerouslySetInnerHTML.__html;
      }
      function shouldAttemptEagerTransition() {
        var event = window.event;
        if (event && "popstate" === event.type) {
          if (event === currentPopstateTransitionEvent) return false;
          currentPopstateTransitionEvent = event;
          return true;
        }
        currentPopstateTransitionEvent = null;
        return false;
      }
      function resolveEventType() {
        var event = window.event;
        return event && event !== schedulerEvent ? event.type : null;
      }
      function resolveEventTimeStamp() {
        var event = window.event;
        return event && event !== schedulerEvent ? event.timeStamp : -1.1;
      }
      function handleErrorInNextTick(error) {
        setTimeout(function() {
          throw error;
        });
      }
      function commitMount(domElement, type, newProps) {
        switch (type) {
          case "button":
          case "input":
          case "select":
          case "textarea":
            newProps.autoFocus && domElement.focus();
            break;
          case "img":
            newProps.src ? domElement.src = newProps.src : newProps.srcSet && (domElement.srcset = newProps.srcSet);
        }
      }
      function commitHydratedInstance() {
      }
      function commitUpdate(domElement, type, oldProps, newProps) {
        updateProperties(domElement, type, oldProps, newProps);
        domElement[internalPropsKey] = newProps;
      }
      function resetTextContent(domElement) {
        setTextContent(domElement, "");
      }
      function commitTextUpdate(textInstance, oldText, newText) {
        textInstance.nodeValue = newText;
      }
      function warnForReactChildrenConflict(container) {
        if (!container.__reactWarnedAboutChildrenConflict) {
          var props = container[internalPropsKey] || null;
          if (null !== props) {
            var fiber = getInstanceFromNode(container);
            null !== fiber && ("string" === typeof props.children || "number" === typeof props.children ? (container.__reactWarnedAboutChildrenConflict = true, runWithFiberInDEV(fiber, function() {
              console.error(
                'Cannot use a ref on a React element as a container to `createRoot` or `createPortal` if that element also sets "children" text content using React. It should be a leaf with no children. Otherwise it\'s ambiguous which children should be used.'
              );
            })) : null != props.dangerouslySetInnerHTML && (container.__reactWarnedAboutChildrenConflict = true, runWithFiberInDEV(fiber, function() {
              console.error(
                'Cannot use a ref on a React element as a container to `createRoot` or `createPortal` if that element also sets "dangerouslySetInnerHTML" using React. It should be a leaf with no children. Otherwise it\'s ambiguous which children should be used.'
              );
            })));
          }
        }
      }
      function isSingletonScope(type) {
        return "head" === type;
      }
      function removeChild(parentInstance, child) {
        parentInstance.removeChild(child);
      }
      function removeChildFromContainer(container, child) {
        (9 === container.nodeType ? container.body : "HTML" === container.nodeName ? container.ownerDocument.body : container).removeChild(child);
      }
      function clearHydrationBoundary(parentInstance, hydrationInstance) {
        var node = hydrationInstance, depth = 0;
        do {
          var nextNode = node.nextSibling;
          parentInstance.removeChild(node);
          if (nextNode && 8 === nextNode.nodeType)
            if (node = nextNode.data, node === SUSPENSE_END_DATA || node === ACTIVITY_END_DATA) {
              if (0 === depth) {
                parentInstance.removeChild(nextNode);
                retryIfBlockedOn(hydrationInstance);
                return;
              }
              depth--;
            } else if (node === SUSPENSE_START_DATA || node === SUSPENSE_PENDING_START_DATA || node === SUSPENSE_QUEUED_START_DATA || node === SUSPENSE_FALLBACK_START_DATA || node === ACTIVITY_START_DATA)
              depth++;
            else if (node === PREAMBLE_CONTRIBUTION_HTML)
              releaseSingletonInstance(
                parentInstance.ownerDocument.documentElement
              );
            else if (node === PREAMBLE_CONTRIBUTION_HEAD) {
              node = parentInstance.ownerDocument.head;
              releaseSingletonInstance(node);
              for (var node$jscomp$0 = node.firstChild; node$jscomp$0; ) {
                var nextNode$jscomp$0 = node$jscomp$0.nextSibling, nodeName = node$jscomp$0.nodeName;
                node$jscomp$0[internalHoistableMarker] || "SCRIPT" === nodeName || "STYLE" === nodeName || "LINK" === nodeName && "stylesheet" === node$jscomp$0.rel.toLowerCase() || node.removeChild(node$jscomp$0);
                node$jscomp$0 = nextNode$jscomp$0;
              }
            } else
              node === PREAMBLE_CONTRIBUTION_BODY && releaseSingletonInstance(parentInstance.ownerDocument.body);
          node = nextNode;
        } while (node);
        retryIfBlockedOn(hydrationInstance);
      }
      function hideOrUnhideDehydratedBoundary(suspenseInstance, isHidden) {
        var node = suspenseInstance;
        suspenseInstance = 0;
        do {
          var nextNode = node.nextSibling;
          1 === node.nodeType ? isHidden ? (node._stashedDisplay = node.style.display, node.style.display = "none") : (node.style.display = node._stashedDisplay || "", "" === node.getAttribute("style") && node.removeAttribute("style")) : 3 === node.nodeType && (isHidden ? (node._stashedText = node.nodeValue, node.nodeValue = "") : node.nodeValue = node._stashedText || "");
          if (nextNode && 8 === nextNode.nodeType)
            if (node = nextNode.data, node === SUSPENSE_END_DATA)
              if (0 === suspenseInstance) break;
              else suspenseInstance--;
            else
              node !== SUSPENSE_START_DATA && node !== SUSPENSE_PENDING_START_DATA && node !== SUSPENSE_QUEUED_START_DATA && node !== SUSPENSE_FALLBACK_START_DATA || suspenseInstance++;
          node = nextNode;
        } while (node);
      }
      function hideDehydratedBoundary(suspenseInstance) {
        hideOrUnhideDehydratedBoundary(suspenseInstance, true);
      }
      function hideInstance(instance) {
        instance = instance.style;
        "function" === typeof instance.setProperty ? instance.setProperty("display", "none", "important") : instance.display = "none";
      }
      function hideTextInstance(textInstance) {
        textInstance.nodeValue = "";
      }
      function unhideDehydratedBoundary(dehydratedInstance) {
        hideOrUnhideDehydratedBoundary(dehydratedInstance, false);
      }
      function unhideInstance(instance, props) {
        props = props[STYLE];
        props = void 0 !== props && null !== props && props.hasOwnProperty("display") ? props.display : null;
        instance.style.display = null == props || "boolean" === typeof props ? "" : ("" + props).trim();
      }
      function unhideTextInstance(textInstance, text5) {
        textInstance.nodeValue = text5;
      }
      function clearContainerSparingly(container) {
        var nextNode = container.firstChild;
        nextNode && 10 === nextNode.nodeType && (nextNode = nextNode.nextSibling);
        for (; nextNode; ) {
          var node = nextNode;
          nextNode = nextNode.nextSibling;
          switch (node.nodeName) {
            case "HTML":
            case "HEAD":
            case "BODY":
              clearContainerSparingly(node);
              detachDeletedInstance(node);
              continue;
            case "SCRIPT":
            case "STYLE":
              continue;
            case "LINK":
              if ("stylesheet" === node.rel.toLowerCase()) continue;
          }
          container.removeChild(node);
        }
      }
      function canHydrateInstance(instance, type, props, inRootOrSingleton) {
        for (; 1 === instance.nodeType; ) {
          var anyProps = props;
          if (instance.nodeName.toLowerCase() !== type.toLowerCase()) {
            if (!inRootOrSingleton && ("INPUT" !== instance.nodeName || "hidden" !== instance.type))
              break;
          } else if (!inRootOrSingleton)
            if ("input" === type && "hidden" === instance.type) {
              checkAttributeStringCoercion(anyProps.name, "name");
              var name = null == anyProps.name ? null : "" + anyProps.name;
              if ("hidden" === anyProps.type && instance.getAttribute("name") === name)
                return instance;
            } else return instance;
          else if (!instance[internalHoistableMarker])
            switch (type) {
              case "meta":
                if (!instance.hasAttribute("itemprop")) break;
                return instance;
              case "link":
                name = instance.getAttribute("rel");
                if ("stylesheet" === name && instance.hasAttribute("data-precedence"))
                  break;
                else if (name !== anyProps.rel || instance.getAttribute("href") !== (null == anyProps.href || "" === anyProps.href ? null : anyProps.href) || instance.getAttribute("crossorigin") !== (null == anyProps.crossOrigin ? null : anyProps.crossOrigin) || instance.getAttribute("title") !== (null == anyProps.title ? null : anyProps.title))
                  break;
                return instance;
              case "style":
                if (instance.hasAttribute("data-precedence")) break;
                return instance;
              case "script":
                name = instance.getAttribute("src");
                if ((name !== (null == anyProps.src ? null : anyProps.src) || instance.getAttribute("type") !== (null == anyProps.type ? null : anyProps.type) || instance.getAttribute("crossorigin") !== (null == anyProps.crossOrigin ? null : anyProps.crossOrigin)) && name && instance.hasAttribute("async") && !instance.hasAttribute("itemprop"))
                  break;
                return instance;
              default:
                return instance;
            }
          instance = getNextHydratable(instance.nextSibling);
          if (null === instance) break;
        }
        return null;
      }
      function canHydrateTextInstance(instance, text5, inRootOrSingleton) {
        if ("" === text5) return null;
        for (; 3 !== instance.nodeType; ) {
          if ((1 !== instance.nodeType || "INPUT" !== instance.nodeName || "hidden" !== instance.type) && !inRootOrSingleton)
            return null;
          instance = getNextHydratable(instance.nextSibling);
          if (null === instance) return null;
        }
        return instance;
      }
      function canHydrateHydrationBoundary(instance, inRootOrSingleton) {
        for (; 8 !== instance.nodeType; ) {
          if ((1 !== instance.nodeType || "INPUT" !== instance.nodeName || "hidden" !== instance.type) && !inRootOrSingleton)
            return null;
          instance = getNextHydratable(instance.nextSibling);
          if (null === instance) return null;
        }
        return instance;
      }
      function isSuspenseInstancePending(instance) {
        return instance.data === SUSPENSE_PENDING_START_DATA || instance.data === SUSPENSE_QUEUED_START_DATA;
      }
      function isSuspenseInstanceFallback(instance) {
        return instance.data === SUSPENSE_FALLBACK_START_DATA || instance.data === SUSPENSE_PENDING_START_DATA && instance.ownerDocument.readyState !== DOCUMENT_READY_STATE_LOADING;
      }
      function registerSuspenseInstanceRetry(instance, callback) {
        var ownerDocument = instance.ownerDocument;
        if (instance.data === SUSPENSE_QUEUED_START_DATA)
          instance._reactRetry = callback;
        else if (instance.data !== SUSPENSE_PENDING_START_DATA || ownerDocument.readyState !== DOCUMENT_READY_STATE_LOADING)
          callback();
        else {
          var listener = function() {
            callback();
            ownerDocument.removeEventListener("DOMContentLoaded", listener);
          };
          ownerDocument.addEventListener("DOMContentLoaded", listener);
          instance._reactRetry = listener;
        }
      }
      function getNextHydratable(node) {
        for (; null != node; node = node.nextSibling) {
          var nodeType = node.nodeType;
          if (1 === nodeType || 3 === nodeType) break;
          if (8 === nodeType) {
            nodeType = node.data;
            if (nodeType === SUSPENSE_START_DATA || nodeType === SUSPENSE_FALLBACK_START_DATA || nodeType === SUSPENSE_PENDING_START_DATA || nodeType === SUSPENSE_QUEUED_START_DATA || nodeType === ACTIVITY_START_DATA || nodeType === FORM_STATE_IS_MATCHING || nodeType === FORM_STATE_IS_NOT_MATCHING)
              break;
            if (nodeType === SUSPENSE_END_DATA || nodeType === ACTIVITY_END_DATA)
              return null;
          }
        }
        return node;
      }
      function describeHydratableInstanceForDevWarnings(instance) {
        if (1 === instance.nodeType) {
          for (var JSCompiler_temp_const = instance.nodeName.toLowerCase(), serverDifferences = {}, attributes = instance.attributes, i = 0; i < attributes.length; i++) {
            var attr = attributes[i];
            serverDifferences[getPropNameFromAttributeName(attr.name)] = "style" === attr.name.toLowerCase() ? getStylesObjectFromElement(instance) : attr.value;
          }
          return { type: JSCompiler_temp_const, props: serverDifferences };
        }
        return 8 === instance.nodeType ? instance.data === ACTIVITY_START_DATA ? { type: "Activity", props: {} } : { type: "Suspense", props: {} } : instance.nodeValue;
      }
      function diffHydratedTextForDevWarnings(textInstance, text5, parentProps) {
        return null === parentProps || true !== parentProps[SUPPRESS_HYDRATION_WARNING] ? (textInstance.nodeValue === text5 ? textInstance = null : (text5 = normalizeMarkupForTextOrAttribute(text5), textInstance = normalizeMarkupForTextOrAttribute(textInstance.nodeValue) === text5 ? null : textInstance.nodeValue), textInstance) : null;
      }
      function getNextHydratableInstanceAfterHydrationBoundary(hydrationInstance) {
        hydrationInstance = hydrationInstance.nextSibling;
        for (var depth = 0; hydrationInstance; ) {
          if (8 === hydrationInstance.nodeType) {
            var data = hydrationInstance.data;
            if (data === SUSPENSE_END_DATA || data === ACTIVITY_END_DATA) {
              if (0 === depth)
                return getNextHydratable(hydrationInstance.nextSibling);
              depth--;
            } else
              data !== SUSPENSE_START_DATA && data !== SUSPENSE_FALLBACK_START_DATA && data !== SUSPENSE_PENDING_START_DATA && data !== SUSPENSE_QUEUED_START_DATA && data !== ACTIVITY_START_DATA || depth++;
          }
          hydrationInstance = hydrationInstance.nextSibling;
        }
        return null;
      }
      function getParentHydrationBoundary(targetInstance) {
        targetInstance = targetInstance.previousSibling;
        for (var depth = 0; targetInstance; ) {
          if (8 === targetInstance.nodeType) {
            var data = targetInstance.data;
            if (data === SUSPENSE_START_DATA || data === SUSPENSE_FALLBACK_START_DATA || data === SUSPENSE_PENDING_START_DATA || data === SUSPENSE_QUEUED_START_DATA || data === ACTIVITY_START_DATA) {
              if (0 === depth) return targetInstance;
              depth--;
            } else
              data !== SUSPENSE_END_DATA && data !== ACTIVITY_END_DATA || depth++;
          }
          targetInstance = targetInstance.previousSibling;
        }
        return null;
      }
      function commitHydratedContainer(container) {
        retryIfBlockedOn(container);
      }
      function commitHydratedActivityInstance(activityInstance) {
        retryIfBlockedOn(activityInstance);
      }
      function commitHydratedSuspenseInstance(suspenseInstance) {
        retryIfBlockedOn(suspenseInstance);
      }
      function resolveSingletonInstance(type, props, rootContainerInstance, hostContext, validateDOMNestingDev) {
        validateDOMNestingDev && validateDOMNesting(type, hostContext.ancestorInfo);
        props = getOwnerDocumentFromRootContainer(rootContainerInstance);
        switch (type) {
          case "html":
            type = props.documentElement;
            if (!type)
              throw Error(
                "React expected an <html> element (document.documentElement) to exist in the Document but one was not found. React never removes the documentElement for any Document it renders into so the cause is likely in some other script running on this page."
              );
            return type;
          case "head":
            type = props.head;
            if (!type)
              throw Error(
                "React expected a <head> element (document.head) to exist in the Document but one was not found. React never removes the head for any Document it renders into so the cause is likely in some other script running on this page."
              );
            return type;
          case "body":
            type = props.body;
            if (!type)
              throw Error(
                "React expected a <body> element (document.body) to exist in the Document but one was not found. React never removes the body for any Document it renders into so the cause is likely in some other script running on this page."
              );
            return type;
          default:
            throw Error(
              "resolveSingletonInstance was called with an element type that is not supported. This is a bug in React."
            );
        }
      }
      function acquireSingletonInstance(type, props, instance, internalInstanceHandle) {
        if (!instance[internalContainerInstanceKey] && getInstanceFromNode(instance)) {
          var tagName = instance.tagName.toLowerCase();
          console.error(
            "You are mounting a new %s component when a previous one has not first unmounted. It is an error to render more than one %s component at a time and attributes and children of these components will likely fail in unpredictable ways. Please only render a single instance of <%s> and if you need to mount a new one, ensure any previous ones have unmounted first.",
            tagName,
            tagName,
            tagName
          );
        }
        switch (type) {
          case "html":
          case "head":
          case "body":
            break;
          default:
            console.error(
              "acquireSingletonInstance was called with an element type that is not supported. This is a bug in React."
            );
        }
        for (tagName = instance.attributes; tagName.length; )
          instance.removeAttributeNode(tagName[0]);
        setInitialProperties(instance, type, props);
        instance[internalInstanceKey] = internalInstanceHandle;
        instance[internalPropsKey] = props;
      }
      function releaseSingletonInstance(instance) {
        for (var attributes = instance.attributes; attributes.length; )
          instance.removeAttributeNode(attributes[0]);
        detachDeletedInstance(instance);
      }
      function getHoistableRoot(container) {
        return "function" === typeof container.getRootNode ? container.getRootNode() : 9 === container.nodeType ? container : container.ownerDocument;
      }
      function preconnectAs(rel2, href, crossOrigin) {
        var ownerDocument = globalDocument;
        if (ownerDocument && "string" === typeof href && href) {
          var limitedEscapedHref = escapeSelectorAttributeValueInsideDoubleQuotes(href);
          limitedEscapedHref = 'link[rel="' + rel2 + '"][href="' + limitedEscapedHref + '"]';
          "string" === typeof crossOrigin && (limitedEscapedHref += '[crossorigin="' + crossOrigin + '"]');
          preconnectsSet.has(limitedEscapedHref) || (preconnectsSet.add(limitedEscapedHref), rel2 = { rel: rel2, crossOrigin, href }, null === ownerDocument.querySelector(limitedEscapedHref) && (href = ownerDocument.createElement("link"), setInitialProperties(href, "link", rel2), markNodeAsHoistable(href), ownerDocument.head.appendChild(href)));
        }
      }
      function getResource(type, currentProps, pendingProps, currentResource) {
        var resourceRoot = (resourceRoot = rootInstanceStackCursor.current) ? getHoistableRoot(resourceRoot) : null;
        if (!resourceRoot)
          throw Error(
            '"resourceRoot" was expected to exist. This is a bug in React.'
          );
        switch (type) {
          case "meta":
          case "title":
            return null;
          case "style":
            return "string" === typeof pendingProps.precedence && "string" === typeof pendingProps.href ? (pendingProps = getStyleKey(pendingProps.href), currentProps = getResourcesFromRoot(resourceRoot).hoistableStyles, currentResource = currentProps.get(pendingProps), currentResource || (currentResource = {
              type: "style",
              instance: null,
              count: 0,
              state: null
            }, currentProps.set(pendingProps, currentResource)), currentResource) : { type: "void", instance: null, count: 0, state: null };
          case "link":
            if ("stylesheet" === pendingProps.rel && "string" === typeof pendingProps.href && "string" === typeof pendingProps.precedence) {
              type = getStyleKey(pendingProps.href);
              var _styles = getResourcesFromRoot(resourceRoot).hoistableStyles, _resource = _styles.get(type);
              if (!_resource && (resourceRoot = resourceRoot.ownerDocument || resourceRoot, _resource = {
                type: "stylesheet",
                instance: null,
                count: 0,
                state: { loading: NotLoaded, preload: null }
              }, _styles.set(type, _resource), (_styles = resourceRoot.querySelector(
                getStylesheetSelectorFromKey(type)
              )) && !_styles._p && (_resource.instance = _styles, _resource.state.loading = Loaded | Inserted), !preloadPropsMap.has(type))) {
                var preloadProps = {
                  rel: "preload",
                  as: "style",
                  href: pendingProps.href,
                  crossOrigin: pendingProps.crossOrigin,
                  integrity: pendingProps.integrity,
                  media: pendingProps.media,
                  hrefLang: pendingProps.hrefLang,
                  referrerPolicy: pendingProps.referrerPolicy
                };
                preloadPropsMap.set(type, preloadProps);
                _styles || preloadStylesheet(
                  resourceRoot,
                  type,
                  preloadProps,
                  _resource.state
                );
              }
              if (currentProps && null === currentResource)
                throw pendingProps = "\n\n  - " + describeLinkForResourceErrorDEV(currentProps) + "\n  + " + describeLinkForResourceErrorDEV(pendingProps), Error(
                  "Expected <link> not to update to be updated to a stylesheet with precedence. Check the `rel`, `href`, and `precedence` props of this component. Alternatively, check whether two different <link> components render in the same slot or share the same key." + pendingProps
                );
              return _resource;
            }
            if (currentProps && null !== currentResource)
              throw pendingProps = "\n\n  - " + describeLinkForResourceErrorDEV(currentProps) + "\n  + " + describeLinkForResourceErrorDEV(pendingProps), Error(
                "Expected stylesheet with precedence to not be updated to a different kind of <link>. Check the `rel`, `href`, and `precedence` props of this component. Alternatively, check whether two different <link> components render in the same slot or share the same key." + pendingProps
              );
            return null;
          case "script":
            return currentProps = pendingProps.async, pendingProps = pendingProps.src, "string" === typeof pendingProps && currentProps && "function" !== typeof currentProps && "symbol" !== typeof currentProps ? (pendingProps = getScriptKey(pendingProps), currentProps = getResourcesFromRoot(resourceRoot).hoistableScripts, currentResource = currentProps.get(pendingProps), currentResource || (currentResource = {
              type: "script",
              instance: null,
              count: 0,
              state: null
            }, currentProps.set(pendingProps, currentResource)), currentResource) : { type: "void", instance: null, count: 0, state: null };
          default:
            throw Error(
              'getResource encountered a type it did not expect: "' + type + '". this is a bug in React.'
            );
        }
      }
      function describeLinkForResourceErrorDEV(props) {
        var describedProps = 0, description = "<link";
        "string" === typeof props.rel ? (describedProps++, description += ' rel="' + props.rel + '"') : hasOwnProperty2.call(props, "rel") && (describedProps++, description += ' rel="' + (null === props.rel ? "null" : "invalid type " + typeof props.rel) + '"');
        "string" === typeof props.href ? (describedProps++, description += ' href="' + props.href + '"') : hasOwnProperty2.call(props, "href") && (describedProps++, description += ' href="' + (null === props.href ? "null" : "invalid type " + typeof props.href) + '"');
        "string" === typeof props.precedence ? (describedProps++, description += ' precedence="' + props.precedence + '"') : hasOwnProperty2.call(props, "precedence") && (describedProps++, description += " precedence={" + (null === props.precedence ? "null" : "invalid type " + typeof props.precedence) + "}");
        Object.getOwnPropertyNames(props).length > describedProps && (description += " ...");
        return description + " />";
      }
      function getStyleKey(href) {
        return 'href="' + escapeSelectorAttributeValueInsideDoubleQuotes(href) + '"';
      }
      function getStylesheetSelectorFromKey(key) {
        return 'link[rel="stylesheet"][' + key + "]";
      }
      function stylesheetPropsFromRawProps(rawProps) {
        return assign({}, rawProps, {
          "data-precedence": rawProps.precedence,
          precedence: null
        });
      }
      function preloadStylesheet(ownerDocument, key, preloadProps, state) {
        ownerDocument.querySelector(
          'link[rel="preload"][as="style"][' + key + "]"
        ) ? state.loading = Loaded : (key = ownerDocument.createElement("link"), state.preload = key, key.addEventListener("load", function() {
          return state.loading |= Loaded;
        }), key.addEventListener("error", function() {
          return state.loading |= Errored;
        }), setInitialProperties(key, "link", preloadProps), markNodeAsHoistable(key), ownerDocument.head.appendChild(key));
      }
      function getScriptKey(src) {
        return '[src="' + escapeSelectorAttributeValueInsideDoubleQuotes(src) + '"]';
      }
      function getScriptSelectorFromKey(key) {
        return "script[async]" + key;
      }
      function acquireResource(hoistableRoot, resource, props) {
        resource.count++;
        if (null === resource.instance)
          switch (resource.type) {
            case "style":
              var instance = hoistableRoot.querySelector(
                'style[data-href~="' + escapeSelectorAttributeValueInsideDoubleQuotes(props.href) + '"]'
              );
              if (instance)
                return resource.instance = instance, markNodeAsHoistable(instance), instance;
              var styleProps = assign({}, props, {
                "data-href": props.href,
                "data-precedence": props.precedence,
                href: null,
                precedence: null
              });
              instance = (hoistableRoot.ownerDocument || hoistableRoot).createElement("style");
              markNodeAsHoistable(instance);
              setInitialProperties(instance, "style", styleProps);
              insertStylesheet(instance, props.precedence, hoistableRoot);
              return resource.instance = instance;
            case "stylesheet":
              styleProps = getStyleKey(props.href);
              var _instance = hoistableRoot.querySelector(
                getStylesheetSelectorFromKey(styleProps)
              );
              if (_instance)
                return resource.state.loading |= Inserted, resource.instance = _instance, markNodeAsHoistable(_instance), _instance;
              instance = stylesheetPropsFromRawProps(props);
              (styleProps = preloadPropsMap.get(styleProps)) && adoptPreloadPropsForStylesheet(instance, styleProps);
              _instance = (hoistableRoot.ownerDocument || hoistableRoot).createElement("link");
              markNodeAsHoistable(_instance);
              var linkInstance = _instance;
              linkInstance._p = new Promise(function(resolve, reject) {
                linkInstance.onload = resolve;
                linkInstance.onerror = reject;
              });
              setInitialProperties(_instance, "link", instance);
              resource.state.loading |= Inserted;
              insertStylesheet(_instance, props.precedence, hoistableRoot);
              return resource.instance = _instance;
            case "script":
              _instance = getScriptKey(props.src);
              if (styleProps = hoistableRoot.querySelector(
                getScriptSelectorFromKey(_instance)
              ))
                return resource.instance = styleProps, markNodeAsHoistable(styleProps), styleProps;
              instance = props;
              if (styleProps = preloadPropsMap.get(_instance))
                instance = assign({}, props), adoptPreloadPropsForScript(instance, styleProps);
              hoistableRoot = hoistableRoot.ownerDocument || hoistableRoot;
              styleProps = hoistableRoot.createElement("script");
              markNodeAsHoistable(styleProps);
              setInitialProperties(styleProps, "link", instance);
              hoistableRoot.head.appendChild(styleProps);
              return resource.instance = styleProps;
            case "void":
              return null;
            default:
              throw Error(
                'acquireResource encountered a resource type it did not expect: "' + resource.type + '". this is a bug in React.'
              );
          }
        else
          "stylesheet" === resource.type && (resource.state.loading & Inserted) === NotLoaded && (instance = resource.instance, resource.state.loading |= Inserted, insertStylesheet(instance, props.precedence, hoistableRoot));
        return resource.instance;
      }
      function insertStylesheet(instance, precedence, root2) {
        for (var nodes = root2.querySelectorAll(
          'link[rel="stylesheet"][data-precedence],style[data-precedence]'
        ), last = nodes.length ? nodes[nodes.length - 1] : null, prior = last, i = 0; i < nodes.length; i++) {
          var node = nodes[i];
          if (node.dataset.precedence === precedence) prior = node;
          else if (prior !== last) break;
        }
        prior ? prior.parentNode.insertBefore(instance, prior.nextSibling) : (precedence = 9 === root2.nodeType ? root2.head : root2, precedence.insertBefore(instance, precedence.firstChild));
      }
      function adoptPreloadPropsForStylesheet(stylesheetProps, preloadProps) {
        null == stylesheetProps.crossOrigin && (stylesheetProps.crossOrigin = preloadProps.crossOrigin);
        null == stylesheetProps.referrerPolicy && (stylesheetProps.referrerPolicy = preloadProps.referrerPolicy);
        null == stylesheetProps.title && (stylesheetProps.title = preloadProps.title);
      }
      function adoptPreloadPropsForScript(scriptProps, preloadProps) {
        null == scriptProps.crossOrigin && (scriptProps.crossOrigin = preloadProps.crossOrigin);
        null == scriptProps.referrerPolicy && (scriptProps.referrerPolicy = preloadProps.referrerPolicy);
        null == scriptProps.integrity && (scriptProps.integrity = preloadProps.integrity);
      }
      function getHydratableHoistableCache(type, keyAttribute, ownerDocument) {
        if (null === tagCaches) {
          var cache = /* @__PURE__ */ new Map();
          var caches = tagCaches = /* @__PURE__ */ new Map();
          caches.set(ownerDocument, cache);
        } else
          caches = tagCaches, cache = caches.get(ownerDocument), cache || (cache = /* @__PURE__ */ new Map(), caches.set(ownerDocument, cache));
        if (cache.has(type)) return cache;
        cache.set(type, null);
        ownerDocument = ownerDocument.getElementsByTagName(type);
        for (caches = 0; caches < ownerDocument.length; caches++) {
          var node = ownerDocument[caches];
          if (!(node[internalHoistableMarker] || node[internalInstanceKey] || "link" === type && "stylesheet" === node.getAttribute("rel")) && node.namespaceURI !== SVG_NAMESPACE) {
            var nodeKey = node.getAttribute(keyAttribute) || "";
            nodeKey = type + nodeKey;
            var existing = cache.get(nodeKey);
            existing ? existing.push(node) : cache.set(nodeKey, [node]);
          }
        }
        return cache;
      }
      function mountHoistable(hoistableRoot, type, instance) {
        hoistableRoot = hoistableRoot.ownerDocument || hoistableRoot;
        hoistableRoot.head.insertBefore(
          instance,
          "title" === type ? hoistableRoot.querySelector("head > title") : null
        );
      }
      function isHostHoistableType(type, props, hostContext) {
        var outsideHostContainerContext = !hostContext.ancestorInfo.containerTagInScope;
        if (hostContext.context === HostContextNamespaceSvg || null != props.itemProp)
          return !outsideHostContainerContext || null == props.itemProp || "meta" !== type && "title" !== type && "style" !== type && "link" !== type && "script" !== type || console.error(
            "Cannot render a <%s> outside the main document if it has an `itemProp` prop. `itemProp` suggests the tag belongs to an `itemScope` which can appear anywhere in the DOM. If you were intending for React to hoist this <%s> remove the `itemProp` prop. Otherwise, try moving this tag into the <head> or <body> of the Document.",
            type,
            type
          ), false;
        switch (type) {
          case "meta":
          case "title":
            return true;
          case "style":
            if ("string" !== typeof props.precedence || "string" !== typeof props.href || "" === props.href) {
              outsideHostContainerContext && console.error(
                'Cannot render a <style> outside the main document without knowing its precedence and a unique href key. React can hoist and deduplicate <style> tags if you provide a `precedence` prop along with an `href` prop that does not conflict with the `href` values used in any other hoisted <style> or <link rel="stylesheet" ...> tags.  Note that hoisting <style> tags is considered an advanced feature that most will not use directly. Consider moving the <style> tag to the <head> or consider adding a `precedence="default"` and `href="some unique resource identifier"`.'
              );
              break;
            }
            return true;
          case "link":
            if ("string" !== typeof props.rel || "string" !== typeof props.href || "" === props.href || props.onLoad || props.onError) {
              if ("stylesheet" === props.rel && "string" === typeof props.precedence) {
                type = props.href;
                var onError = props.onError, disabled = props.disabled;
                hostContext = [];
                props.onLoad && hostContext.push("`onLoad`");
                onError && hostContext.push("`onError`");
                null != disabled && hostContext.push("`disabled`");
                onError = propNamesListJoin(hostContext, "and");
                onError += 1 === hostContext.length ? " prop" : " props";
                disabled = 1 === hostContext.length ? "an " + onError : "the " + onError;
                hostContext.length && console.error(
                  'React encountered a <link rel="stylesheet" href="%s" ... /> with a `precedence` prop that also included %s. The presence of loading and error handlers indicates an intent to manage the stylesheet loading state from your from your Component code and React will not hoist or deduplicate this stylesheet. If your intent was to have React hoist and deduplciate this stylesheet using the `precedence` prop remove the %s, otherwise remove the `precedence` prop.',
                  type,
                  disabled,
                  onError
                );
              }
              outsideHostContainerContext && ("string" !== typeof props.rel || "string" !== typeof props.href || "" === props.href ? console.error(
                "Cannot render a <link> outside the main document without a `rel` and `href` prop. Try adding a `rel` and/or `href` prop to this <link> or moving the link into the <head> tag"
              ) : (props.onError || props.onLoad) && console.error(
                "Cannot render a <link> with onLoad or onError listeners outside the main document. Try removing onLoad={...} and onError={...} or moving it into the root <head> tag or somewhere in the <body>."
              ));
              break;
            }
            switch (props.rel) {
              case "stylesheet":
                return type = props.precedence, props = props.disabled, "string" !== typeof type && outsideHostContainerContext && console.error(
                  'Cannot render a <link rel="stylesheet" /> outside the main document without knowing its precedence. Consider adding precedence="default" or moving it into the root <head> tag.'
                ), "string" === typeof type && null == props;
              default:
                return true;
            }
          case "script":
            type = props.async && "function" !== typeof props.async && "symbol" !== typeof props.async;
            if (!type || props.onLoad || props.onError || !props.src || "string" !== typeof props.src) {
              outsideHostContainerContext && (type ? props.onLoad || props.onError ? console.error(
                "Cannot render a <script> with onLoad or onError listeners outside the main document. Try removing onLoad={...} and onError={...} or moving it into the root <head> tag or somewhere in the <body>."
              ) : console.error(
                "Cannot render a <script> outside the main document without `async={true}` and a non-empty `src` prop. Ensure there is a valid `src` and either make the script async or move it into the root <head> tag or somewhere in the <body>."
              ) : console.error(
                'Cannot render a sync or defer <script> outside the main document without knowing its order. Try adding async="" or moving it into the root <head> tag.'
              ));
              break;
            }
            return true;
          case "noscript":
          case "template":
            outsideHostContainerContext && console.error(
              "Cannot render <%s> outside the main document. Try moving it into the root <head> tag.",
              type
            );
        }
        return false;
      }
      function preloadResource(resource) {
        return "stylesheet" === resource.type && (resource.state.loading & Settled) === NotLoaded ? false : true;
      }
      function suspendResource(state, hoistableRoot, resource, props) {
        if ("stylesheet" === resource.type && ("string" !== typeof props.media || false !== matchMedia(props.media).matches) && (resource.state.loading & Inserted) === NotLoaded) {
          if (null === resource.instance) {
            var key = getStyleKey(props.href), instance = hoistableRoot.querySelector(
              getStylesheetSelectorFromKey(key)
            );
            if (instance) {
              hoistableRoot = instance._p;
              null !== hoistableRoot && "object" === typeof hoistableRoot && "function" === typeof hoistableRoot.then && (state.count++, state = onUnsuspend.bind(state), hoistableRoot.then(state, state));
              resource.state.loading |= Inserted;
              resource.instance = instance;
              markNodeAsHoistable(instance);
              return;
            }
            instance = hoistableRoot.ownerDocument || hoistableRoot;
            props = stylesheetPropsFromRawProps(props);
            (key = preloadPropsMap.get(key)) && adoptPreloadPropsForStylesheet(props, key);
            instance = instance.createElement("link");
            markNodeAsHoistable(instance);
            var linkInstance = instance;
            linkInstance._p = new Promise(function(resolve, reject) {
              linkInstance.onload = resolve;
              linkInstance.onerror = reject;
            });
            setInitialProperties(instance, "link", props);
            resource.instance = instance;
          }
          null === state.stylesheets && (state.stylesheets = /* @__PURE__ */ new Map());
          state.stylesheets.set(resource, hoistableRoot);
          (hoistableRoot = resource.state.preload) && (resource.state.loading & Settled) === NotLoaded && (state.count++, resource = onUnsuspend.bind(state), hoistableRoot.addEventListener("load", resource), hoistableRoot.addEventListener("error", resource));
        }
      }
      function waitForCommitToBeReady(state, timeoutOffset) {
        state.stylesheets && 0 === state.count && insertSuspendedStylesheets(state, state.stylesheets);
        return 0 < state.count || 0 < state.imgCount ? function(commit) {
          var stylesheetTimer = setTimeout(function() {
            state.stylesheets && insertSuspendedStylesheets(state, state.stylesheets);
            if (state.unsuspend) {
              var unsuspend = state.unsuspend;
              state.unsuspend = null;
              unsuspend();
            }
          }, SUSPENSEY_STYLESHEET_TIMEOUT + timeoutOffset);
          0 < state.imgBytes && 0 === estimatedBytesWithinLimit && (estimatedBytesWithinLimit = 125 * estimateBandwidth() * SUSPENSEY_IMAGE_TIME_ESTIMATE);
          var imgTimer = setTimeout(
            function() {
              state.waitingForImages = false;
              if (0 === state.count && (state.stylesheets && insertSuspendedStylesheets(state, state.stylesheets), state.unsuspend)) {
                var unsuspend = state.unsuspend;
                state.unsuspend = null;
                unsuspend();
              }
            },
            (state.imgBytes > estimatedBytesWithinLimit ? 50 : SUSPENSEY_IMAGE_TIMEOUT) + timeoutOffset
          );
          state.unsuspend = commit;
          return function() {
            state.unsuspend = null;
            clearTimeout(stylesheetTimer);
            clearTimeout(imgTimer);
          };
        } : null;
      }
      function onUnsuspend() {
        this.count--;
        if (0 === this.count && (0 === this.imgCount || !this.waitingForImages)) {
          if (this.stylesheets)
            insertSuspendedStylesheets(this, this.stylesheets);
          else if (this.unsuspend) {
            var unsuspend = this.unsuspend;
            this.unsuspend = null;
            unsuspend();
          }
        }
      }
      function insertSuspendedStylesheets(state, resources) {
        state.stylesheets = null;
        null !== state.unsuspend && (state.count++, precedencesByRoot = /* @__PURE__ */ new Map(), resources.forEach(insertStylesheetIntoRoot, state), precedencesByRoot = null, onUnsuspend.call(state));
      }
      function insertStylesheetIntoRoot(root2, resource) {
        if (!(resource.state.loading & Inserted)) {
          var precedences = precedencesByRoot.get(root2);
          if (precedences) var last = precedences.get(LAST_PRECEDENCE);
          else {
            precedences = /* @__PURE__ */ new Map();
            precedencesByRoot.set(root2, precedences);
            for (var nodes = root2.querySelectorAll(
              "link[data-precedence],style[data-precedence]"
            ), i = 0; i < nodes.length; i++) {
              var node = nodes[i];
              if ("LINK" === node.nodeName || "not all" !== node.getAttribute("media"))
                precedences.set(node.dataset.precedence, node), last = node;
            }
            last && precedences.set(LAST_PRECEDENCE, last);
          }
          nodes = resource.instance;
          node = nodes.getAttribute("data-precedence");
          i = precedences.get(node) || last;
          i === last && precedences.set(LAST_PRECEDENCE, nodes);
          precedences.set(node, nodes);
          this.count++;
          last = onUnsuspend.bind(this);
          nodes.addEventListener("load", last);
          nodes.addEventListener("error", last);
          i ? i.parentNode.insertBefore(nodes, i.nextSibling) : (root2 = 9 === root2.nodeType ? root2.head : root2, root2.insertBefore(nodes, root2.firstChild));
          resource.state.loading |= Inserted;
        }
      }
      function FiberRootNode(containerInfo, tag, hydrate, identifierPrefix, onUncaughtError, onCaughtError, onRecoverableError, onDefaultTransitionIndicator, formState) {
        this.tag = 1;
        this.containerInfo = containerInfo;
        this.pingCache = this.current = this.pendingChildren = null;
        this.timeoutHandle = noTimeout;
        this.callbackNode = this.next = this.pendingContext = this.context = this.cancelPendingCommit = null;
        this.callbackPriority = 0;
        this.expirationTimes = createLaneMap(-1);
        this.entangledLanes = this.shellSuspendCounter = this.errorRecoveryDisabledLanes = this.expiredLanes = this.warmLanes = this.pingedLanes = this.suspendedLanes = this.pendingLanes = 0;
        this.entanglements = createLaneMap(0);
        this.hiddenUpdates = createLaneMap(null);
        this.identifierPrefix = identifierPrefix;
        this.onUncaughtError = onUncaughtError;
        this.onCaughtError = onCaughtError;
        this.onRecoverableError = onRecoverableError;
        this.pooledCache = null;
        this.pooledCacheLanes = 0;
        this.formState = formState;
        this.incompleteTransitions = /* @__PURE__ */ new Map();
        this.passiveEffectDuration = this.effectDuration = -0;
        this.memoizedUpdaters = /* @__PURE__ */ new Set();
        containerInfo = this.pendingUpdatersLaneMap = [];
        for (tag = 0; 31 > tag; tag++) containerInfo.push(/* @__PURE__ */ new Set());
        this._debugRootType = hydrate ? "hydrateRoot()" : "createRoot()";
      }
      function createFiberRoot(containerInfo, tag, hydrate, initialChildren, hydrationCallbacks, isStrictMode, identifierPrefix, formState, onUncaughtError, onCaughtError, onRecoverableError, onDefaultTransitionIndicator) {
        containerInfo = new FiberRootNode(
          containerInfo,
          tag,
          hydrate,
          identifierPrefix,
          onUncaughtError,
          onCaughtError,
          onRecoverableError,
          onDefaultTransitionIndicator,
          formState
        );
        tag = ConcurrentMode;
        true === isStrictMode && (tag |= StrictLegacyMode | StrictEffectsMode);
        tag |= ProfileMode;
        isStrictMode = createFiber(3, null, null, tag);
        containerInfo.current = isStrictMode;
        isStrictMode.stateNode = containerInfo;
        tag = createCache();
        retainCache(tag);
        containerInfo.pooledCache = tag;
        retainCache(tag);
        isStrictMode.memoizedState = {
          element: initialChildren,
          isDehydrated: hydrate,
          cache: tag
        };
        initializeUpdateQueue(isStrictMode);
        return containerInfo;
      }
      function getContextForSubtree(parentComponent) {
        if (!parentComponent) return emptyContextObject;
        parentComponent = emptyContextObject;
        return parentComponent;
      }
      function updateContainerImpl(rootFiber, lane, element, container, parentComponent, callback) {
        if (injectedHook && "function" === typeof injectedHook.onScheduleFiberRoot)
          try {
            injectedHook.onScheduleFiberRoot(rendererID, container, element);
          } catch (err) {
            hasLoggedError || (hasLoggedError = true, console.error(
              "React instrumentation encountered an error: %o",
              err
            ));
          }
        parentComponent = getContextForSubtree(parentComponent);
        null === container.context ? container.context = parentComponent : container.pendingContext = parentComponent;
        isRendering && null !== current && !didWarnAboutNestedUpdates && (didWarnAboutNestedUpdates = true, console.error(
          "Render methods should be a pure function of props and state; triggering nested component updates from render is not allowed. If necessary, trigger nested updates in componentDidUpdate.\n\nCheck the render method of %s.",
          getComponentNameFromFiber(current) || "Unknown"
        ));
        container = createUpdate(lane);
        container.payload = { element };
        callback = void 0 === callback ? null : callback;
        null !== callback && ("function" !== typeof callback && console.error(
          "Expected the last optional `callback` argument to be a function. Instead received: %s.",
          callback
        ), container.callback = callback);
        element = enqueueUpdate(rootFiber, container, lane);
        null !== element && (startUpdateTimerByLane(lane, "root.render()", null), scheduleUpdateOnFiber(element, rootFiber, lane), entangleTransitions(element, rootFiber, lane));
      }
      function markRetryLaneImpl(fiber, retryLane) {
        fiber = fiber.memoizedState;
        if (null !== fiber && null !== fiber.dehydrated) {
          var a2 = fiber.retryLane;
          fiber.retryLane = 0 !== a2 && a2 < retryLane ? a2 : retryLane;
        }
      }
      function markRetryLaneIfNotHydrated(fiber, retryLane) {
        markRetryLaneImpl(fiber, retryLane);
        (fiber = fiber.alternate) && markRetryLaneImpl(fiber, retryLane);
      }
      function attemptContinuousHydration(fiber) {
        if (13 === fiber.tag || 31 === fiber.tag) {
          var root2 = enqueueConcurrentRenderForLane(fiber, 67108864);
          null !== root2 && scheduleUpdateOnFiber(root2, fiber, 67108864);
          markRetryLaneIfNotHydrated(fiber, 67108864);
        }
      }
      function attemptHydrationAtCurrentPriority(fiber) {
        if (13 === fiber.tag || 31 === fiber.tag) {
          var lane = requestUpdateLane(fiber);
          lane = getBumpedLaneForHydrationByLane(lane);
          var root2 = enqueueConcurrentRenderForLane(fiber, lane);
          null !== root2 && scheduleUpdateOnFiber(root2, fiber, lane);
          markRetryLaneIfNotHydrated(fiber, lane);
        }
      }
      function getCurrentFiberForDevTools() {
        return current;
      }
      function dispatchDiscreteEvent(domEventName, eventSystemFlags, container, nativeEvent) {
        var prevTransition = ReactSharedInternals.T;
        ReactSharedInternals.T = null;
        var previousPriority = ReactDOMSharedInternals.p;
        try {
          ReactDOMSharedInternals.p = DiscreteEventPriority, dispatchEvent2(domEventName, eventSystemFlags, container, nativeEvent);
        } finally {
          ReactDOMSharedInternals.p = previousPriority, ReactSharedInternals.T = prevTransition;
        }
      }
      function dispatchContinuousEvent(domEventName, eventSystemFlags, container, nativeEvent) {
        var prevTransition = ReactSharedInternals.T;
        ReactSharedInternals.T = null;
        var previousPriority = ReactDOMSharedInternals.p;
        try {
          ReactDOMSharedInternals.p = ContinuousEventPriority, dispatchEvent2(domEventName, eventSystemFlags, container, nativeEvent);
        } finally {
          ReactDOMSharedInternals.p = previousPriority, ReactSharedInternals.T = prevTransition;
        }
      }
      function dispatchEvent2(domEventName, eventSystemFlags, targetContainer, nativeEvent) {
        if (_enabled) {
          var blockedOn = findInstanceBlockingEvent(nativeEvent);
          if (null === blockedOn)
            dispatchEventForPluginEventSystem(
              domEventName,
              eventSystemFlags,
              nativeEvent,
              return_targetInst,
              targetContainer
            ), clearIfContinuousEvent(domEventName, nativeEvent);
          else if (queueIfContinuousEvent(
            blockedOn,
            domEventName,
            eventSystemFlags,
            targetContainer,
            nativeEvent
          ))
            nativeEvent.stopPropagation();
          else if (clearIfContinuousEvent(domEventName, nativeEvent), eventSystemFlags & 4 && -1 < discreteReplayableEvents.indexOf(domEventName)) {
            for (; null !== blockedOn; ) {
              var fiber = getInstanceFromNode(blockedOn);
              if (null !== fiber)
                switch (fiber.tag) {
                  case 3:
                    fiber = fiber.stateNode;
                    if (fiber.current.memoizedState.isDehydrated) {
                      var lanes = getHighestPriorityLanes(fiber.pendingLanes);
                      if (0 !== lanes) {
                        var root2 = fiber;
                        root2.pendingLanes |= 2;
                        for (root2.entangledLanes |= 2; lanes; ) {
                          var lane = 1 << 31 - clz32(lanes);
                          root2.entanglements[1] |= lane;
                          lanes &= ~lane;
                        }
                        ensureRootIsScheduled(fiber);
                        (executionContext & (RenderContext | CommitContext)) === NoContext && (workInProgressRootRenderTargetTime = now$1() + RENDER_TIMEOUT_MS, flushSyncWorkAcrossRoots_impl(0, false));
                      }
                    }
                    break;
                  case 31:
                  case 13:
                    root2 = enqueueConcurrentRenderForLane(fiber, 2), null !== root2 && scheduleUpdateOnFiber(root2, fiber, 2), flushSyncWork$1(), markRetryLaneIfNotHydrated(fiber, 2);
                }
              fiber = findInstanceBlockingEvent(nativeEvent);
              null === fiber && dispatchEventForPluginEventSystem(
                domEventName,
                eventSystemFlags,
                nativeEvent,
                return_targetInst,
                targetContainer
              );
              if (fiber === blockedOn) break;
              blockedOn = fiber;
            }
            null !== blockedOn && nativeEvent.stopPropagation();
          } else
            dispatchEventForPluginEventSystem(
              domEventName,
              eventSystemFlags,
              nativeEvent,
              null,
              targetContainer
            );
        }
      }
      function findInstanceBlockingEvent(nativeEvent) {
        nativeEvent = getEventTarget(nativeEvent);
        return findInstanceBlockingTarget(nativeEvent);
      }
      function findInstanceBlockingTarget(targetNode) {
        return_targetInst = null;
        targetNode = getClosestInstanceFromNode(targetNode);
        if (null !== targetNode) {
          var nearestMounted = getNearestMountedFiber(targetNode);
          if (null === nearestMounted) targetNode = null;
          else {
            var tag = nearestMounted.tag;
            if (13 === tag) {
              targetNode = getSuspenseInstanceFromFiber(nearestMounted);
              if (null !== targetNode) return targetNode;
              targetNode = null;
            } else if (31 === tag) {
              targetNode = getActivityInstanceFromFiber(nearestMounted);
              if (null !== targetNode) return targetNode;
              targetNode = null;
            } else if (3 === tag) {
              if (nearestMounted.stateNode.current.memoizedState.isDehydrated)
                return 3 === nearestMounted.tag ? nearestMounted.stateNode.containerInfo : null;
              targetNode = null;
            } else nearestMounted !== targetNode && (targetNode = null);
          }
        }
        return_targetInst = targetNode;
        return null;
      }
      function getEventPriority(domEventName) {
        switch (domEventName) {
          case "beforetoggle":
          case "cancel":
          case "click":
          case "close":
          case "contextmenu":
          case "copy":
          case "cut":
          case "auxclick":
          case "dblclick":
          case "dragend":
          case "dragstart":
          case "drop":
          case "focusin":
          case "focusout":
          case "input":
          case "invalid":
          case "keydown":
          case "keypress":
          case "keyup":
          case "mousedown":
          case "mouseup":
          case "paste":
          case "pause":
          case "play":
          case "pointercancel":
          case "pointerdown":
          case "pointerup":
          case "ratechange":
          case "reset":
          case "resize":
          case "seeked":
          case "submit":
          case "toggle":
          case "touchcancel":
          case "touchend":
          case "touchstart":
          case "volumechange":
          case "change":
          case "selectionchange":
          case "textInput":
          case "compositionstart":
          case "compositionend":
          case "compositionupdate":
          case "beforeblur":
          case "afterblur":
          case "beforeinput":
          case "blur":
          case "fullscreenchange":
          case "focus":
          case "hashchange":
          case "popstate":
          case "select":
          case "selectstart":
            return DiscreteEventPriority;
          case "drag":
          case "dragenter":
          case "dragexit":
          case "dragleave":
          case "dragover":
          case "mousemove":
          case "mouseout":
          case "mouseover":
          case "pointermove":
          case "pointerout":
          case "pointerover":
          case "scroll":
          case "touchmove":
          case "wheel":
          case "mouseenter":
          case "mouseleave":
          case "pointerenter":
          case "pointerleave":
            return ContinuousEventPriority;
          case "message":
            switch (getCurrentPriorityLevel()) {
              case ImmediatePriority:
                return DiscreteEventPriority;
              case UserBlockingPriority:
                return ContinuousEventPriority;
              case NormalPriority$1:
              case LowPriority:
                return DefaultEventPriority;
              case IdlePriority:
                return IdleEventPriority;
              default:
                return DefaultEventPriority;
            }
          default:
            return DefaultEventPriority;
        }
      }
      function clearIfContinuousEvent(domEventName, nativeEvent) {
        switch (domEventName) {
          case "focusin":
          case "focusout":
            queuedFocus = null;
            break;
          case "dragenter":
          case "dragleave":
            queuedDrag = null;
            break;
          case "mouseover":
          case "mouseout":
            queuedMouse = null;
            break;
          case "pointerover":
          case "pointerout":
            queuedPointers.delete(nativeEvent.pointerId);
            break;
          case "gotpointercapture":
          case "lostpointercapture":
            queuedPointerCaptures.delete(nativeEvent.pointerId);
        }
      }
      function accumulateOrCreateContinuousQueuedReplayableEvent(existingQueuedEvent, blockedOn, domEventName, eventSystemFlags, targetContainer, nativeEvent) {
        if (null === existingQueuedEvent || existingQueuedEvent.nativeEvent !== nativeEvent)
          return existingQueuedEvent = {
            blockedOn,
            domEventName,
            eventSystemFlags,
            nativeEvent,
            targetContainers: [targetContainer]
          }, null !== blockedOn && (blockedOn = getInstanceFromNode(blockedOn), null !== blockedOn && attemptContinuousHydration(blockedOn)), existingQueuedEvent;
        existingQueuedEvent.eventSystemFlags |= eventSystemFlags;
        blockedOn = existingQueuedEvent.targetContainers;
        null !== targetContainer && -1 === blockedOn.indexOf(targetContainer) && blockedOn.push(targetContainer);
        return existingQueuedEvent;
      }
      function queueIfContinuousEvent(blockedOn, domEventName, eventSystemFlags, targetContainer, nativeEvent) {
        switch (domEventName) {
          case "focusin":
            return queuedFocus = accumulateOrCreateContinuousQueuedReplayableEvent(
              queuedFocus,
              blockedOn,
              domEventName,
              eventSystemFlags,
              targetContainer,
              nativeEvent
            ), true;
          case "dragenter":
            return queuedDrag = accumulateOrCreateContinuousQueuedReplayableEvent(
              queuedDrag,
              blockedOn,
              domEventName,
              eventSystemFlags,
              targetContainer,
              nativeEvent
            ), true;
          case "mouseover":
            return queuedMouse = accumulateOrCreateContinuousQueuedReplayableEvent(
              queuedMouse,
              blockedOn,
              domEventName,
              eventSystemFlags,
              targetContainer,
              nativeEvent
            ), true;
          case "pointerover":
            var pointerId = nativeEvent.pointerId;
            queuedPointers.set(
              pointerId,
              accumulateOrCreateContinuousQueuedReplayableEvent(
                queuedPointers.get(pointerId) || null,
                blockedOn,
                domEventName,
                eventSystemFlags,
                targetContainer,
                nativeEvent
              )
            );
            return true;
          case "gotpointercapture":
            return pointerId = nativeEvent.pointerId, queuedPointerCaptures.set(
              pointerId,
              accumulateOrCreateContinuousQueuedReplayableEvent(
                queuedPointerCaptures.get(pointerId) || null,
                blockedOn,
                domEventName,
                eventSystemFlags,
                targetContainer,
                nativeEvent
              )
            ), true;
        }
        return false;
      }
      function attemptExplicitHydrationTarget(queuedTarget) {
        var targetInst = getClosestInstanceFromNode(queuedTarget.target);
        if (null !== targetInst) {
          var nearestMounted = getNearestMountedFiber(targetInst);
          if (null !== nearestMounted) {
            if (targetInst = nearestMounted.tag, 13 === targetInst) {
              if (targetInst = getSuspenseInstanceFromFiber(nearestMounted), null !== targetInst) {
                queuedTarget.blockedOn = targetInst;
                runWithPriority(queuedTarget.priority, function() {
                  attemptHydrationAtCurrentPriority(nearestMounted);
                });
                return;
              }
            } else if (31 === targetInst) {
              if (targetInst = getActivityInstanceFromFiber(nearestMounted), null !== targetInst) {
                queuedTarget.blockedOn = targetInst;
                runWithPriority(queuedTarget.priority, function() {
                  attemptHydrationAtCurrentPriority(nearestMounted);
                });
                return;
              }
            } else if (3 === targetInst && nearestMounted.stateNode.current.memoizedState.isDehydrated) {
              queuedTarget.blockedOn = 3 === nearestMounted.tag ? nearestMounted.stateNode.containerInfo : null;
              return;
            }
          }
        }
        queuedTarget.blockedOn = null;
      }
      function attemptReplayContinuousQueuedEvent(queuedEvent) {
        if (null !== queuedEvent.blockedOn) return false;
        for (var targetContainers = queuedEvent.targetContainers; 0 < targetContainers.length; ) {
          var nextBlockedOn = findInstanceBlockingEvent(queuedEvent.nativeEvent);
          if (null === nextBlockedOn) {
            nextBlockedOn = queuedEvent.nativeEvent;
            var nativeEventClone = new nextBlockedOn.constructor(
              nextBlockedOn.type,
              nextBlockedOn
            ), event = nativeEventClone;
            null !== currentReplayingEvent && console.error(
              "Expected currently replaying event to be null. This error is likely caused by a bug in React. Please file an issue."
            );
            currentReplayingEvent = event;
            nextBlockedOn.target.dispatchEvent(nativeEventClone);
            null === currentReplayingEvent && console.error(
              "Expected currently replaying event to not be null. This error is likely caused by a bug in React. Please file an issue."
            );
            currentReplayingEvent = null;
          } else
            return targetContainers = getInstanceFromNode(nextBlockedOn), null !== targetContainers && attemptContinuousHydration(targetContainers), queuedEvent.blockedOn = nextBlockedOn, false;
          targetContainers.shift();
        }
        return true;
      }
      function attemptReplayContinuousQueuedEventInMap(queuedEvent, key, map2) {
        attemptReplayContinuousQueuedEvent(queuedEvent) && map2.delete(key);
      }
      function replayUnblockedEvents() {
        hasScheduledReplayAttempt = false;
        null !== queuedFocus && attemptReplayContinuousQueuedEvent(queuedFocus) && (queuedFocus = null);
        null !== queuedDrag && attemptReplayContinuousQueuedEvent(queuedDrag) && (queuedDrag = null);
        null !== queuedMouse && attemptReplayContinuousQueuedEvent(queuedMouse) && (queuedMouse = null);
        queuedPointers.forEach(attemptReplayContinuousQueuedEventInMap);
        queuedPointerCaptures.forEach(attemptReplayContinuousQueuedEventInMap);
      }
      function scheduleCallbackIfUnblocked(queuedEvent, unblocked) {
        queuedEvent.blockedOn === unblocked && (queuedEvent.blockedOn = null, hasScheduledReplayAttempt || (hasScheduledReplayAttempt = true, Scheduler.unstable_scheduleCallback(
          Scheduler.unstable_NormalPriority,
          replayUnblockedEvents
        )));
      }
      function scheduleReplayQueueIfNeeded(formReplayingQueue) {
        lastScheduledReplayQueue !== formReplayingQueue && (lastScheduledReplayQueue = formReplayingQueue, Scheduler.unstable_scheduleCallback(
          Scheduler.unstable_NormalPriority,
          function() {
            lastScheduledReplayQueue === formReplayingQueue && (lastScheduledReplayQueue = null);
            for (var i = 0; i < formReplayingQueue.length; i += 3) {
              var form = formReplayingQueue[i], submitterOrAction = formReplayingQueue[i + 1], formData = formReplayingQueue[i + 2];
              if ("function" !== typeof submitterOrAction)
                if (null === findInstanceBlockingTarget(submitterOrAction || form))
                  continue;
                else break;
              var formInst = getInstanceFromNode(form);
              null !== formInst && (formReplayingQueue.splice(i, 3), i -= 3, form = {
                pending: true,
                data: formData,
                method: form.method,
                action: submitterOrAction
              }, Object.freeze(form), startHostTransition(
                formInst,
                form,
                submitterOrAction,
                formData
              ));
            }
          }
        ));
      }
      function retryIfBlockedOn(unblocked) {
        function unblock(queuedEvent) {
          return scheduleCallbackIfUnblocked(queuedEvent, unblocked);
        }
        null !== queuedFocus && scheduleCallbackIfUnblocked(queuedFocus, unblocked);
        null !== queuedDrag && scheduleCallbackIfUnblocked(queuedDrag, unblocked);
        null !== queuedMouse && scheduleCallbackIfUnblocked(queuedMouse, unblocked);
        queuedPointers.forEach(unblock);
        queuedPointerCaptures.forEach(unblock);
        for (var i = 0; i < queuedExplicitHydrationTargets.length; i++) {
          var queuedTarget = queuedExplicitHydrationTargets[i];
          queuedTarget.blockedOn === unblocked && (queuedTarget.blockedOn = null);
        }
        for (; 0 < queuedExplicitHydrationTargets.length && (i = queuedExplicitHydrationTargets[0], null === i.blockedOn); )
          attemptExplicitHydrationTarget(i), null === i.blockedOn && queuedExplicitHydrationTargets.shift();
        i = (unblocked.ownerDocument || unblocked).$$reactFormReplay;
        if (null != i)
          for (queuedTarget = 0; queuedTarget < i.length; queuedTarget += 3) {
            var form = i[queuedTarget], submitterOrAction = i[queuedTarget + 1], formProps = form[internalPropsKey] || null;
            if ("function" === typeof submitterOrAction)
              formProps || scheduleReplayQueueIfNeeded(i);
            else if (formProps) {
              var action = null;
              if (submitterOrAction && submitterOrAction.hasAttribute("formAction"))
                if (form = submitterOrAction, formProps = submitterOrAction[internalPropsKey] || null)
                  action = formProps.formAction;
                else {
                  if (null !== findInstanceBlockingTarget(form)) continue;
                }
              else action = formProps.action;
              "function" === typeof action ? i[queuedTarget + 1] = action : (i.splice(queuedTarget, 3), queuedTarget -= 3);
              scheduleReplayQueueIfNeeded(i);
            }
          }
      }
      function defaultOnDefaultTransitionIndicator() {
        function handleNavigate(event) {
          event.canIntercept && "react-transition" === event.info && event.intercept({
            handler: function() {
              return new Promise(function(resolve) {
                return pendingResolve = resolve;
              });
            },
            focusReset: "manual",
            scroll: "manual"
          });
        }
        function handleNavigateComplete() {
          null !== pendingResolve && (pendingResolve(), pendingResolve = null);
          isCancelled || setTimeout(startFakeNavigation, 20);
        }
        function startFakeNavigation() {
          if (!isCancelled && !navigation.transition) {
            var currentEntry = navigation.currentEntry;
            currentEntry && null != currentEntry.url && navigation.navigate(currentEntry.url, {
              state: currentEntry.getState(),
              info: "react-transition",
              history: "replace"
            });
          }
        }
        if ("object" === typeof navigation) {
          var isCancelled = false, pendingResolve = null;
          navigation.addEventListener("navigate", handleNavigate);
          navigation.addEventListener("navigatesuccess", handleNavigateComplete);
          navigation.addEventListener("navigateerror", handleNavigateComplete);
          setTimeout(startFakeNavigation, 100);
          return function() {
            isCancelled = true;
            navigation.removeEventListener("navigate", handleNavigate);
            navigation.removeEventListener(
              "navigatesuccess",
              handleNavigateComplete
            );
            navigation.removeEventListener(
              "navigateerror",
              handleNavigateComplete
            );
            null !== pendingResolve && (pendingResolve(), pendingResolve = null);
          };
        }
      }
      function ReactDOMRoot(internalRoot) {
        this._internalRoot = internalRoot;
      }
      function ReactDOMHydrationRoot(internalRoot) {
        this._internalRoot = internalRoot;
      }
      function warnIfReactDOMContainerInDEV(container) {
        container[internalContainerInstanceKey] && (container._reactRootContainer ? console.error(
          "You are calling ReactDOMClient.createRoot() on a container that was previously passed to ReactDOM.render(). This is not supported."
        ) : console.error(
          "You are calling ReactDOMClient.createRoot() on a container that has already been passed to createRoot() before. Instead, call root.render() on the existing root instead if you want to update it."
        ));
      }
      "undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ && "function" === typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart && __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(Error());
      var Scheduler = require_scheduler(), React7 = require_react(), ReactDOM2 = require_react_dom(), assign = Object.assign, REACT_LEGACY_ELEMENT_TYPE = /* @__PURE__ */ Symbol.for("react.element"), REACT_ELEMENT_TYPE = /* @__PURE__ */ Symbol.for("react.transitional.element"), REACT_PORTAL_TYPE = /* @__PURE__ */ Symbol.for("react.portal"), REACT_FRAGMENT_TYPE = /* @__PURE__ */ Symbol.for("react.fragment"), REACT_STRICT_MODE_TYPE = /* @__PURE__ */ Symbol.for("react.strict_mode"), REACT_PROFILER_TYPE = /* @__PURE__ */ Symbol.for("react.profiler"), REACT_CONSUMER_TYPE = /* @__PURE__ */ Symbol.for("react.consumer"), REACT_CONTEXT_TYPE = /* @__PURE__ */ Symbol.for("react.context"), REACT_FORWARD_REF_TYPE = /* @__PURE__ */ Symbol.for("react.forward_ref"), REACT_SUSPENSE_TYPE = /* @__PURE__ */ Symbol.for("react.suspense"), REACT_SUSPENSE_LIST_TYPE = /* @__PURE__ */ Symbol.for("react.suspense_list"), REACT_MEMO_TYPE = /* @__PURE__ */ Symbol.for("react.memo"), REACT_LAZY_TYPE = /* @__PURE__ */ Symbol.for("react.lazy");
      /* @__PURE__ */ Symbol.for("react.scope");
      var REACT_ACTIVITY_TYPE = /* @__PURE__ */ Symbol.for("react.activity");
      /* @__PURE__ */ Symbol.for("react.legacy_hidden");
      /* @__PURE__ */ Symbol.for("react.tracing_marker");
      var REACT_MEMO_CACHE_SENTINEL = /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel");
      /* @__PURE__ */ Symbol.for("react.view_transition");
      var MAYBE_ITERATOR_SYMBOL = Symbol.iterator, REACT_CLIENT_REFERENCE = /* @__PURE__ */ Symbol.for("react.client.reference"), isArrayImpl = Array.isArray, ReactSharedInternals = React7.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE, ReactDOMSharedInternals = ReactDOM2.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE, NotPending = Object.freeze({
        pending: false,
        data: null,
        method: null,
        action: null
      }), valueStack = [];
      var fiberStack = [];
      var index$jscomp$0 = -1, contextStackCursor = createCursor(null), contextFiberStackCursor = createCursor(null), rootInstanceStackCursor = createCursor(null), hostTransitionProviderCursor = createCursor(null), disabledDepth = 0, prevLog, prevInfo, prevWarn, prevError, prevGroup, prevGroupCollapsed, prevGroupEnd;
      disabledLog.__reactDisabledLog = true;
      var prefix, suffix, reentry = false;
      var componentFrameCache = new ("function" === typeof WeakMap ? WeakMap : Map)();
      var current = null, isRendering = false, hasOwnProperty2 = Object.prototype.hasOwnProperty, scheduleCallback$3 = Scheduler.unstable_scheduleCallback, cancelCallback$1 = Scheduler.unstable_cancelCallback, shouldYield = Scheduler.unstable_shouldYield, requestPaint = Scheduler.unstable_requestPaint, now$1 = Scheduler.unstable_now, getCurrentPriorityLevel = Scheduler.unstable_getCurrentPriorityLevel, ImmediatePriority = Scheduler.unstable_ImmediatePriority, UserBlockingPriority = Scheduler.unstable_UserBlockingPriority, NormalPriority$1 = Scheduler.unstable_NormalPriority, LowPriority = Scheduler.unstable_LowPriority, IdlePriority = Scheduler.unstable_IdlePriority, log$1 = Scheduler.log, unstable_setDisableYieldValue = Scheduler.unstable_setDisableYieldValue, rendererID = null, injectedHook = null, hasLoggedError = false, isDevToolsPresent = "undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__, clz32 = Math.clz32 ? Math.clz32 : clz32Fallback, log = Math.log, LN2 = Math.LN2, nextTransitionUpdateLane = 256, nextTransitionDeferredLane = 262144, nextRetryLane = 4194304, DiscreteEventPriority = 2, ContinuousEventPriority = 8, DefaultEventPriority = 32, IdleEventPriority = 268435456, randomKey = Math.random().toString(36).slice(2), internalInstanceKey = "__reactFiber$" + randomKey, internalPropsKey = "__reactProps$" + randomKey, internalContainerInstanceKey = "__reactContainer$" + randomKey, internalEventHandlersKey = "__reactEvents$" + randomKey, internalEventHandlerListenersKey = "__reactListeners$" + randomKey, internalEventHandlesSetKey = "__reactHandles$" + randomKey, internalRootNodeResourcesKey = "__reactResources$" + randomKey, internalHoistableMarker = "__reactMarker$" + randomKey, allNativeEvents = /* @__PURE__ */ new Set(), registrationNameDependencies = {}, possibleRegistrationNames = {}, hasReadOnlyValue = {
        button: true,
        checkbox: true,
        image: true,
        hidden: true,
        radio: true,
        reset: true,
        submit: true
      }, VALID_ATTRIBUTE_NAME_REGEX = RegExp(
        "^[:A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD][:A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD\\-.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040]*$"
      ), illegalAttributeNameCache = {}, validatedAttributeNameCache = {}, escapeSelectorAttributeValueInsideDoubleQuotesRegex = /[\n"\\]/g, didWarnValueDefaultValue$1 = false, didWarnCheckedDefaultChecked = false, didWarnSelectedSetOnOption = false, didWarnInvalidChild = false, didWarnInvalidInnerHTML = false;
      var didWarnValueDefaultValue = false;
      var valuePropNames = ["value", "defaultValue"], didWarnValDefaultVal = false, needsEscaping = /["'&<>\n\t]|^\s|\s$/, specialTags = "address applet area article aside base basefont bgsound blockquote body br button caption center col colgroup dd details dir div dl dt embed fieldset figcaption figure footer form frame frameset h1 h2 h3 h4 h5 h6 head header hgroup hr html iframe img input isindex li link listing main marquee menu menuitem meta nav noembed noframes noscript object ol p param plaintext pre script section select source style summary table tbody td template textarea tfoot th thead title tr track ul wbr xmp".split(
        " "
      ), inScopeTags = "applet caption html table td th marquee object template foreignObject desc title".split(
        " "
      ), buttonScopeTags = inScopeTags.concat(["button"]), impliedEndTags = "dd dt li option optgroup p rp rt".split(" "), emptyAncestorInfoDev = {
        current: null,
        formTag: null,
        aTagInScope: null,
        buttonTagInScope: null,
        nobrTagInScope: null,
        pTagInButtonScope: null,
        listItemTagAutoclosing: null,
        dlItemTagAutoclosing: null,
        containerTagInScope: null,
        implicitRootScope: false
      }, didWarn = {}, shorthandToLonghand = {
        animation: "animationDelay animationDirection animationDuration animationFillMode animationIterationCount animationName animationPlayState animationTimingFunction".split(
          " "
        ),
        background: "backgroundAttachment backgroundClip backgroundColor backgroundImage backgroundOrigin backgroundPositionX backgroundPositionY backgroundRepeat backgroundSize".split(
          " "
        ),
        backgroundPosition: ["backgroundPositionX", "backgroundPositionY"],
        border: "borderBottomColor borderBottomStyle borderBottomWidth borderImageOutset borderImageRepeat borderImageSlice borderImageSource borderImageWidth borderLeftColor borderLeftStyle borderLeftWidth borderRightColor borderRightStyle borderRightWidth borderTopColor borderTopStyle borderTopWidth".split(
          " "
        ),
        borderBlockEnd: [
          "borderBlockEndColor",
          "borderBlockEndStyle",
          "borderBlockEndWidth"
        ],
        borderBlockStart: [
          "borderBlockStartColor",
          "borderBlockStartStyle",
          "borderBlockStartWidth"
        ],
        borderBottom: [
          "borderBottomColor",
          "borderBottomStyle",
          "borderBottomWidth"
        ],
        borderColor: [
          "borderBottomColor",
          "borderLeftColor",
          "borderRightColor",
          "borderTopColor"
        ],
        borderImage: [
          "borderImageOutset",
          "borderImageRepeat",
          "borderImageSlice",
          "borderImageSource",
          "borderImageWidth"
        ],
        borderInlineEnd: [
          "borderInlineEndColor",
          "borderInlineEndStyle",
          "borderInlineEndWidth"
        ],
        borderInlineStart: [
          "borderInlineStartColor",
          "borderInlineStartStyle",
          "borderInlineStartWidth"
        ],
        borderLeft: ["borderLeftColor", "borderLeftStyle", "borderLeftWidth"],
        borderRadius: [
          "borderBottomLeftRadius",
          "borderBottomRightRadius",
          "borderTopLeftRadius",
          "borderTopRightRadius"
        ],
        borderRight: [
          "borderRightColor",
          "borderRightStyle",
          "borderRightWidth"
        ],
        borderStyle: [
          "borderBottomStyle",
          "borderLeftStyle",
          "borderRightStyle",
          "borderTopStyle"
        ],
        borderTop: ["borderTopColor", "borderTopStyle", "borderTopWidth"],
        borderWidth: [
          "borderBottomWidth",
          "borderLeftWidth",
          "borderRightWidth",
          "borderTopWidth"
        ],
        columnRule: ["columnRuleColor", "columnRuleStyle", "columnRuleWidth"],
        columns: ["columnCount", "columnWidth"],
        flex: ["flexBasis", "flexGrow", "flexShrink"],
        flexFlow: ["flexDirection", "flexWrap"],
        font: "fontFamily fontFeatureSettings fontKerning fontLanguageOverride fontSize fontSizeAdjust fontStretch fontStyle fontVariant fontVariantAlternates fontVariantCaps fontVariantEastAsian fontVariantLigatures fontVariantNumeric fontVariantPosition fontWeight lineHeight".split(
          " "
        ),
        fontVariant: "fontVariantAlternates fontVariantCaps fontVariantEastAsian fontVariantLigatures fontVariantNumeric fontVariantPosition".split(
          " "
        ),
        gap: ["columnGap", "rowGap"],
        grid: "gridAutoColumns gridAutoFlow gridAutoRows gridTemplateAreas gridTemplateColumns gridTemplateRows".split(
          " "
        ),
        gridArea: [
          "gridColumnEnd",
          "gridColumnStart",
          "gridRowEnd",
          "gridRowStart"
        ],
        gridColumn: ["gridColumnEnd", "gridColumnStart"],
        gridColumnGap: ["columnGap"],
        gridGap: ["columnGap", "rowGap"],
        gridRow: ["gridRowEnd", "gridRowStart"],
        gridRowGap: ["rowGap"],
        gridTemplate: [
          "gridTemplateAreas",
          "gridTemplateColumns",
          "gridTemplateRows"
        ],
        listStyle: ["listStyleImage", "listStylePosition", "listStyleType"],
        margin: ["marginBottom", "marginLeft", "marginRight", "marginTop"],
        marker: ["markerEnd", "markerMid", "markerStart"],
        mask: "maskClip maskComposite maskImage maskMode maskOrigin maskPositionX maskPositionY maskRepeat maskSize".split(
          " "
        ),
        maskPosition: ["maskPositionX", "maskPositionY"],
        outline: ["outlineColor", "outlineStyle", "outlineWidth"],
        overflow: ["overflowX", "overflowY"],
        padding: ["paddingBottom", "paddingLeft", "paddingRight", "paddingTop"],
        placeContent: ["alignContent", "justifyContent"],
        placeItems: ["alignItems", "justifyItems"],
        placeSelf: ["alignSelf", "justifySelf"],
        textDecoration: [
          "textDecorationColor",
          "textDecorationLine",
          "textDecorationStyle"
        ],
        textEmphasis: ["textEmphasisColor", "textEmphasisStyle"],
        transition: [
          "transitionDelay",
          "transitionDuration",
          "transitionProperty",
          "transitionTimingFunction"
        ],
        wordWrap: ["overflowWrap"]
      }, uppercasePattern = /([A-Z])/g, msPattern$1 = /^ms-/, badVendoredStyleNamePattern = /^(?:webkit|moz|o)[A-Z]/, msPattern = /^-ms-/, hyphenPattern = /-(.)/g, badStyleValueWithSemicolonPattern = /;\s*$/, warnedStyleNames = {}, warnedStyleValues = {}, warnedForNaNValue = false, warnedForInfinityValue = false, unitlessNumbers = new Set(
        "animationIterationCount aspectRatio borderImageOutset borderImageSlice borderImageWidth boxFlex boxFlexGroup boxOrdinalGroup columnCount columns flex flexGrow flexPositive flexShrink flexNegative flexOrder gridArea gridRow gridRowEnd gridRowSpan gridRowStart gridColumn gridColumnEnd gridColumnSpan gridColumnStart fontWeight lineClamp lineHeight opacity order orphans scale tabSize widows zIndex zoom fillOpacity floodOpacity stopOpacity strokeDasharray strokeDashoffset strokeMiterlimit strokeOpacity strokeWidth MozAnimationIterationCount MozBoxFlex MozBoxFlexGroup MozLineClamp msAnimationIterationCount msFlex msZoom msFlexGrow msFlexNegative msFlexOrder msFlexPositive msFlexShrink msGridColumn msGridColumnSpan msGridRow msGridRowSpan WebkitAnimationIterationCount WebkitBoxFlex WebKitBoxFlexGroup WebkitBoxOrdinalGroup WebkitColumnCount WebkitColumns WebkitFlex WebkitFlexGrow WebkitFlexPositive WebkitFlexShrink WebkitLineClamp".split(
          " "
        )
      ), MATH_NAMESPACE = "http://www.w3.org/1998/Math/MathML", SVG_NAMESPACE = "http://www.w3.org/2000/svg", aliases = /* @__PURE__ */ new Map([
        ["acceptCharset", "accept-charset"],
        ["htmlFor", "for"],
        ["httpEquiv", "http-equiv"],
        ["crossOrigin", "crossorigin"],
        ["accentHeight", "accent-height"],
        ["alignmentBaseline", "alignment-baseline"],
        ["arabicForm", "arabic-form"],
        ["baselineShift", "baseline-shift"],
        ["capHeight", "cap-height"],
        ["clipPath", "clip-path"],
        ["clipRule", "clip-rule"],
        ["colorInterpolation", "color-interpolation"],
        ["colorInterpolationFilters", "color-interpolation-filters"],
        ["colorProfile", "color-profile"],
        ["colorRendering", "color-rendering"],
        ["dominantBaseline", "dominant-baseline"],
        ["enableBackground", "enable-background"],
        ["fillOpacity", "fill-opacity"],
        ["fillRule", "fill-rule"],
        ["floodColor", "flood-color"],
        ["floodOpacity", "flood-opacity"],
        ["fontFamily", "font-family"],
        ["fontSize", "font-size"],
        ["fontSizeAdjust", "font-size-adjust"],
        ["fontStretch", "font-stretch"],
        ["fontStyle", "font-style"],
        ["fontVariant", "font-variant"],
        ["fontWeight", "font-weight"],
        ["glyphName", "glyph-name"],
        ["glyphOrientationHorizontal", "glyph-orientation-horizontal"],
        ["glyphOrientationVertical", "glyph-orientation-vertical"],
        ["horizAdvX", "horiz-adv-x"],
        ["horizOriginX", "horiz-origin-x"],
        ["imageRendering", "image-rendering"],
        ["letterSpacing", "letter-spacing"],
        ["lightingColor", "lighting-color"],
        ["markerEnd", "marker-end"],
        ["markerMid", "marker-mid"],
        ["markerStart", "marker-start"],
        ["overlinePosition", "overline-position"],
        ["overlineThickness", "overline-thickness"],
        ["paintOrder", "paint-order"],
        ["panose-1", "panose-1"],
        ["pointerEvents", "pointer-events"],
        ["renderingIntent", "rendering-intent"],
        ["shapeRendering", "shape-rendering"],
        ["stopColor", "stop-color"],
        ["stopOpacity", "stop-opacity"],
        ["strikethroughPosition", "strikethrough-position"],
        ["strikethroughThickness", "strikethrough-thickness"],
        ["strokeDasharray", "stroke-dasharray"],
        ["strokeDashoffset", "stroke-dashoffset"],
        ["strokeLinecap", "stroke-linecap"],
        ["strokeLinejoin", "stroke-linejoin"],
        ["strokeMiterlimit", "stroke-miterlimit"],
        ["strokeOpacity", "stroke-opacity"],
        ["strokeWidth", "stroke-width"],
        ["textAnchor", "text-anchor"],
        ["textDecoration", "text-decoration"],
        ["textRendering", "text-rendering"],
        ["transformOrigin", "transform-origin"],
        ["underlinePosition", "underline-position"],
        ["underlineThickness", "underline-thickness"],
        ["unicodeBidi", "unicode-bidi"],
        ["unicodeRange", "unicode-range"],
        ["unitsPerEm", "units-per-em"],
        ["vAlphabetic", "v-alphabetic"],
        ["vHanging", "v-hanging"],
        ["vIdeographic", "v-ideographic"],
        ["vMathematical", "v-mathematical"],
        ["vectorEffect", "vector-effect"],
        ["vertAdvY", "vert-adv-y"],
        ["vertOriginX", "vert-origin-x"],
        ["vertOriginY", "vert-origin-y"],
        ["wordSpacing", "word-spacing"],
        ["writingMode", "writing-mode"],
        ["xmlnsXlink", "xmlns:xlink"],
        ["xHeight", "x-height"]
      ]), possibleStandardNames = {
        accept: "accept",
        acceptcharset: "acceptCharset",
        "accept-charset": "acceptCharset",
        accesskey: "accessKey",
        action: "action",
        allowfullscreen: "allowFullScreen",
        alt: "alt",
        as: "as",
        async: "async",
        autocapitalize: "autoCapitalize",
        autocomplete: "autoComplete",
        autocorrect: "autoCorrect",
        autofocus: "autoFocus",
        autoplay: "autoPlay",
        autosave: "autoSave",
        capture: "capture",
        cellpadding: "cellPadding",
        cellspacing: "cellSpacing",
        challenge: "challenge",
        charset: "charSet",
        checked: "checked",
        children: "children",
        cite: "cite",
        class: "className",
        classid: "classID",
        classname: "className",
        cols: "cols",
        colspan: "colSpan",
        content: "content",
        contenteditable: "contentEditable",
        contextmenu: "contextMenu",
        controls: "controls",
        controlslist: "controlsList",
        coords: "coords",
        crossorigin: "crossOrigin",
        dangerouslysetinnerhtml: "dangerouslySetInnerHTML",
        data: "data",
        datetime: "dateTime",
        default: "default",
        defaultchecked: "defaultChecked",
        defaultvalue: "defaultValue",
        defer: "defer",
        dir: "dir",
        disabled: "disabled",
        disablepictureinpicture: "disablePictureInPicture",
        disableremoteplayback: "disableRemotePlayback",
        download: "download",
        draggable: "draggable",
        enctype: "encType",
        enterkeyhint: "enterKeyHint",
        fetchpriority: "fetchPriority",
        for: "htmlFor",
        form: "form",
        formmethod: "formMethod",
        formaction: "formAction",
        formenctype: "formEncType",
        formnovalidate: "formNoValidate",
        formtarget: "formTarget",
        frameborder: "frameBorder",
        headers: "headers",
        height: "height",
        hidden: "hidden",
        high: "high",
        href: "href",
        hreflang: "hrefLang",
        htmlfor: "htmlFor",
        httpequiv: "httpEquiv",
        "http-equiv": "httpEquiv",
        icon: "icon",
        id: "id",
        imagesizes: "imageSizes",
        imagesrcset: "imageSrcSet",
        inert: "inert",
        innerhtml: "innerHTML",
        inputmode: "inputMode",
        integrity: "integrity",
        is: "is",
        itemid: "itemID",
        itemprop: "itemProp",
        itemref: "itemRef",
        itemscope: "itemScope",
        itemtype: "itemType",
        keyparams: "keyParams",
        keytype: "keyType",
        kind: "kind",
        label: "label",
        lang: "lang",
        list: "list",
        loop: "loop",
        low: "low",
        manifest: "manifest",
        marginwidth: "marginWidth",
        marginheight: "marginHeight",
        max: "max",
        maxlength: "maxLength",
        media: "media",
        mediagroup: "mediaGroup",
        method: "method",
        min: "min",
        minlength: "minLength",
        multiple: "multiple",
        muted: "muted",
        name: "name",
        nomodule: "noModule",
        nonce: "nonce",
        novalidate: "noValidate",
        open: "open",
        optimum: "optimum",
        pattern: "pattern",
        placeholder: "placeholder",
        playsinline: "playsInline",
        poster: "poster",
        preload: "preload",
        profile: "profile",
        radiogroup: "radioGroup",
        readonly: "readOnly",
        referrerpolicy: "referrerPolicy",
        rel: "rel",
        required: "required",
        reversed: "reversed",
        role: "role",
        rows: "rows",
        rowspan: "rowSpan",
        sandbox: "sandbox",
        scope: "scope",
        scoped: "scoped",
        scrolling: "scrolling",
        seamless: "seamless",
        selected: "selected",
        shape: "shape",
        size: "size",
        sizes: "sizes",
        span: "span",
        spellcheck: "spellCheck",
        src: "src",
        srcdoc: "srcDoc",
        srclang: "srcLang",
        srcset: "srcSet",
        start: "start",
        step: "step",
        style: "style",
        summary: "summary",
        tabindex: "tabIndex",
        target: "target",
        title: "title",
        type: "type",
        usemap: "useMap",
        value: "value",
        width: "width",
        wmode: "wmode",
        wrap: "wrap",
        about: "about",
        accentheight: "accentHeight",
        "accent-height": "accentHeight",
        accumulate: "accumulate",
        additive: "additive",
        alignmentbaseline: "alignmentBaseline",
        "alignment-baseline": "alignmentBaseline",
        allowreorder: "allowReorder",
        alphabetic: "alphabetic",
        amplitude: "amplitude",
        arabicform: "arabicForm",
        "arabic-form": "arabicForm",
        ascent: "ascent",
        attributename: "attributeName",
        attributetype: "attributeType",
        autoreverse: "autoReverse",
        azimuth: "azimuth",
        basefrequency: "baseFrequency",
        baselineshift: "baselineShift",
        "baseline-shift": "baselineShift",
        baseprofile: "baseProfile",
        bbox: "bbox",
        begin: "begin",
        bias: "bias",
        by: "by",
        calcmode: "calcMode",
        capheight: "capHeight",
        "cap-height": "capHeight",
        clip: "clip",
        clippath: "clipPath",
        "clip-path": "clipPath",
        clippathunits: "clipPathUnits",
        cliprule: "clipRule",
        "clip-rule": "clipRule",
        color: "color",
        colorinterpolation: "colorInterpolation",
        "color-interpolation": "colorInterpolation",
        colorinterpolationfilters: "colorInterpolationFilters",
        "color-interpolation-filters": "colorInterpolationFilters",
        colorprofile: "colorProfile",
        "color-profile": "colorProfile",
        colorrendering: "colorRendering",
        "color-rendering": "colorRendering",
        contentscripttype: "contentScriptType",
        contentstyletype: "contentStyleType",
        cursor: "cursor",
        cx: "cx",
        cy: "cy",
        d: "d",
        datatype: "datatype",
        decelerate: "decelerate",
        descent: "descent",
        diffuseconstant: "diffuseConstant",
        direction: "direction",
        display: "display",
        divisor: "divisor",
        dominantbaseline: "dominantBaseline",
        "dominant-baseline": "dominantBaseline",
        dur: "dur",
        dx: "dx",
        dy: "dy",
        edgemode: "edgeMode",
        elevation: "elevation",
        enablebackground: "enableBackground",
        "enable-background": "enableBackground",
        end: "end",
        exponent: "exponent",
        externalresourcesrequired: "externalResourcesRequired",
        fill: "fill",
        fillopacity: "fillOpacity",
        "fill-opacity": "fillOpacity",
        fillrule: "fillRule",
        "fill-rule": "fillRule",
        filter: "filter",
        filterres: "filterRes",
        filterunits: "filterUnits",
        floodopacity: "floodOpacity",
        "flood-opacity": "floodOpacity",
        floodcolor: "floodColor",
        "flood-color": "floodColor",
        focusable: "focusable",
        fontfamily: "fontFamily",
        "font-family": "fontFamily",
        fontsize: "fontSize",
        "font-size": "fontSize",
        fontsizeadjust: "fontSizeAdjust",
        "font-size-adjust": "fontSizeAdjust",
        fontstretch: "fontStretch",
        "font-stretch": "fontStretch",
        fontstyle: "fontStyle",
        "font-style": "fontStyle",
        fontvariant: "fontVariant",
        "font-variant": "fontVariant",
        fontweight: "fontWeight",
        "font-weight": "fontWeight",
        format: "format",
        from: "from",
        fx: "fx",
        fy: "fy",
        g1: "g1",
        g2: "g2",
        glyphname: "glyphName",
        "glyph-name": "glyphName",
        glyphorientationhorizontal: "glyphOrientationHorizontal",
        "glyph-orientation-horizontal": "glyphOrientationHorizontal",
        glyphorientationvertical: "glyphOrientationVertical",
        "glyph-orientation-vertical": "glyphOrientationVertical",
        glyphref: "glyphRef",
        gradienttransform: "gradientTransform",
        gradientunits: "gradientUnits",
        hanging: "hanging",
        horizadvx: "horizAdvX",
        "horiz-adv-x": "horizAdvX",
        horizoriginx: "horizOriginX",
        "horiz-origin-x": "horizOriginX",
        ideographic: "ideographic",
        imagerendering: "imageRendering",
        "image-rendering": "imageRendering",
        in2: "in2",
        in: "in",
        inlist: "inlist",
        intercept: "intercept",
        k1: "k1",
        k2: "k2",
        k3: "k3",
        k4: "k4",
        k: "k",
        kernelmatrix: "kernelMatrix",
        kernelunitlength: "kernelUnitLength",
        kerning: "kerning",
        keypoints: "keyPoints",
        keysplines: "keySplines",
        keytimes: "keyTimes",
        lengthadjust: "lengthAdjust",
        letterspacing: "letterSpacing",
        "letter-spacing": "letterSpacing",
        lightingcolor: "lightingColor",
        "lighting-color": "lightingColor",
        limitingconeangle: "limitingConeAngle",
        local: "local",
        markerend: "markerEnd",
        "marker-end": "markerEnd",
        markerheight: "markerHeight",
        markermid: "markerMid",
        "marker-mid": "markerMid",
        markerstart: "markerStart",
        "marker-start": "markerStart",
        markerunits: "markerUnits",
        markerwidth: "markerWidth",
        mask: "mask",
        maskcontentunits: "maskContentUnits",
        maskunits: "maskUnits",
        mathematical: "mathematical",
        mode: "mode",
        numoctaves: "numOctaves",
        offset: "offset",
        opacity: "opacity",
        operator: "operator",
        order: "order",
        orient: "orient",
        orientation: "orientation",
        origin: "origin",
        overflow: "overflow",
        overlineposition: "overlinePosition",
        "overline-position": "overlinePosition",
        overlinethickness: "overlineThickness",
        "overline-thickness": "overlineThickness",
        paintorder: "paintOrder",
        "paint-order": "paintOrder",
        panose1: "panose1",
        "panose-1": "panose1",
        pathlength: "pathLength",
        patterncontentunits: "patternContentUnits",
        patterntransform: "patternTransform",
        patternunits: "patternUnits",
        pointerevents: "pointerEvents",
        "pointer-events": "pointerEvents",
        points: "points",
        pointsatx: "pointsAtX",
        pointsaty: "pointsAtY",
        pointsatz: "pointsAtZ",
        popover: "popover",
        popovertarget: "popoverTarget",
        popovertargetaction: "popoverTargetAction",
        prefix: "prefix",
        preservealpha: "preserveAlpha",
        preserveaspectratio: "preserveAspectRatio",
        primitiveunits: "primitiveUnits",
        property: "property",
        r: "r",
        radius: "radius",
        refx: "refX",
        refy: "refY",
        renderingintent: "renderingIntent",
        "rendering-intent": "renderingIntent",
        repeatcount: "repeatCount",
        repeatdur: "repeatDur",
        requiredextensions: "requiredExtensions",
        requiredfeatures: "requiredFeatures",
        resource: "resource",
        restart: "restart",
        result: "result",
        results: "results",
        rotate: "rotate",
        rx: "rx",
        ry: "ry",
        scale: "scale",
        security: "security",
        seed: "seed",
        shaperendering: "shapeRendering",
        "shape-rendering": "shapeRendering",
        slope: "slope",
        spacing: "spacing",
        specularconstant: "specularConstant",
        specularexponent: "specularExponent",
        speed: "speed",
        spreadmethod: "spreadMethod",
        startoffset: "startOffset",
        stddeviation: "stdDeviation",
        stemh: "stemh",
        stemv: "stemv",
        stitchtiles: "stitchTiles",
        stopcolor: "stopColor",
        "stop-color": "stopColor",
        stopopacity: "stopOpacity",
        "stop-opacity": "stopOpacity",
        strikethroughposition: "strikethroughPosition",
        "strikethrough-position": "strikethroughPosition",
        strikethroughthickness: "strikethroughThickness",
        "strikethrough-thickness": "strikethroughThickness",
        string: "string",
        stroke: "stroke",
        strokedasharray: "strokeDasharray",
        "stroke-dasharray": "strokeDasharray",
        strokedashoffset: "strokeDashoffset",
        "stroke-dashoffset": "strokeDashoffset",
        strokelinecap: "strokeLinecap",
        "stroke-linecap": "strokeLinecap",
        strokelinejoin: "strokeLinejoin",
        "stroke-linejoin": "strokeLinejoin",
        strokemiterlimit: "strokeMiterlimit",
        "stroke-miterlimit": "strokeMiterlimit",
        strokewidth: "strokeWidth",
        "stroke-width": "strokeWidth",
        strokeopacity: "strokeOpacity",
        "stroke-opacity": "strokeOpacity",
        suppresscontenteditablewarning: "suppressContentEditableWarning",
        suppresshydrationwarning: "suppressHydrationWarning",
        surfacescale: "surfaceScale",
        systemlanguage: "systemLanguage",
        tablevalues: "tableValues",
        targetx: "targetX",
        targety: "targetY",
        textanchor: "textAnchor",
        "text-anchor": "textAnchor",
        textdecoration: "textDecoration",
        "text-decoration": "textDecoration",
        textlength: "textLength",
        textrendering: "textRendering",
        "text-rendering": "textRendering",
        to: "to",
        transform: "transform",
        transformorigin: "transformOrigin",
        "transform-origin": "transformOrigin",
        typeof: "typeof",
        u1: "u1",
        u2: "u2",
        underlineposition: "underlinePosition",
        "underline-position": "underlinePosition",
        underlinethickness: "underlineThickness",
        "underline-thickness": "underlineThickness",
        unicode: "unicode",
        unicodebidi: "unicodeBidi",
        "unicode-bidi": "unicodeBidi",
        unicoderange: "unicodeRange",
        "unicode-range": "unicodeRange",
        unitsperem: "unitsPerEm",
        "units-per-em": "unitsPerEm",
        unselectable: "unselectable",
        valphabetic: "vAlphabetic",
        "v-alphabetic": "vAlphabetic",
        values: "values",
        vectoreffect: "vectorEffect",
        "vector-effect": "vectorEffect",
        version: "version",
        vertadvy: "vertAdvY",
        "vert-adv-y": "vertAdvY",
        vertoriginx: "vertOriginX",
        "vert-origin-x": "vertOriginX",
        vertoriginy: "vertOriginY",
        "vert-origin-y": "vertOriginY",
        vhanging: "vHanging",
        "v-hanging": "vHanging",
        videographic: "vIdeographic",
        "v-ideographic": "vIdeographic",
        viewbox: "viewBox",
        viewtarget: "viewTarget",
        visibility: "visibility",
        vmathematical: "vMathematical",
        "v-mathematical": "vMathematical",
        vocab: "vocab",
        widths: "widths",
        wordspacing: "wordSpacing",
        "word-spacing": "wordSpacing",
        writingmode: "writingMode",
        "writing-mode": "writingMode",
        x1: "x1",
        x2: "x2",
        x: "x",
        xchannelselector: "xChannelSelector",
        xheight: "xHeight",
        "x-height": "xHeight",
        xlinkactuate: "xlinkActuate",
        "xlink:actuate": "xlinkActuate",
        xlinkarcrole: "xlinkArcrole",
        "xlink:arcrole": "xlinkArcrole",
        xlinkhref: "xlinkHref",
        "xlink:href": "xlinkHref",
        xlinkrole: "xlinkRole",
        "xlink:role": "xlinkRole",
        xlinkshow: "xlinkShow",
        "xlink:show": "xlinkShow",
        xlinktitle: "xlinkTitle",
        "xlink:title": "xlinkTitle",
        xlinktype: "xlinkType",
        "xlink:type": "xlinkType",
        xmlbase: "xmlBase",
        "xml:base": "xmlBase",
        xmllang: "xmlLang",
        "xml:lang": "xmlLang",
        xmlns: "xmlns",
        "xml:space": "xmlSpace",
        xmlnsxlink: "xmlnsXlink",
        "xmlns:xlink": "xmlnsXlink",
        xmlspace: "xmlSpace",
        y1: "y1",
        y2: "y2",
        y: "y",
        ychannelselector: "yChannelSelector",
        z: "z",
        zoomandpan: "zoomAndPan"
      }, ariaProperties = {
        "aria-current": 0,
        "aria-description": 0,
        "aria-details": 0,
        "aria-disabled": 0,
        "aria-hidden": 0,
        "aria-invalid": 0,
        "aria-keyshortcuts": 0,
        "aria-label": 0,
        "aria-roledescription": 0,
        "aria-autocomplete": 0,
        "aria-checked": 0,
        "aria-expanded": 0,
        "aria-haspopup": 0,
        "aria-level": 0,
        "aria-modal": 0,
        "aria-multiline": 0,
        "aria-multiselectable": 0,
        "aria-orientation": 0,
        "aria-placeholder": 0,
        "aria-pressed": 0,
        "aria-readonly": 0,
        "aria-required": 0,
        "aria-selected": 0,
        "aria-sort": 0,
        "aria-valuemax": 0,
        "aria-valuemin": 0,
        "aria-valuenow": 0,
        "aria-valuetext": 0,
        "aria-atomic": 0,
        "aria-busy": 0,
        "aria-live": 0,
        "aria-relevant": 0,
        "aria-dropeffect": 0,
        "aria-grabbed": 0,
        "aria-activedescendant": 0,
        "aria-colcount": 0,
        "aria-colindex": 0,
        "aria-colspan": 0,
        "aria-controls": 0,
        "aria-describedby": 0,
        "aria-errormessage": 0,
        "aria-flowto": 0,
        "aria-labelledby": 0,
        "aria-owns": 0,
        "aria-posinset": 0,
        "aria-rowcount": 0,
        "aria-rowindex": 0,
        "aria-rowspan": 0,
        "aria-setsize": 0,
        "aria-braillelabel": 0,
        "aria-brailleroledescription": 0,
        "aria-colindextext": 0,
        "aria-rowindextext": 0
      }, warnedProperties$1 = {}, rARIA$1 = RegExp(
        "^(aria)-[:A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD\\-.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040]*$"
      ), rARIACamel$1 = RegExp(
        "^(aria)[A-Z][:A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD\\-.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040]*$"
      ), didWarnValueNull = false, warnedProperties = {}, EVENT_NAME_REGEX = /^on./, INVALID_EVENT_NAME_REGEX = /^on[^A-Z]/, rARIA = RegExp(
        "^(aria)-[:A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD\\-.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040]*$"
      ), rARIACamel = RegExp(
        "^(aria)[A-Z][:A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD\\-.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040]*$"
      ), isJavaScriptProtocol = /^[\u0000-\u001F ]*j[\r\n\t]*a[\r\n\t]*v[\r\n\t]*a[\r\n\t]*s[\r\n\t]*c[\r\n\t]*r[\r\n\t]*i[\r\n\t]*p[\r\n\t]*t[\r\n\t]*:/i, currentReplayingEvent = null, restoreTarget = null, restoreQueue = null, isInsideEventHandler = false, canUseDOM = !("undefined" === typeof window || "undefined" === typeof window.document || "undefined" === typeof window.document.createElement), passiveBrowserEventsSupported = false;
      if (canUseDOM)
        try {
          var options$jscomp$0 = {};
          Object.defineProperty(options$jscomp$0, "passive", {
            get: function() {
              passiveBrowserEventsSupported = true;
            }
          });
          window.addEventListener("test", options$jscomp$0, options$jscomp$0);
          window.removeEventListener("test", options$jscomp$0, options$jscomp$0);
        } catch (e) {
          passiveBrowserEventsSupported = false;
        }
      var root = null, startText = null, fallbackText = null, EventInterface = {
        eventPhase: 0,
        bubbles: 0,
        cancelable: 0,
        timeStamp: function(event) {
          return event.timeStamp || Date.now();
        },
        defaultPrevented: 0,
        isTrusted: 0
      }, SyntheticEvent = createSyntheticEvent(EventInterface), UIEventInterface = assign({}, EventInterface, { view: 0, detail: 0 }), SyntheticUIEvent = createSyntheticEvent(UIEventInterface), lastMovementX, lastMovementY, lastMouseEvent, MouseEventInterface = assign({}, UIEventInterface, {
        screenX: 0,
        screenY: 0,
        clientX: 0,
        clientY: 0,
        pageX: 0,
        pageY: 0,
        ctrlKey: 0,
        shiftKey: 0,
        altKey: 0,
        metaKey: 0,
        getModifierState: getEventModifierState,
        button: 0,
        buttons: 0,
        relatedTarget: function(event) {
          return void 0 === event.relatedTarget ? event.fromElement === event.srcElement ? event.toElement : event.fromElement : event.relatedTarget;
        },
        movementX: function(event) {
          if ("movementX" in event) return event.movementX;
          event !== lastMouseEvent && (lastMouseEvent && "mousemove" === event.type ? (lastMovementX = event.screenX - lastMouseEvent.screenX, lastMovementY = event.screenY - lastMouseEvent.screenY) : lastMovementY = lastMovementX = 0, lastMouseEvent = event);
          return lastMovementX;
        },
        movementY: function(event) {
          return "movementY" in event ? event.movementY : lastMovementY;
        }
      }), SyntheticMouseEvent = createSyntheticEvent(MouseEventInterface), DragEventInterface = assign({}, MouseEventInterface, { dataTransfer: 0 }), SyntheticDragEvent = createSyntheticEvent(DragEventInterface), FocusEventInterface = assign({}, UIEventInterface, { relatedTarget: 0 }), SyntheticFocusEvent = createSyntheticEvent(FocusEventInterface), AnimationEventInterface = assign({}, EventInterface, {
        animationName: 0,
        elapsedTime: 0,
        pseudoElement: 0
      }), SyntheticAnimationEvent = createSyntheticEvent(AnimationEventInterface), ClipboardEventInterface = assign({}, EventInterface, {
        clipboardData: function(event) {
          return "clipboardData" in event ? event.clipboardData : window.clipboardData;
        }
      }), SyntheticClipboardEvent = createSyntheticEvent(ClipboardEventInterface), CompositionEventInterface = assign({}, EventInterface, { data: 0 }), SyntheticCompositionEvent = createSyntheticEvent(
        CompositionEventInterface
      ), SyntheticInputEvent = SyntheticCompositionEvent, normalizeKey = {
        Esc: "Escape",
        Spacebar: " ",
        Left: "ArrowLeft",
        Up: "ArrowUp",
        Right: "ArrowRight",
        Down: "ArrowDown",
        Del: "Delete",
        Win: "OS",
        Menu: "ContextMenu",
        Apps: "ContextMenu",
        Scroll: "ScrollLock",
        MozPrintableKey: "Unidentified"
      }, translateToKey = {
        8: "Backspace",
        9: "Tab",
        12: "Clear",
        13: "Enter",
        16: "Shift",
        17: "Control",
        18: "Alt",
        19: "Pause",
        20: "CapsLock",
        27: "Escape",
        32: " ",
        33: "PageUp",
        34: "PageDown",
        35: "End",
        36: "Home",
        37: "ArrowLeft",
        38: "ArrowUp",
        39: "ArrowRight",
        40: "ArrowDown",
        45: "Insert",
        46: "Delete",
        112: "F1",
        113: "F2",
        114: "F3",
        115: "F4",
        116: "F5",
        117: "F6",
        118: "F7",
        119: "F8",
        120: "F9",
        121: "F10",
        122: "F11",
        123: "F12",
        144: "NumLock",
        145: "ScrollLock",
        224: "Meta"
      }, modifierKeyToProp = {
        Alt: "altKey",
        Control: "ctrlKey",
        Meta: "metaKey",
        Shift: "shiftKey"
      }, KeyboardEventInterface = assign({}, UIEventInterface, {
        key: function(nativeEvent) {
          if (nativeEvent.key) {
            var key = normalizeKey[nativeEvent.key] || nativeEvent.key;
            if ("Unidentified" !== key) return key;
          }
          return "keypress" === nativeEvent.type ? (nativeEvent = getEventCharCode(nativeEvent), 13 === nativeEvent ? "Enter" : String.fromCharCode(nativeEvent)) : "keydown" === nativeEvent.type || "keyup" === nativeEvent.type ? translateToKey[nativeEvent.keyCode] || "Unidentified" : "";
        },
        code: 0,
        location: 0,
        ctrlKey: 0,
        shiftKey: 0,
        altKey: 0,
        metaKey: 0,
        repeat: 0,
        locale: 0,
        getModifierState: getEventModifierState,
        charCode: function(event) {
          return "keypress" === event.type ? getEventCharCode(event) : 0;
        },
        keyCode: function(event) {
          return "keydown" === event.type || "keyup" === event.type ? event.keyCode : 0;
        },
        which: function(event) {
          return "keypress" === event.type ? getEventCharCode(event) : "keydown" === event.type || "keyup" === event.type ? event.keyCode : 0;
        }
      }), SyntheticKeyboardEvent = createSyntheticEvent(KeyboardEventInterface), PointerEventInterface = assign({}, MouseEventInterface, {
        pointerId: 0,
        width: 0,
        height: 0,
        pressure: 0,
        tangentialPressure: 0,
        tiltX: 0,
        tiltY: 0,
        twist: 0,
        pointerType: 0,
        isPrimary: 0
      }), SyntheticPointerEvent = createSyntheticEvent(PointerEventInterface), TouchEventInterface = assign({}, UIEventInterface, {
        touches: 0,
        targetTouches: 0,
        changedTouches: 0,
        altKey: 0,
        metaKey: 0,
        ctrlKey: 0,
        shiftKey: 0,
        getModifierState: getEventModifierState
      }), SyntheticTouchEvent = createSyntheticEvent(TouchEventInterface), TransitionEventInterface = assign({}, EventInterface, {
        propertyName: 0,
        elapsedTime: 0,
        pseudoElement: 0
      }), SyntheticTransitionEvent = createSyntheticEvent(TransitionEventInterface), WheelEventInterface = assign({}, MouseEventInterface, {
        deltaX: function(event) {
          return "deltaX" in event ? event.deltaX : "wheelDeltaX" in event ? -event.wheelDeltaX : 0;
        },
        deltaY: function(event) {
          return "deltaY" in event ? event.deltaY : "wheelDeltaY" in event ? -event.wheelDeltaY : "wheelDelta" in event ? -event.wheelDelta : 0;
        },
        deltaZ: 0,
        deltaMode: 0
      }), SyntheticWheelEvent = createSyntheticEvent(WheelEventInterface), ToggleEventInterface = assign({}, EventInterface, {
        newState: 0,
        oldState: 0
      }), SyntheticToggleEvent = createSyntheticEvent(ToggleEventInterface), END_KEYCODES = [9, 13, 27, 32], START_KEYCODE = 229, canUseCompositionEvent = canUseDOM && "CompositionEvent" in window, documentMode = null;
      canUseDOM && "documentMode" in document && (documentMode = document.documentMode);
      var canUseTextInputEvent = canUseDOM && "TextEvent" in window && !documentMode, useFallbackCompositionData = canUseDOM && (!canUseCompositionEvent || documentMode && 8 < documentMode && 11 >= documentMode), SPACEBAR_CODE = 32, SPACEBAR_CHAR = String.fromCharCode(SPACEBAR_CODE), hasSpaceKeypress = false, isComposing = false, supportedInputTypes = {
        color: true,
        date: true,
        datetime: true,
        "datetime-local": true,
        email: true,
        month: true,
        number: true,
        password: true,
        range: true,
        search: true,
        tel: true,
        text: true,
        time: true,
        url: true,
        week: true
      }, activeElement$1 = null, activeElementInst$1 = null, isInputEventSupported = false;
      canUseDOM && (isInputEventSupported = isEventSupported("input") && (!document.documentMode || 9 < document.documentMode));
      var objectIs = "function" === typeof Object.is ? Object.is : is, skipSelectionChangeEvent = canUseDOM && "documentMode" in document && 11 >= document.documentMode, activeElement = null, activeElementInst = null, lastSelection = null, mouseDown = false, vendorPrefixes = {
        animationend: makePrefixMap("Animation", "AnimationEnd"),
        animationiteration: makePrefixMap("Animation", "AnimationIteration"),
        animationstart: makePrefixMap("Animation", "AnimationStart"),
        transitionrun: makePrefixMap("Transition", "TransitionRun"),
        transitionstart: makePrefixMap("Transition", "TransitionStart"),
        transitioncancel: makePrefixMap("Transition", "TransitionCancel"),
        transitionend: makePrefixMap("Transition", "TransitionEnd")
      }, prefixedEventNames = {}, style2 = {};
      canUseDOM && (style2 = document.createElement("div").style, "AnimationEvent" in window || (delete vendorPrefixes.animationend.animation, delete vendorPrefixes.animationiteration.animation, delete vendorPrefixes.animationstart.animation), "TransitionEvent" in window || delete vendorPrefixes.transitionend.transition);
      var ANIMATION_END = getVendorPrefixedEventName("animationend"), ANIMATION_ITERATION = getVendorPrefixedEventName("animationiteration"), ANIMATION_START = getVendorPrefixedEventName("animationstart"), TRANSITION_RUN = getVendorPrefixedEventName("transitionrun"), TRANSITION_START = getVendorPrefixedEventName("transitionstart"), TRANSITION_CANCEL = getVendorPrefixedEventName("transitioncancel"), TRANSITION_END = getVendorPrefixedEventName("transitionend"), topLevelEventsToReactNames = /* @__PURE__ */ new Map(), simpleEventPluginEvents = "abort auxClick beforeToggle cancel canPlay canPlayThrough click close contextMenu copy cut drag dragEnd dragEnter dragExit dragLeave dragOver dragStart drop durationChange emptied encrypted ended error gotPointerCapture input invalid keyDown keyPress keyUp load loadedData loadedMetadata loadStart lostPointerCapture mouseDown mouseMove mouseOut mouseOver mouseUp paste pause play playing pointerCancel pointerDown pointerMove pointerOut pointerOver pointerUp progress rateChange reset resize seeked seeking stalled submit suspend timeUpdate touchCancel touchEnd touchStart volumeChange scroll toggle touchMove waiting wheel".split(
        " "
      );
      simpleEventPluginEvents.push("scrollEnd");
      var lastResetTime = 0;
      if ("object" === typeof performance && "function" === typeof performance.now) {
        var localPerformance = performance;
        var getCurrentTime = function() {
          return localPerformance.now();
        };
      } else {
        var localDate = Date;
        getCurrentTime = function() {
          return localDate.now();
        };
      }
      var reportGlobalError = "function" === typeof reportError ? reportError : function(error) {
        if ("object" === typeof window && "function" === typeof window.ErrorEvent) {
          var event = new window.ErrorEvent("error", {
            bubbles: true,
            cancelable: true,
            message: "object" === typeof error && null !== error && "string" === typeof error.message ? String(error.message) : String(error),
            error
          });
          if (!window.dispatchEvent(event)) return;
        } else if ("object" === typeof process && "function" === typeof process.emit) {
          process.emit("uncaughtException", error);
          return;
        }
        console.error(error);
      }, OMITTED_PROP_ERROR = "This object has been omitted by React in the console log to avoid sending too much data from the server. Try logging smaller or more specific objects.", EMPTY_ARRAY = 0, COMPLEX_ARRAY = 1, PRIMITIVE_ARRAY = 2, ENTRIES_ARRAY = 3, REMOVED = "\u2013\xA0", ADDED = "+\xA0", UNCHANGED = "\u2007\xA0", supportsUserTiming = "undefined" !== typeof console && "function" === typeof console.timeStamp && "undefined" !== typeof performance && "function" === typeof performance.measure, COMPONENTS_TRACK = "Components \u269B", LANES_TRACK_GROUP = "Scheduler \u269B", currentTrack = "Blocking", alreadyWarnedForDeepEquality = false, reusableComponentDevToolDetails = {
        color: "primary",
        properties: null,
        tooltipText: "",
        track: COMPONENTS_TRACK
      }, reusableComponentOptions = {
        start: -0,
        end: -0,
        detail: { devtools: reusableComponentDevToolDetails }
      }, resuableChangedPropsEntry = ["Changed Props", ""], DEEP_EQUALITY_WARNING = "This component received deeply equal props. It might benefit from useMemo or the React Compiler in its owner.", reusableDeeplyEqualPropsEntry = ["Changed Props", DEEP_EQUALITY_WARNING], OffscreenVisible = 1, OffscreenPassiveEffectsConnected = 2, concurrentQueues = [], concurrentQueuesIndex = 0, concurrentlyUpdatedLanes = 0, emptyContextObject = {};
      Object.freeze(emptyContextObject);
      var resolveFamily = null, failedBoundaries = null, NoMode = 0, ConcurrentMode = 1, ProfileMode = 2, StrictLegacyMode = 8, StrictEffectsMode = 16, SuspenseyImagesMode = 32;
      var hasBadMapPolyfill = false;
      try {
        var nonExtensibleObject = Object.preventExtensions({});
        /* @__PURE__ */ new Map([[nonExtensibleObject, null]]);
        /* @__PURE__ */ new Set([nonExtensibleObject]);
      } catch (e$3) {
        hasBadMapPolyfill = true;
      }
      var CapturedStacks = /* @__PURE__ */ new WeakMap(), forkStack = [], forkStackIndex = 0, treeForkProvider = null, treeForkCount = 0, idStack = [], idStackIndex = 0, treeContextProvider = null, treeContextId = 1, treeContextOverflow = "", hydrationParentFiber = null, nextHydratableInstance = null, isHydrating = false, didSuspendOrErrorDEV = false, hydrationDiffRootDEV = null, hydrationErrors = null, rootOrSingletonContext = false, HydrationMismatchException = Error(
        "Hydration Mismatch Exception: This is not a real error, and should not leak into userspace. If you're seeing this, it's likely a bug in React."
      ), valueCursor = createCursor(null);
      var rendererCursorDEV = createCursor(null);
      var rendererSigil = {};
      var currentlyRenderingFiber$1 = null, lastContextDependency = null, isDisallowedContextReadInDEV = false, AbortControllerLocal = "undefined" !== typeof AbortController ? AbortController : function() {
        var listeners2 = [], signal = this.signal = {
          aborted: false,
          addEventListener: function(type, listener) {
            listeners2.push(listener);
          }
        };
        this.abort = function() {
          signal.aborted = true;
          listeners2.forEach(function(listener) {
            return listener();
          });
        };
      }, scheduleCallback$2 = Scheduler.unstable_scheduleCallback, NormalPriority = Scheduler.unstable_NormalPriority, CacheContext = {
        $$typeof: REACT_CONTEXT_TYPE,
        Consumer: null,
        Provider: null,
        _currentValue: null,
        _currentValue2: null,
        _threadCount: 0,
        _currentRenderer: null,
        _currentRenderer2: null
      }, now = Scheduler.unstable_now, createTask = console.createTask ? console.createTask : function() {
        return null;
      }, SPAWNED_UPDATE = 1, PINGED_UPDATE = 2, renderStartTime = -0, commitStartTime = -0, commitEndTime = -0, commitErrors = null, profilerStartTime = -1.1, profilerEffectDuration = -0, componentEffectDuration = -0, componentEffectStartTime = -1.1, componentEffectEndTime = -1.1, componentEffectErrors = null, componentEffectSpawnedUpdate = false, blockingClampTime = -0, blockingUpdateTime = -1.1, blockingUpdateTask = null, blockingUpdateType = 0, blockingUpdateMethodName = null, blockingUpdateComponentName = null, blockingEventTime = -1.1, blockingEventType = null, blockingEventRepeatTime = -1.1, blockingSuspendedTime = -1.1, transitionClampTime = -0, transitionStartTime = -1.1, transitionUpdateTime = -1.1, transitionUpdateType = 0, transitionUpdateTask = null, transitionUpdateMethodName = null, transitionUpdateComponentName = null, transitionEventTime = -1.1, transitionEventType = null, transitionEventRepeatTime = -1.1, transitionSuspendedTime = -1.1, retryClampTime = -0, idleClampTime = -0, animatingLanes = 0, animatingTask = null, yieldReason = 0, yieldStartTime = -1.1, currentUpdateIsNested = false, nestedUpdateScheduled = false, currentEntangledListeners = null, currentEntangledPendingCount = 0, currentEntangledLane = 0, currentEntangledActionThenable = null, prevOnStartTransitionFinish = ReactSharedInternals.S;
      ReactSharedInternals.S = function(transition, returnValue) {
        globalMostRecentTransitionTime = now$1();
        if ("object" === typeof returnValue && null !== returnValue && "function" === typeof returnValue.then) {
          if (0 > transitionStartTime && 0 > transitionUpdateTime) {
            transitionStartTime = now();
            var newEventTime = resolveEventTimeStamp(), newEventType = resolveEventType();
            if (newEventTime !== transitionEventRepeatTime || newEventType !== transitionEventType)
              transitionEventRepeatTime = -1.1;
            transitionEventTime = newEventTime;
            transitionEventType = newEventType;
          }
          entangleAsyncAction(transition, returnValue);
        }
        null !== prevOnStartTransitionFinish && prevOnStartTransitionFinish(transition, returnValue);
      };
      var resumedCache = createCursor(null), ReactStrictModeWarnings = {
        recordUnsafeLifecycleWarnings: function() {
        },
        flushPendingUnsafeLifecycleWarnings: function() {
        },
        recordLegacyContextWarning: function() {
        },
        flushLegacyContextWarning: function() {
        },
        discardPendingWarnings: function() {
        }
      }, pendingComponentWillMountWarnings = [], pendingUNSAFE_ComponentWillMountWarnings = [], pendingComponentWillReceivePropsWarnings = [], pendingUNSAFE_ComponentWillReceivePropsWarnings = [], pendingComponentWillUpdateWarnings = [], pendingUNSAFE_ComponentWillUpdateWarnings = [], didWarnAboutUnsafeLifecycles = /* @__PURE__ */ new Set();
      ReactStrictModeWarnings.recordUnsafeLifecycleWarnings = function(fiber, instance) {
        didWarnAboutUnsafeLifecycles.has(fiber.type) || ("function" === typeof instance.componentWillMount && true !== instance.componentWillMount.__suppressDeprecationWarning && pendingComponentWillMountWarnings.push(fiber), fiber.mode & StrictLegacyMode && "function" === typeof instance.UNSAFE_componentWillMount && pendingUNSAFE_ComponentWillMountWarnings.push(fiber), "function" === typeof instance.componentWillReceiveProps && true !== instance.componentWillReceiveProps.__suppressDeprecationWarning && pendingComponentWillReceivePropsWarnings.push(fiber), fiber.mode & StrictLegacyMode && "function" === typeof instance.UNSAFE_componentWillReceiveProps && pendingUNSAFE_ComponentWillReceivePropsWarnings.push(fiber), "function" === typeof instance.componentWillUpdate && true !== instance.componentWillUpdate.__suppressDeprecationWarning && pendingComponentWillUpdateWarnings.push(fiber), fiber.mode & StrictLegacyMode && "function" === typeof instance.UNSAFE_componentWillUpdate && pendingUNSAFE_ComponentWillUpdateWarnings.push(fiber));
      };
      ReactStrictModeWarnings.flushPendingUnsafeLifecycleWarnings = function() {
        var componentWillMountUniqueNames = /* @__PURE__ */ new Set();
        0 < pendingComponentWillMountWarnings.length && (pendingComponentWillMountWarnings.forEach(function(fiber) {
          componentWillMountUniqueNames.add(
            getComponentNameFromFiber(fiber) || "Component"
          );
          didWarnAboutUnsafeLifecycles.add(fiber.type);
        }), pendingComponentWillMountWarnings = []);
        var UNSAFE_componentWillMountUniqueNames = /* @__PURE__ */ new Set();
        0 < pendingUNSAFE_ComponentWillMountWarnings.length && (pendingUNSAFE_ComponentWillMountWarnings.forEach(function(fiber) {
          UNSAFE_componentWillMountUniqueNames.add(
            getComponentNameFromFiber(fiber) || "Component"
          );
          didWarnAboutUnsafeLifecycles.add(fiber.type);
        }), pendingUNSAFE_ComponentWillMountWarnings = []);
        var componentWillReceivePropsUniqueNames = /* @__PURE__ */ new Set();
        0 < pendingComponentWillReceivePropsWarnings.length && (pendingComponentWillReceivePropsWarnings.forEach(function(fiber) {
          componentWillReceivePropsUniqueNames.add(
            getComponentNameFromFiber(fiber) || "Component"
          );
          didWarnAboutUnsafeLifecycles.add(fiber.type);
        }), pendingComponentWillReceivePropsWarnings = []);
        var UNSAFE_componentWillReceivePropsUniqueNames = /* @__PURE__ */ new Set();
        0 < pendingUNSAFE_ComponentWillReceivePropsWarnings.length && (pendingUNSAFE_ComponentWillReceivePropsWarnings.forEach(
          function(fiber) {
            UNSAFE_componentWillReceivePropsUniqueNames.add(
              getComponentNameFromFiber(fiber) || "Component"
            );
            didWarnAboutUnsafeLifecycles.add(fiber.type);
          }
        ), pendingUNSAFE_ComponentWillReceivePropsWarnings = []);
        var componentWillUpdateUniqueNames = /* @__PURE__ */ new Set();
        0 < pendingComponentWillUpdateWarnings.length && (pendingComponentWillUpdateWarnings.forEach(function(fiber) {
          componentWillUpdateUniqueNames.add(
            getComponentNameFromFiber(fiber) || "Component"
          );
          didWarnAboutUnsafeLifecycles.add(fiber.type);
        }), pendingComponentWillUpdateWarnings = []);
        var UNSAFE_componentWillUpdateUniqueNames = /* @__PURE__ */ new Set();
        0 < pendingUNSAFE_ComponentWillUpdateWarnings.length && (pendingUNSAFE_ComponentWillUpdateWarnings.forEach(function(fiber) {
          UNSAFE_componentWillUpdateUniqueNames.add(
            getComponentNameFromFiber(fiber) || "Component"
          );
          didWarnAboutUnsafeLifecycles.add(fiber.type);
        }), pendingUNSAFE_ComponentWillUpdateWarnings = []);
        if (0 < UNSAFE_componentWillMountUniqueNames.size) {
          var sortedNames = setToSortedString(
            UNSAFE_componentWillMountUniqueNames
          );
          console.error(
            "Using UNSAFE_componentWillMount in strict mode is not recommended and may indicate bugs in your code. See https://react.dev/link/unsafe-component-lifecycles for details.\n\n* Move code with side effects to componentDidMount, and set initial state in the constructor.\n\nPlease update the following components: %s",
            sortedNames
          );
        }
        0 < UNSAFE_componentWillReceivePropsUniqueNames.size && (sortedNames = setToSortedString(
          UNSAFE_componentWillReceivePropsUniqueNames
        ), console.error(
          "Using UNSAFE_componentWillReceiveProps in strict mode is not recommended and may indicate bugs in your code. See https://react.dev/link/unsafe-component-lifecycles for details.\n\n* Move data fetching code or side effects to componentDidUpdate.\n* If you're updating state whenever props change, refactor your code to use memoization techniques or move it to static getDerivedStateFromProps. Learn more at: https://react.dev/link/derived-state\n\nPlease update the following components: %s",
          sortedNames
        ));
        0 < UNSAFE_componentWillUpdateUniqueNames.size && (sortedNames = setToSortedString(
          UNSAFE_componentWillUpdateUniqueNames
        ), console.error(
          "Using UNSAFE_componentWillUpdate in strict mode is not recommended and may indicate bugs in your code. See https://react.dev/link/unsafe-component-lifecycles for details.\n\n* Move data fetching code or side effects to componentDidUpdate.\n\nPlease update the following components: %s",
          sortedNames
        ));
        0 < componentWillMountUniqueNames.size && (sortedNames = setToSortedString(componentWillMountUniqueNames), console.warn(
          "componentWillMount has been renamed, and is not recommended for use. See https://react.dev/link/unsafe-component-lifecycles for details.\n\n* Move code with side effects to componentDidMount, and set initial state in the constructor.\n* Rename componentWillMount to UNSAFE_componentWillMount to suppress this warning in non-strict mode. In React 18.x, only the UNSAFE_ name will work. To rename all deprecated lifecycles to their new names, you can run `npx react-codemod rename-unsafe-lifecycles` in your project source folder.\n\nPlease update the following components: %s",
          sortedNames
        ));
        0 < componentWillReceivePropsUniqueNames.size && (sortedNames = setToSortedString(
          componentWillReceivePropsUniqueNames
        ), console.warn(
          "componentWillReceiveProps has been renamed, and is not recommended for use. See https://react.dev/link/unsafe-component-lifecycles for details.\n\n* Move data fetching code or side effects to componentDidUpdate.\n* If you're updating state whenever props change, refactor your code to use memoization techniques or move it to static getDerivedStateFromProps. Learn more at: https://react.dev/link/derived-state\n* Rename componentWillReceiveProps to UNSAFE_componentWillReceiveProps to suppress this warning in non-strict mode. In React 18.x, only the UNSAFE_ name will work. To rename all deprecated lifecycles to their new names, you can run `npx react-codemod rename-unsafe-lifecycles` in your project source folder.\n\nPlease update the following components: %s",
          sortedNames
        ));
        0 < componentWillUpdateUniqueNames.size && (sortedNames = setToSortedString(componentWillUpdateUniqueNames), console.warn(
          "componentWillUpdate has been renamed, and is not recommended for use. See https://react.dev/link/unsafe-component-lifecycles for details.\n\n* Move data fetching code or side effects to componentDidUpdate.\n* Rename componentWillUpdate to UNSAFE_componentWillUpdate to suppress this warning in non-strict mode. In React 18.x, only the UNSAFE_ name will work. To rename all deprecated lifecycles to their new names, you can run `npx react-codemod rename-unsafe-lifecycles` in your project source folder.\n\nPlease update the following components: %s",
          sortedNames
        ));
      };
      var pendingLegacyContextWarning = /* @__PURE__ */ new Map(), didWarnAboutLegacyContext = /* @__PURE__ */ new Set();
      ReactStrictModeWarnings.recordLegacyContextWarning = function(fiber, instance) {
        var strictRoot = null;
        for (var node = fiber; null !== node; )
          node.mode & StrictLegacyMode && (strictRoot = node), node = node.return;
        null === strictRoot ? console.error(
          "Expected to find a StrictMode component in a strict mode tree. This error is likely caused by a bug in React. Please file an issue."
        ) : !didWarnAboutLegacyContext.has(fiber.type) && (node = pendingLegacyContextWarning.get(strictRoot), null != fiber.type.contextTypes || null != fiber.type.childContextTypes || null !== instance && "function" === typeof instance.getChildContext) && (void 0 === node && (node = [], pendingLegacyContextWarning.set(strictRoot, node)), node.push(fiber));
      };
      ReactStrictModeWarnings.flushLegacyContextWarning = function() {
        pendingLegacyContextWarning.forEach(function(fiberArray) {
          if (0 !== fiberArray.length) {
            var firstFiber = fiberArray[0], uniqueNames = /* @__PURE__ */ new Set();
            fiberArray.forEach(function(fiber) {
              uniqueNames.add(getComponentNameFromFiber(fiber) || "Component");
              didWarnAboutLegacyContext.add(fiber.type);
            });
            var sortedNames = setToSortedString(uniqueNames);
            runWithFiberInDEV(firstFiber, function() {
              console.error(
                "Legacy context API has been detected within a strict-mode tree.\n\nThe old API will be supported in all 16.x releases, but applications using it should migrate to the new version.\n\nPlease update the following components: %s\n\nLearn more about this warning here: https://react.dev/link/legacy-context",
                sortedNames
              );
            });
          }
        });
      };
      ReactStrictModeWarnings.discardPendingWarnings = function() {
        pendingComponentWillMountWarnings = [];
        pendingUNSAFE_ComponentWillMountWarnings = [];
        pendingComponentWillReceivePropsWarnings = [];
        pendingUNSAFE_ComponentWillReceivePropsWarnings = [];
        pendingComponentWillUpdateWarnings = [];
        pendingUNSAFE_ComponentWillUpdateWarnings = [];
        pendingLegacyContextWarning = /* @__PURE__ */ new Map();
      };
      var callComponent = {
        react_stack_bottom_frame: function(Component, props, secondArg) {
          var wasRendering = isRendering;
          isRendering = true;
          try {
            return Component(props, secondArg);
          } finally {
            isRendering = wasRendering;
          }
        }
      }, callComponentInDEV = callComponent.react_stack_bottom_frame.bind(callComponent), callRender = {
        react_stack_bottom_frame: function(instance) {
          var wasRendering = isRendering;
          isRendering = true;
          try {
            return instance.render();
          } finally {
            isRendering = wasRendering;
          }
        }
      }, callRenderInDEV = callRender.react_stack_bottom_frame.bind(callRender), callComponentDidMount = {
        react_stack_bottom_frame: function(finishedWork, instance) {
          try {
            instance.componentDidMount();
          } catch (error) {
            captureCommitPhaseError(finishedWork, finishedWork.return, error);
          }
        }
      }, callComponentDidMountInDEV = callComponentDidMount.react_stack_bottom_frame.bind(
        callComponentDidMount
      ), callComponentDidUpdate = {
        react_stack_bottom_frame: function(finishedWork, instance, prevProps, prevState, snapshot) {
          try {
            instance.componentDidUpdate(prevProps, prevState, snapshot);
          } catch (error) {
            captureCommitPhaseError(finishedWork, finishedWork.return, error);
          }
        }
      }, callComponentDidUpdateInDEV = callComponentDidUpdate.react_stack_bottom_frame.bind(
        callComponentDidUpdate
      ), callComponentDidCatch = {
        react_stack_bottom_frame: function(instance, errorInfo) {
          var stack = errorInfo.stack;
          instance.componentDidCatch(errorInfo.value, {
            componentStack: null !== stack ? stack : ""
          });
        }
      }, callComponentDidCatchInDEV = callComponentDidCatch.react_stack_bottom_frame.bind(
        callComponentDidCatch
      ), callComponentWillUnmount = {
        react_stack_bottom_frame: function(current2, nearestMountedAncestor, instance) {
          try {
            instance.componentWillUnmount();
          } catch (error) {
            captureCommitPhaseError(current2, nearestMountedAncestor, error);
          }
        }
      }, callComponentWillUnmountInDEV = callComponentWillUnmount.react_stack_bottom_frame.bind(
        callComponentWillUnmount
      ), callCreate = {
        react_stack_bottom_frame: function(effect) {
          var create = effect.create;
          effect = effect.inst;
          create = create();
          return effect.destroy = create;
        }
      }, callCreateInDEV = callCreate.react_stack_bottom_frame.bind(callCreate), callDestroy = {
        react_stack_bottom_frame: function(current2, nearestMountedAncestor, destroy) {
          try {
            destroy();
          } catch (error) {
            captureCommitPhaseError(current2, nearestMountedAncestor, error);
          }
        }
      }, callDestroyInDEV = callDestroy.react_stack_bottom_frame.bind(callDestroy), callLazyInit = {
        react_stack_bottom_frame: function(lazy) {
          var init2 = lazy._init;
          return init2(lazy._payload);
        }
      }, callLazyInitInDEV = callLazyInit.react_stack_bottom_frame.bind(callLazyInit), SuspenseException = Error(
        "Suspense Exception: This is not a real error! It's an implementation detail of `use` to interrupt the current render. You must either rethrow it immediately, or move the `use` call outside of the `try/catch` block. Capturing without rethrowing will lead to unexpected behavior.\n\nTo handle async errors, wrap your component in an error boundary, or call the promise's `.catch` method and pass the result to `use`."
      ), SuspenseyCommitException = Error(
        "Suspense Exception: This is not a real error, and should not leak into userspace. If you're seeing this, it's likely a bug in React."
      ), SuspenseActionException = Error(
        "Suspense Exception: This is not a real error! It's an implementation detail of `useActionState` to interrupt the current render. You must either rethrow it immediately, or move the `useActionState` call outside of the `try/catch` block. Capturing without rethrowing will lead to unexpected behavior.\n\nTo handle async errors, wrap your component in an error boundary."
      ), noopSuspenseyCommitThenable = {
        then: function() {
          console.error(
            'Internal React error: A listener was unexpectedly attached to a "noop" thenable. This is a bug in React. Please file an issue.'
          );
        }
      }, suspendedThenable = null, needsToResetSuspendedThenableDEV = false, thenableState$1 = null, thenableIndexCounter$1 = 0, currentDebugInfo = null, didWarnAboutMaps;
      var didWarnAboutGenerators = didWarnAboutMaps = false;
      var ownerHasKeyUseWarning = {};
      var ownerHasFunctionTypeWarning = {};
      var ownerHasSymbolTypeWarning = {};
      warnForMissingKey = function(returnFiber, workInProgress2, child) {
        if (null !== child && "object" === typeof child && child._store && (!child._store.validated && null == child.key || 2 === child._store.validated)) {
          if ("object" !== typeof child._store)
            throw Error(
              "React Component in warnForMissingKey should have a _store. This error is likely caused by a bug in React. Please file an issue."
            );
          child._store.validated = 1;
          var componentName2 = getComponentNameFromFiber(returnFiber), componentKey = componentName2 || "null";
          if (!ownerHasKeyUseWarning[componentKey]) {
            ownerHasKeyUseWarning[componentKey] = true;
            child = child._owner;
            returnFiber = returnFiber._debugOwner;
            var currentComponentErrorInfo = "";
            returnFiber && "number" === typeof returnFiber.tag && (componentKey = getComponentNameFromFiber(returnFiber)) && (currentComponentErrorInfo = "\n\nCheck the render method of `" + componentKey + "`.");
            currentComponentErrorInfo || componentName2 && (currentComponentErrorInfo = "\n\nCheck the top-level render call using <" + componentName2 + ">.");
            var childOwnerAppendix = "";
            null != child && returnFiber !== child && (componentName2 = null, "number" === typeof child.tag ? componentName2 = getComponentNameFromFiber(child) : "string" === typeof child.name && (componentName2 = child.name), componentName2 && (childOwnerAppendix = " It was passed a child from " + componentName2 + "."));
            runWithFiberInDEV(workInProgress2, function() {
              console.error(
                'Each child in a list should have a unique "key" prop.%s%s See https://react.dev/link/warning-keys for more information.',
                currentComponentErrorInfo,
                childOwnerAppendix
              );
            });
          }
        }
      };
      var reconcileChildFibers = createChildReconciler(true), mountChildFibers = createChildReconciler(false), UpdateState = 0, ReplaceState = 1, ForceUpdate = 2, CaptureUpdate = 3, hasForceUpdate = false;
      var didWarnUpdateInsideUpdate = false;
      var currentlyProcessingQueue = null;
      var didReadFromEntangledAsyncAction = false, currentTreeHiddenStackCursor = createCursor(null), prevEntangledRenderLanesCursor = createCursor(0), suspenseHandlerStackCursor = createCursor(null), shellBoundary = null, SubtreeSuspenseContextMask = 1, ForceSuspenseFallback = 2, suspenseStackCursor = createCursor(0), NoFlags = 0, HasEffect = 1, Insertion = 2, Layout = 4, Passive = 8, didWarnUncachedGetSnapshot;
      var didWarnAboutMismatchedHooksForComponent = /* @__PURE__ */ new Set();
      var didWarnAboutUseWrappedInTryCatch = /* @__PURE__ */ new Set();
      var didWarnAboutAsyncClientComponent = /* @__PURE__ */ new Set();
      var didWarnAboutUseFormState = /* @__PURE__ */ new Set();
      var renderLanes = 0, currentlyRenderingFiber = null, currentHook = null, workInProgressHook = null, didScheduleRenderPhaseUpdate = false, didScheduleRenderPhaseUpdateDuringThisPass = false, shouldDoubleInvokeUserFnsInHooksDEV = false, localIdCounter = 0, thenableIndexCounter = 0, thenableState = null, globalClientIdCounter = 0, RE_RENDER_LIMIT = 25, currentHookNameInDev = null, hookTypesDev = null, hookTypesUpdateIndexDev = -1, ignorePreviousDependencies = false, ContextOnlyDispatcher = {
        readContext,
        use,
        useCallback: throwInvalidHookError,
        useContext: throwInvalidHookError,
        useEffect: throwInvalidHookError,
        useImperativeHandle: throwInvalidHookError,
        useLayoutEffect: throwInvalidHookError,
        useInsertionEffect: throwInvalidHookError,
        useMemo: throwInvalidHookError,
        useReducer: throwInvalidHookError,
        useRef: throwInvalidHookError,
        useState: throwInvalidHookError,
        useDebugValue: throwInvalidHookError,
        useDeferredValue: throwInvalidHookError,
        useTransition: throwInvalidHookError,
        useSyncExternalStore: throwInvalidHookError,
        useId: throwInvalidHookError,
        useHostTransitionStatus: throwInvalidHookError,
        useFormState: throwInvalidHookError,
        useActionState: throwInvalidHookError,
        useOptimistic: throwInvalidHookError,
        useMemoCache: throwInvalidHookError,
        useCacheRefresh: throwInvalidHookError
      };
      ContextOnlyDispatcher.useEffectEvent = throwInvalidHookError;
      var HooksDispatcherOnMountInDEV = null, HooksDispatcherOnMountWithHookTypesInDEV = null, HooksDispatcherOnUpdateInDEV = null, HooksDispatcherOnRerenderInDEV = null, InvalidNestedHooksDispatcherOnMountInDEV = null, InvalidNestedHooksDispatcherOnUpdateInDEV = null, InvalidNestedHooksDispatcherOnRerenderInDEV = null;
      HooksDispatcherOnMountInDEV = {
        readContext: function(context) {
          return readContext(context);
        },
        use,
        useCallback: function(callback, deps) {
          currentHookNameInDev = "useCallback";
          mountHookTypesDev();
          checkDepsAreArrayDev(deps);
          return mountCallback(callback, deps);
        },
        useContext: function(context) {
          currentHookNameInDev = "useContext";
          mountHookTypesDev();
          return readContext(context);
        },
        useEffect: function(create, deps) {
          currentHookNameInDev = "useEffect";
          mountHookTypesDev();
          checkDepsAreArrayDev(deps);
          return mountEffect(create, deps);
        },
        useImperativeHandle: function(ref, create, deps) {
          currentHookNameInDev = "useImperativeHandle";
          mountHookTypesDev();
          checkDepsAreArrayDev(deps);
          return mountImperativeHandle(ref, create, deps);
        },
        useInsertionEffect: function(create, deps) {
          currentHookNameInDev = "useInsertionEffect";
          mountHookTypesDev();
          checkDepsAreArrayDev(deps);
          mountEffectImpl(4, Insertion, create, deps);
        },
        useLayoutEffect: function(create, deps) {
          currentHookNameInDev = "useLayoutEffect";
          mountHookTypesDev();
          checkDepsAreArrayDev(deps);
          return mountLayoutEffect(create, deps);
        },
        useMemo: function(create, deps) {
          currentHookNameInDev = "useMemo";
          mountHookTypesDev();
          checkDepsAreArrayDev(deps);
          var prevDispatcher = ReactSharedInternals.H;
          ReactSharedInternals.H = InvalidNestedHooksDispatcherOnMountInDEV;
          try {
            return mountMemo(create, deps);
          } finally {
            ReactSharedInternals.H = prevDispatcher;
          }
        },
        useReducer: function(reducer, initialArg, init2) {
          currentHookNameInDev = "useReducer";
          mountHookTypesDev();
          var prevDispatcher = ReactSharedInternals.H;
          ReactSharedInternals.H = InvalidNestedHooksDispatcherOnMountInDEV;
          try {
            return mountReducer(reducer, initialArg, init2);
          } finally {
            ReactSharedInternals.H = prevDispatcher;
          }
        },
        useRef: function(initialValue) {
          currentHookNameInDev = "useRef";
          mountHookTypesDev();
          return mountRef(initialValue);
        },
        useState: function(initialState) {
          currentHookNameInDev = "useState";
          mountHookTypesDev();
          var prevDispatcher = ReactSharedInternals.H;
          ReactSharedInternals.H = InvalidNestedHooksDispatcherOnMountInDEV;
          try {
            return mountState(initialState);
          } finally {
            ReactSharedInternals.H = prevDispatcher;
          }
        },
        useDebugValue: function() {
          currentHookNameInDev = "useDebugValue";
          mountHookTypesDev();
        },
        useDeferredValue: function(value, initialValue) {
          currentHookNameInDev = "useDeferredValue";
          mountHookTypesDev();
          return mountDeferredValue(value, initialValue);
        },
        useTransition: function() {
          currentHookNameInDev = "useTransition";
          mountHookTypesDev();
          return mountTransition();
        },
        useSyncExternalStore: function(subscribe2, getSnapshot, getServerSnapshot) {
          currentHookNameInDev = "useSyncExternalStore";
          mountHookTypesDev();
          return mountSyncExternalStore(
            subscribe2,
            getSnapshot,
            getServerSnapshot
          );
        },
        useId: function() {
          currentHookNameInDev = "useId";
          mountHookTypesDev();
          return mountId();
        },
        useFormState: function(action, initialState) {
          currentHookNameInDev = "useFormState";
          mountHookTypesDev();
          warnOnUseFormStateInDev();
          return mountActionState(action, initialState);
        },
        useActionState: function(action, initialState) {
          currentHookNameInDev = "useActionState";
          mountHookTypesDev();
          return mountActionState(action, initialState);
        },
        useOptimistic: function(passthrough) {
          currentHookNameInDev = "useOptimistic";
          mountHookTypesDev();
          return mountOptimistic(passthrough);
        },
        useHostTransitionStatus,
        useMemoCache,
        useCacheRefresh: function() {
          currentHookNameInDev = "useCacheRefresh";
          mountHookTypesDev();
          return mountRefresh();
        },
        useEffectEvent: function(callback) {
          currentHookNameInDev = "useEffectEvent";
          mountHookTypesDev();
          return mountEvent(callback);
        }
      };
      HooksDispatcherOnMountWithHookTypesInDEV = {
        readContext: function(context) {
          return readContext(context);
        },
        use,
        useCallback: function(callback, deps) {
          currentHookNameInDev = "useCallback";
          updateHookTypesDev();
          return mountCallback(callback, deps);
        },
        useContext: function(context) {
          currentHookNameInDev = "useContext";
          updateHookTypesDev();
          return readContext(context);
        },
        useEffect: function(create, deps) {
          currentHookNameInDev = "useEffect";
          updateHookTypesDev();
          return mountEffect(create, deps);
        },
        useImperativeHandle: function(ref, create, deps) {
          currentHookNameInDev = "useImperativeHandle";
          updateHookTypesDev();
          return mountImperativeHandle(ref, create, deps);
        },
        useInsertionEffect: function(create, deps) {
          currentHookNameInDev = "useInsertionEffect";
          updateHookTypesDev();
          mountEffectImpl(4, Insertion, create, deps);
        },
        useLayoutEffect: function(create, deps) {
          currentHookNameInDev = "useLayoutEffect";
          updateHookTypesDev();
          return mountLayoutEffect(create, deps);
        },
        useMemo: function(create, deps) {
          currentHookNameInDev = "useMemo";
          updateHookTypesDev();
          var prevDispatcher = ReactSharedInternals.H;
          ReactSharedInternals.H = InvalidNestedHooksDispatcherOnMountInDEV;
          try {
            return mountMemo(create, deps);
          } finally {
            ReactSharedInternals.H = prevDispatcher;
          }
        },
        useReducer: function(reducer, initialArg, init2) {
          currentHookNameInDev = "useReducer";
          updateHookTypesDev();
          var prevDispatcher = ReactSharedInternals.H;
          ReactSharedInternals.H = InvalidNestedHooksDispatcherOnMountInDEV;
          try {
            return mountReducer(reducer, initialArg, init2);
          } finally {
            ReactSharedInternals.H = prevDispatcher;
          }
        },
        useRef: function(initialValue) {
          currentHookNameInDev = "useRef";
          updateHookTypesDev();
          return mountRef(initialValue);
        },
        useState: function(initialState) {
          currentHookNameInDev = "useState";
          updateHookTypesDev();
          var prevDispatcher = ReactSharedInternals.H;
          ReactSharedInternals.H = InvalidNestedHooksDispatcherOnMountInDEV;
          try {
            return mountState(initialState);
          } finally {
            ReactSharedInternals.H = prevDispatcher;
          }
        },
        useDebugValue: function() {
          currentHookNameInDev = "useDebugValue";
          updateHookTypesDev();
        },
        useDeferredValue: function(value, initialValue) {
          currentHookNameInDev = "useDeferredValue";
          updateHookTypesDev();
          return mountDeferredValue(value, initialValue);
        },
        useTransition: function() {
          currentHookNameInDev = "useTransition";
          updateHookTypesDev();
          return mountTransition();
        },
        useSyncExternalStore: function(subscribe2, getSnapshot, getServerSnapshot) {
          currentHookNameInDev = "useSyncExternalStore";
          updateHookTypesDev();
          return mountSyncExternalStore(
            subscribe2,
            getSnapshot,
            getServerSnapshot
          );
        },
        useId: function() {
          currentHookNameInDev = "useId";
          updateHookTypesDev();
          return mountId();
        },
        useActionState: function(action, initialState) {
          currentHookNameInDev = "useActionState";
          updateHookTypesDev();
          return mountActionState(action, initialState);
        },
        useFormState: function(action, initialState) {
          currentHookNameInDev = "useFormState";
          updateHookTypesDev();
          warnOnUseFormStateInDev();
          return mountActionState(action, initialState);
        },
        useOptimistic: function(passthrough) {
          currentHookNameInDev = "useOptimistic";
          updateHookTypesDev();
          return mountOptimistic(passthrough);
        },
        useHostTransitionStatus,
        useMemoCache,
        useCacheRefresh: function() {
          currentHookNameInDev = "useCacheRefresh";
          updateHookTypesDev();
          return mountRefresh();
        },
        useEffectEvent: function(callback) {
          currentHookNameInDev = "useEffectEvent";
          updateHookTypesDev();
          return mountEvent(callback);
        }
      };
      HooksDispatcherOnUpdateInDEV = {
        readContext: function(context) {
          return readContext(context);
        },
        use,
        useCallback: function(callback, deps) {
          currentHookNameInDev = "useCallback";
          updateHookTypesDev();
          return updateCallback(callback, deps);
        },
        useContext: function(context) {
          currentHookNameInDev = "useContext";
          updateHookTypesDev();
          return readContext(context);
        },
        useEffect: function(create, deps) {
          currentHookNameInDev = "useEffect";
          updateHookTypesDev();
          updateEffectImpl(2048, Passive, create, deps);
        },
        useImperativeHandle: function(ref, create, deps) {
          currentHookNameInDev = "useImperativeHandle";
          updateHookTypesDev();
          return updateImperativeHandle(ref, create, deps);
        },
        useInsertionEffect: function(create, deps) {
          currentHookNameInDev = "useInsertionEffect";
          updateHookTypesDev();
          return updateEffectImpl(4, Insertion, create, deps);
        },
        useLayoutEffect: function(create, deps) {
          currentHookNameInDev = "useLayoutEffect";
          updateHookTypesDev();
          return updateEffectImpl(4, Layout, create, deps);
        },
        useMemo: function(create, deps) {
          currentHookNameInDev = "useMemo";
          updateHookTypesDev();
          var prevDispatcher = ReactSharedInternals.H;
          ReactSharedInternals.H = InvalidNestedHooksDispatcherOnUpdateInDEV;
          try {
            return updateMemo(create, deps);
          } finally {
            ReactSharedInternals.H = prevDispatcher;
          }
        },
        useReducer: function(reducer, initialArg, init2) {
          currentHookNameInDev = "useReducer";
          updateHookTypesDev();
          var prevDispatcher = ReactSharedInternals.H;
          ReactSharedInternals.H = InvalidNestedHooksDispatcherOnUpdateInDEV;
          try {
            return updateReducer(reducer, initialArg, init2);
          } finally {
            ReactSharedInternals.H = prevDispatcher;
          }
        },
        useRef: function() {
          currentHookNameInDev = "useRef";
          updateHookTypesDev();
          return updateWorkInProgressHook().memoizedState;
        },
        useState: function() {
          currentHookNameInDev = "useState";
          updateHookTypesDev();
          var prevDispatcher = ReactSharedInternals.H;
          ReactSharedInternals.H = InvalidNestedHooksDispatcherOnUpdateInDEV;
          try {
            return updateReducer(basicStateReducer);
          } finally {
            ReactSharedInternals.H = prevDispatcher;
          }
        },
        useDebugValue: function() {
          currentHookNameInDev = "useDebugValue";
          updateHookTypesDev();
        },
        useDeferredValue: function(value, initialValue) {
          currentHookNameInDev = "useDeferredValue";
          updateHookTypesDev();
          return updateDeferredValue(value, initialValue);
        },
        useTransition: function() {
          currentHookNameInDev = "useTransition";
          updateHookTypesDev();
          return updateTransition();
        },
        useSyncExternalStore: function(subscribe2, getSnapshot, getServerSnapshot) {
          currentHookNameInDev = "useSyncExternalStore";
          updateHookTypesDev();
          return updateSyncExternalStore(
            subscribe2,
            getSnapshot,
            getServerSnapshot
          );
        },
        useId: function() {
          currentHookNameInDev = "useId";
          updateHookTypesDev();
          return updateWorkInProgressHook().memoizedState;
        },
        useFormState: function(action) {
          currentHookNameInDev = "useFormState";
          updateHookTypesDev();
          warnOnUseFormStateInDev();
          return updateActionState(action);
        },
        useActionState: function(action) {
          currentHookNameInDev = "useActionState";
          updateHookTypesDev();
          return updateActionState(action);
        },
        useOptimistic: function(passthrough, reducer) {
          currentHookNameInDev = "useOptimistic";
          updateHookTypesDev();
          return updateOptimistic(passthrough, reducer);
        },
        useHostTransitionStatus,
        useMemoCache,
        useCacheRefresh: function() {
          currentHookNameInDev = "useCacheRefresh";
          updateHookTypesDev();
          return updateWorkInProgressHook().memoizedState;
        },
        useEffectEvent: function(callback) {
          currentHookNameInDev = "useEffectEvent";
          updateHookTypesDev();
          return updateEvent(callback);
        }
      };
      HooksDispatcherOnRerenderInDEV = {
        readContext: function(context) {
          return readContext(context);
        },
        use,
        useCallback: function(callback, deps) {
          currentHookNameInDev = "useCallback";
          updateHookTypesDev();
          return updateCallback(callback, deps);
        },
        useContext: function(context) {
          currentHookNameInDev = "useContext";
          updateHookTypesDev();
          return readContext(context);
        },
        useEffect: function(create, deps) {
          currentHookNameInDev = "useEffect";
          updateHookTypesDev();
          updateEffectImpl(2048, Passive, create, deps);
        },
        useImperativeHandle: function(ref, create, deps) {
          currentHookNameInDev = "useImperativeHandle";
          updateHookTypesDev();
          return updateImperativeHandle(ref, create, deps);
        },
        useInsertionEffect: function(create, deps) {
          currentHookNameInDev = "useInsertionEffect";
          updateHookTypesDev();
          return updateEffectImpl(4, Insertion, create, deps);
        },
        useLayoutEffect: function(create, deps) {
          currentHookNameInDev = "useLayoutEffect";
          updateHookTypesDev();
          return updateEffectImpl(4, Layout, create, deps);
        },
        useMemo: function(create, deps) {
          currentHookNameInDev = "useMemo";
          updateHookTypesDev();
          var prevDispatcher = ReactSharedInternals.H;
          ReactSharedInternals.H = InvalidNestedHooksDispatcherOnRerenderInDEV;
          try {
            return updateMemo(create, deps);
          } finally {
            ReactSharedInternals.H = prevDispatcher;
          }
        },
        useReducer: function(reducer, initialArg, init2) {
          currentHookNameInDev = "useReducer";
          updateHookTypesDev();
          var prevDispatcher = ReactSharedInternals.H;
          ReactSharedInternals.H = InvalidNestedHooksDispatcherOnRerenderInDEV;
          try {
            return rerenderReducer(reducer, initialArg, init2);
          } finally {
            ReactSharedInternals.H = prevDispatcher;
          }
        },
        useRef: function() {
          currentHookNameInDev = "useRef";
          updateHookTypesDev();
          return updateWorkInProgressHook().memoizedState;
        },
        useState: function() {
          currentHookNameInDev = "useState";
          updateHookTypesDev();
          var prevDispatcher = ReactSharedInternals.H;
          ReactSharedInternals.H = InvalidNestedHooksDispatcherOnRerenderInDEV;
          try {
            return rerenderReducer(basicStateReducer);
          } finally {
            ReactSharedInternals.H = prevDispatcher;
          }
        },
        useDebugValue: function() {
          currentHookNameInDev = "useDebugValue";
          updateHookTypesDev();
        },
        useDeferredValue: function(value, initialValue) {
          currentHookNameInDev = "useDeferredValue";
          updateHookTypesDev();
          return rerenderDeferredValue(value, initialValue);
        },
        useTransition: function() {
          currentHookNameInDev = "useTransition";
          updateHookTypesDev();
          return rerenderTransition();
        },
        useSyncExternalStore: function(subscribe2, getSnapshot, getServerSnapshot) {
          currentHookNameInDev = "useSyncExternalStore";
          updateHookTypesDev();
          return updateSyncExternalStore(
            subscribe2,
            getSnapshot,
            getServerSnapshot
          );
        },
        useId: function() {
          currentHookNameInDev = "useId";
          updateHookTypesDev();
          return updateWorkInProgressHook().memoizedState;
        },
        useFormState: function(action) {
          currentHookNameInDev = "useFormState";
          updateHookTypesDev();
          warnOnUseFormStateInDev();
          return rerenderActionState(action);
        },
        useActionState: function(action) {
          currentHookNameInDev = "useActionState";
          updateHookTypesDev();
          return rerenderActionState(action);
        },
        useOptimistic: function(passthrough, reducer) {
          currentHookNameInDev = "useOptimistic";
          updateHookTypesDev();
          return rerenderOptimistic(passthrough, reducer);
        },
        useHostTransitionStatus,
        useMemoCache,
        useCacheRefresh: function() {
          currentHookNameInDev = "useCacheRefresh";
          updateHookTypesDev();
          return updateWorkInProgressHook().memoizedState;
        },
        useEffectEvent: function(callback) {
          currentHookNameInDev = "useEffectEvent";
          updateHookTypesDev();
          return updateEvent(callback);
        }
      };
      InvalidNestedHooksDispatcherOnMountInDEV = {
        readContext: function(context) {
          warnInvalidContextAccess();
          return readContext(context);
        },
        use: function(usable) {
          warnInvalidHookAccess();
          return use(usable);
        },
        useCallback: function(callback, deps) {
          currentHookNameInDev = "useCallback";
          warnInvalidHookAccess();
          mountHookTypesDev();
          return mountCallback(callback, deps);
        },
        useContext: function(context) {
          currentHookNameInDev = "useContext";
          warnInvalidHookAccess();
          mountHookTypesDev();
          return readContext(context);
        },
        useEffect: function(create, deps) {
          currentHookNameInDev = "useEffect";
          warnInvalidHookAccess();
          mountHookTypesDev();
          return mountEffect(create, deps);
        },
        useImperativeHandle: function(ref, create, deps) {
          currentHookNameInDev = "useImperativeHandle";
          warnInvalidHookAccess();
          mountHookTypesDev();
          return mountImperativeHandle(ref, create, deps);
        },
        useInsertionEffect: function(create, deps) {
          currentHookNameInDev = "useInsertionEffect";
          warnInvalidHookAccess();
          mountHookTypesDev();
          mountEffectImpl(4, Insertion, create, deps);
        },
        useLayoutEffect: function(create, deps) {
          currentHookNameInDev = "useLayoutEffect";
          warnInvalidHookAccess();
          mountHookTypesDev();
          return mountLayoutEffect(create, deps);
        },
        useMemo: function(create, deps) {
          currentHookNameInDev = "useMemo";
          warnInvalidHookAccess();
          mountHookTypesDev();
          var prevDispatcher = ReactSharedInternals.H;
          ReactSharedInternals.H = InvalidNestedHooksDispatcherOnMountInDEV;
          try {
            return mountMemo(create, deps);
          } finally {
            ReactSharedInternals.H = prevDispatcher;
          }
        },
        useReducer: function(reducer, initialArg, init2) {
          currentHookNameInDev = "useReducer";
          warnInvalidHookAccess();
          mountHookTypesDev();
          var prevDispatcher = ReactSharedInternals.H;
          ReactSharedInternals.H = InvalidNestedHooksDispatcherOnMountInDEV;
          try {
            return mountReducer(reducer, initialArg, init2);
          } finally {
            ReactSharedInternals.H = prevDispatcher;
          }
        },
        useRef: function(initialValue) {
          currentHookNameInDev = "useRef";
          warnInvalidHookAccess();
          mountHookTypesDev();
          return mountRef(initialValue);
        },
        useState: function(initialState) {
          currentHookNameInDev = "useState";
          warnInvalidHookAccess();
          mountHookTypesDev();
          var prevDispatcher = ReactSharedInternals.H;
          ReactSharedInternals.H = InvalidNestedHooksDispatcherOnMountInDEV;
          try {
            return mountState(initialState);
          } finally {
            ReactSharedInternals.H = prevDispatcher;
          }
        },
        useDebugValue: function() {
          currentHookNameInDev = "useDebugValue";
          warnInvalidHookAccess();
          mountHookTypesDev();
        },
        useDeferredValue: function(value, initialValue) {
          currentHookNameInDev = "useDeferredValue";
          warnInvalidHookAccess();
          mountHookTypesDev();
          return mountDeferredValue(value, initialValue);
        },
        useTransition: function() {
          currentHookNameInDev = "useTransition";
          warnInvalidHookAccess();
          mountHookTypesDev();
          return mountTransition();
        },
        useSyncExternalStore: function(subscribe2, getSnapshot, getServerSnapshot) {
          currentHookNameInDev = "useSyncExternalStore";
          warnInvalidHookAccess();
          mountHookTypesDev();
          return mountSyncExternalStore(
            subscribe2,
            getSnapshot,
            getServerSnapshot
          );
        },
        useId: function() {
          currentHookNameInDev = "useId";
          warnInvalidHookAccess();
          mountHookTypesDev();
          return mountId();
        },
        useFormState: function(action, initialState) {
          currentHookNameInDev = "useFormState";
          warnInvalidHookAccess();
          mountHookTypesDev();
          return mountActionState(action, initialState);
        },
        useActionState: function(action, initialState) {
          currentHookNameInDev = "useActionState";
          warnInvalidHookAccess();
          mountHookTypesDev();
          return mountActionState(action, initialState);
        },
        useOptimistic: function(passthrough) {
          currentHookNameInDev = "useOptimistic";
          warnInvalidHookAccess();
          mountHookTypesDev();
          return mountOptimistic(passthrough);
        },
        useMemoCache: function(size) {
          warnInvalidHookAccess();
          return useMemoCache(size);
        },
        useHostTransitionStatus,
        useCacheRefresh: function() {
          currentHookNameInDev = "useCacheRefresh";
          mountHookTypesDev();
          return mountRefresh();
        },
        useEffectEvent: function(callback) {
          currentHookNameInDev = "useEffectEvent";
          warnInvalidHookAccess();
          mountHookTypesDev();
          return mountEvent(callback);
        }
      };
      InvalidNestedHooksDispatcherOnUpdateInDEV = {
        readContext: function(context) {
          warnInvalidContextAccess();
          return readContext(context);
        },
        use: function(usable) {
          warnInvalidHookAccess();
          return use(usable);
        },
        useCallback: function(callback, deps) {
          currentHookNameInDev = "useCallback";
          warnInvalidHookAccess();
          updateHookTypesDev();
          return updateCallback(callback, deps);
        },
        useContext: function(context) {
          currentHookNameInDev = "useContext";
          warnInvalidHookAccess();
          updateHookTypesDev();
          return readContext(context);
        },
        useEffect: function(create, deps) {
          currentHookNameInDev = "useEffect";
          warnInvalidHookAccess();
          updateHookTypesDev();
          updateEffectImpl(2048, Passive, create, deps);
        },
        useImperativeHandle: function(ref, create, deps) {
          currentHookNameInDev = "useImperativeHandle";
          warnInvalidHookAccess();
          updateHookTypesDev();
          return updateImperativeHandle(ref, create, deps);
        },
        useInsertionEffect: function(create, deps) {
          currentHookNameInDev = "useInsertionEffect";
          warnInvalidHookAccess();
          updateHookTypesDev();
          return updateEffectImpl(4, Insertion, create, deps);
        },
        useLayoutEffect: function(create, deps) {
          currentHookNameInDev = "useLayoutEffect";
          warnInvalidHookAccess();
          updateHookTypesDev();
          return updateEffectImpl(4, Layout, create, deps);
        },
        useMemo: function(create, deps) {
          currentHookNameInDev = "useMemo";
          warnInvalidHookAccess();
          updateHookTypesDev();
          var prevDispatcher = ReactSharedInternals.H;
          ReactSharedInternals.H = InvalidNestedHooksDispatcherOnUpdateInDEV;
          try {
            return updateMemo(create, deps);
          } finally {
            ReactSharedInternals.H = prevDispatcher;
          }
        },
        useReducer: function(reducer, initialArg, init2) {
          currentHookNameInDev = "useReducer";
          warnInvalidHookAccess();
          updateHookTypesDev();
          var prevDispatcher = ReactSharedInternals.H;
          ReactSharedInternals.H = InvalidNestedHooksDispatcherOnUpdateInDEV;
          try {
            return updateReducer(reducer, initialArg, init2);
          } finally {
            ReactSharedInternals.H = prevDispatcher;
          }
        },
        useRef: function() {
          currentHookNameInDev = "useRef";
          warnInvalidHookAccess();
          updateHookTypesDev();
          return updateWorkInProgressHook().memoizedState;
        },
        useState: function() {
          currentHookNameInDev = "useState";
          warnInvalidHookAccess();
          updateHookTypesDev();
          var prevDispatcher = ReactSharedInternals.H;
          ReactSharedInternals.H = InvalidNestedHooksDispatcherOnUpdateInDEV;
          try {
            return updateReducer(basicStateReducer);
          } finally {
            ReactSharedInternals.H = prevDispatcher;
          }
        },
        useDebugValue: function() {
          currentHookNameInDev = "useDebugValue";
          warnInvalidHookAccess();
          updateHookTypesDev();
        },
        useDeferredValue: function(value, initialValue) {
          currentHookNameInDev = "useDeferredValue";
          warnInvalidHookAccess();
          updateHookTypesDev();
          return updateDeferredValue(value, initialValue);
        },
        useTransition: function() {
          currentHookNameInDev = "useTransition";
          warnInvalidHookAccess();
          updateHookTypesDev();
          return updateTransition();
        },
        useSyncExternalStore: function(subscribe2, getSnapshot, getServerSnapshot) {
          currentHookNameInDev = "useSyncExternalStore";
          warnInvalidHookAccess();
          updateHookTypesDev();
          return updateSyncExternalStore(
            subscribe2,
            getSnapshot,
            getServerSnapshot
          );
        },
        useId: function() {
          currentHookNameInDev = "useId";
          warnInvalidHookAccess();
          updateHookTypesDev();
          return updateWorkInProgressHook().memoizedState;
        },
        useFormState: function(action) {
          currentHookNameInDev = "useFormState";
          warnInvalidHookAccess();
          updateHookTypesDev();
          return updateActionState(action);
        },
        useActionState: function(action) {
          currentHookNameInDev = "useActionState";
          warnInvalidHookAccess();
          updateHookTypesDev();
          return updateActionState(action);
        },
        useOptimistic: function(passthrough, reducer) {
          currentHookNameInDev = "useOptimistic";
          warnInvalidHookAccess();
          updateHookTypesDev();
          return updateOptimistic(passthrough, reducer);
        },
        useMemoCache: function(size) {
          warnInvalidHookAccess();
          return useMemoCache(size);
        },
        useHostTransitionStatus,
        useCacheRefresh: function() {
          currentHookNameInDev = "useCacheRefresh";
          updateHookTypesDev();
          return updateWorkInProgressHook().memoizedState;
        },
        useEffectEvent: function(callback) {
          currentHookNameInDev = "useEffectEvent";
          warnInvalidHookAccess();
          updateHookTypesDev();
          return updateEvent(callback);
        }
      };
      InvalidNestedHooksDispatcherOnRerenderInDEV = {
        readContext: function(context) {
          warnInvalidContextAccess();
          return readContext(context);
        },
        use: function(usable) {
          warnInvalidHookAccess();
          return use(usable);
        },
        useCallback: function(callback, deps) {
          currentHookNameInDev = "useCallback";
          warnInvalidHookAccess();
          updateHookTypesDev();
          return updateCallback(callback, deps);
        },
        useContext: function(context) {
          currentHookNameInDev = "useContext";
          warnInvalidHookAccess();
          updateHookTypesDev();
          return readContext(context);
        },
        useEffect: function(create, deps) {
          currentHookNameInDev = "useEffect";
          warnInvalidHookAccess();
          updateHookTypesDev();
          updateEffectImpl(2048, Passive, create, deps);
        },
        useImperativeHandle: function(ref, create, deps) {
          currentHookNameInDev = "useImperativeHandle";
          warnInvalidHookAccess();
          updateHookTypesDev();
          return updateImperativeHandle(ref, create, deps);
        },
        useInsertionEffect: function(create, deps) {
          currentHookNameInDev = "useInsertionEffect";
          warnInvalidHookAccess();
          updateHookTypesDev();
          return updateEffectImpl(4, Insertion, create, deps);
        },
        useLayoutEffect: function(create, deps) {
          currentHookNameInDev = "useLayoutEffect";
          warnInvalidHookAccess();
          updateHookTypesDev();
          return updateEffectImpl(4, Layout, create, deps);
        },
        useMemo: function(create, deps) {
          currentHookNameInDev = "useMemo";
          warnInvalidHookAccess();
          updateHookTypesDev();
          var prevDispatcher = ReactSharedInternals.H;
          ReactSharedInternals.H = InvalidNestedHooksDispatcherOnUpdateInDEV;
          try {
            return updateMemo(create, deps);
          } finally {
            ReactSharedInternals.H = prevDispatcher;
          }
        },
        useReducer: function(reducer, initialArg, init2) {
          currentHookNameInDev = "useReducer";
          warnInvalidHookAccess();
          updateHookTypesDev();
          var prevDispatcher = ReactSharedInternals.H;
          ReactSharedInternals.H = InvalidNestedHooksDispatcherOnUpdateInDEV;
          try {
            return rerenderReducer(reducer, initialArg, init2);
          } finally {
            ReactSharedInternals.H = prevDispatcher;
          }
        },
        useRef: function() {
          currentHookNameInDev = "useRef";
          warnInvalidHookAccess();
          updateHookTypesDev();
          return updateWorkInProgressHook().memoizedState;
        },
        useState: function() {
          currentHookNameInDev = "useState";
          warnInvalidHookAccess();
          updateHookTypesDev();
          var prevDispatcher = ReactSharedInternals.H;
          ReactSharedInternals.H = InvalidNestedHooksDispatcherOnUpdateInDEV;
          try {
            return rerenderReducer(basicStateReducer);
          } finally {
            ReactSharedInternals.H = prevDispatcher;
          }
        },
        useDebugValue: function() {
          currentHookNameInDev = "useDebugValue";
          warnInvalidHookAccess();
          updateHookTypesDev();
        },
        useDeferredValue: function(value, initialValue) {
          currentHookNameInDev = "useDeferredValue";
          warnInvalidHookAccess();
          updateHookTypesDev();
          return rerenderDeferredValue(value, initialValue);
        },
        useTransition: function() {
          currentHookNameInDev = "useTransition";
          warnInvalidHookAccess();
          updateHookTypesDev();
          return rerenderTransition();
        },
        useSyncExternalStore: function(subscribe2, getSnapshot, getServerSnapshot) {
          currentHookNameInDev = "useSyncExternalStore";
          warnInvalidHookAccess();
          updateHookTypesDev();
          return updateSyncExternalStore(
            subscribe2,
            getSnapshot,
            getServerSnapshot
          );
        },
        useId: function() {
          currentHookNameInDev = "useId";
          warnInvalidHookAccess();
          updateHookTypesDev();
          return updateWorkInProgressHook().memoizedState;
        },
        useFormState: function(action) {
          currentHookNameInDev = "useFormState";
          warnInvalidHookAccess();
          updateHookTypesDev();
          return rerenderActionState(action);
        },
        useActionState: function(action) {
          currentHookNameInDev = "useActionState";
          warnInvalidHookAccess();
          updateHookTypesDev();
          return rerenderActionState(action);
        },
        useOptimistic: function(passthrough, reducer) {
          currentHookNameInDev = "useOptimistic";
          warnInvalidHookAccess();
          updateHookTypesDev();
          return rerenderOptimistic(passthrough, reducer);
        },
        useMemoCache: function(size) {
          warnInvalidHookAccess();
          return useMemoCache(size);
        },
        useHostTransitionStatus,
        useCacheRefresh: function() {
          currentHookNameInDev = "useCacheRefresh";
          updateHookTypesDev();
          return updateWorkInProgressHook().memoizedState;
        },
        useEffectEvent: function(callback) {
          currentHookNameInDev = "useEffectEvent";
          warnInvalidHookAccess();
          updateHookTypesDev();
          return updateEvent(callback);
        }
      };
      var fakeInternalInstance = {};
      var didWarnAboutStateAssignmentForComponent = /* @__PURE__ */ new Set();
      var didWarnAboutUninitializedState = /* @__PURE__ */ new Set();
      var didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate = /* @__PURE__ */ new Set();
      var didWarnAboutLegacyLifecyclesAndDerivedState = /* @__PURE__ */ new Set();
      var didWarnAboutDirectlyAssigningPropsToState = /* @__PURE__ */ new Set();
      var didWarnAboutUndefinedDerivedState = /* @__PURE__ */ new Set();
      var didWarnAboutContextTypes$1 = /* @__PURE__ */ new Set();
      var didWarnAboutChildContextTypes = /* @__PURE__ */ new Set();
      var didWarnAboutInvalidateContextType = /* @__PURE__ */ new Set();
      var didWarnOnInvalidCallback = /* @__PURE__ */ new Set();
      Object.freeze(fakeInternalInstance);
      var classComponentUpdater = {
        enqueueSetState: function(inst, payload, callback) {
          inst = inst._reactInternals;
          var lane = requestUpdateLane(inst), update = createUpdate(lane);
          update.payload = payload;
          void 0 !== callback && null !== callback && (warnOnInvalidCallback(callback), update.callback = callback);
          payload = enqueueUpdate(inst, update, lane);
          null !== payload && (startUpdateTimerByLane(lane, "this.setState()", inst), scheduleUpdateOnFiber(payload, inst, lane), entangleTransitions(payload, inst, lane));
        },
        enqueueReplaceState: function(inst, payload, callback) {
          inst = inst._reactInternals;
          var lane = requestUpdateLane(inst), update = createUpdate(lane);
          update.tag = ReplaceState;
          update.payload = payload;
          void 0 !== callback && null !== callback && (warnOnInvalidCallback(callback), update.callback = callback);
          payload = enqueueUpdate(inst, update, lane);
          null !== payload && (startUpdateTimerByLane(lane, "this.replaceState()", inst), scheduleUpdateOnFiber(payload, inst, lane), entangleTransitions(payload, inst, lane));
        },
        enqueueForceUpdate: function(inst, callback) {
          inst = inst._reactInternals;
          var lane = requestUpdateLane(inst), update = createUpdate(lane);
          update.tag = ForceUpdate;
          void 0 !== callback && null !== callback && (warnOnInvalidCallback(callback), update.callback = callback);
          callback = enqueueUpdate(inst, update, lane);
          null !== callback && (startUpdateTimerByLane(lane, "this.forceUpdate()", inst), scheduleUpdateOnFiber(callback, inst, lane), entangleTransitions(callback, inst, lane));
        }
      }, componentName = null, errorBoundaryName = null, SelectiveHydrationException = Error(
        "This is not a real error. It's an implementation detail of React's selective hydration feature. If this leaks into userspace, it's a bug in React. Please file an issue."
      ), didReceiveUpdate = false;
      var didWarnAboutBadClass = {};
      var didWarnAboutContextTypeOnFunctionComponent = {};
      var didWarnAboutContextTypes = {};
      var didWarnAboutGetDerivedStateOnFunctionComponent = {};
      var didWarnAboutReassigningProps = false;
      var didWarnAboutRevealOrder = {};
      var didWarnAboutTailOptions = {};
      var SUSPENDED_MARKER = {
        dehydrated: null,
        treeContext: null,
        retryLane: 0,
        hydrationErrors: null
      }, hasWarnedAboutUsingNoValuePropOnContextProvider = false, didWarnAboutUndefinedSnapshotBeforeUpdate = null;
      didWarnAboutUndefinedSnapshotBeforeUpdate = /* @__PURE__ */ new Set();
      var offscreenSubtreeIsHidden = false, offscreenSubtreeWasHidden = false, needsFormReset = false, PossiblyWeakSet = "function" === typeof WeakSet ? WeakSet : Set, nextEffect = null, inProgressLanes = null, inProgressRoot = null, hostParent = null, hostParentIsContainer = false, currentHoistableRoot = null, inHydratedSubtree = false, suspenseyCommitFlag = 8192, DefaultAsyncDispatcher = {
        getCacheForType: function(resourceType) {
          var cache = readContext(CacheContext), cacheForType = cache.data.get(resourceType);
          void 0 === cacheForType && (cacheForType = resourceType(), cache.data.set(resourceType, cacheForType));
          return cacheForType;
        },
        cacheSignal: function() {
          return readContext(CacheContext).controller.signal;
        },
        getOwner: function() {
          return current;
        }
      };
      if ("function" === typeof Symbol && Symbol.for) {
        var symbolFor = Symbol.for;
        symbolFor("selector.component");
        symbolFor("selector.has_pseudo_class");
        symbolFor("selector.role");
        symbolFor("selector.test_id");
        symbolFor("selector.text");
      }
      var commitHooks = [], PossiblyWeakMap = "function" === typeof WeakMap ? WeakMap : Map, NoContext = 0, RenderContext = 2, CommitContext = 4, RootInProgress = 0, RootFatalErrored = 1, RootErrored = 2, RootSuspended = 3, RootSuspendedWithDelay = 4, RootSuspendedAtTheShell = 6, RootCompleted = 5, executionContext = NoContext, workInProgressRoot = null, workInProgress = null, workInProgressRootRenderLanes = 0, NotSuspended = 0, SuspendedOnError = 1, SuspendedOnData = 2, SuspendedOnImmediate = 3, SuspendedOnInstance = 4, SuspendedOnInstanceAndReadyToContinue = 5, SuspendedOnDeprecatedThrowPromise = 6, SuspendedAndReadyToContinue = 7, SuspendedOnHydration = 8, SuspendedOnAction = 9, workInProgressSuspendedReason = NotSuspended, workInProgressThrownValue = null, workInProgressRootDidSkipSuspendedSiblings = false, workInProgressRootIsPrerendering = false, workInProgressRootDidAttachPingListener = false, entangledRenderLanes = 0, workInProgressRootExitStatus = RootInProgress, workInProgressRootSkippedLanes = 0, workInProgressRootInterleavedUpdatedLanes = 0, workInProgressRootPingedLanes = 0, workInProgressDeferredLane = 0, workInProgressSuspendedRetryLanes = 0, workInProgressRootConcurrentErrors = null, workInProgressRootRecoverableErrors = null, workInProgressRootDidIncludeRecursiveRenderUpdate = false, globalMostRecentFallbackTime = 0, globalMostRecentTransitionTime = 0, FALLBACK_THROTTLE_MS = 300, workInProgressRootRenderTargetTime = Infinity, RENDER_TIMEOUT_MS = 500, workInProgressTransitions = null, workInProgressUpdateTask = null, legacyErrorBoundariesThatAlreadyFailed = null, IMMEDIATE_COMMIT = 0, ABORTED_VIEW_TRANSITION_COMMIT = 1, DELAYED_PASSIVE_COMMIT = 2, ANIMATION_STARTED_COMMIT = 3, NO_PENDING_EFFECTS = 0, PENDING_MUTATION_PHASE = 1, PENDING_LAYOUT_PHASE = 2, PENDING_AFTER_MUTATION_PHASE = 3, PENDING_SPAWNED_WORK = 4, PENDING_PASSIVE_PHASE = 5, pendingEffectsStatus = 0, pendingEffectsRoot = null, pendingFinishedWork = null, pendingEffectsLanes = 0, pendingEffectsRemainingLanes = 0, pendingEffectsRenderEndTime = -0, pendingPassiveTransitions = null, pendingRecoverableErrors = null, pendingSuspendedCommitReason = null, pendingDelayedCommitReason = IMMEDIATE_COMMIT, pendingSuspendedViewTransitionReason = null, NESTED_UPDATE_LIMIT = 50, nestedUpdateCount = 0, rootWithNestedUpdates = null, isFlushingPassiveEffects = false, didScheduleUpdateDuringPassiveEffects = false, NESTED_PASSIVE_UPDATE_LIMIT = 50, nestedPassiveUpdateCount = 0, rootWithPassiveNestedUpdates = null, isRunningInsertionEffect = false, didWarnStateUpdateForNotYetMountedComponent = null, didWarnAboutUpdateInRender = false;
      var didWarnAboutUpdateInRenderForAnotherComponent = /* @__PURE__ */ new Set();
      var fakeActCallbackNode$1 = {}, firstScheduledRoot = null, lastScheduledRoot = null, didScheduleMicrotask = false, didScheduleMicrotask_act = false, mightHavePendingSyncWork = false, isFlushingWork = false, currentEventTransitionLane = 0, fakeActCallbackNode = {};
      (function() {
        for (var i = 0; i < simpleEventPluginEvents.length; i++) {
          var eventName = simpleEventPluginEvents[i], domEventName = eventName.toLowerCase();
          eventName = eventName[0].toUpperCase() + eventName.slice(1);
          registerSimpleEvent(domEventName, "on" + eventName);
        }
        registerSimpleEvent(ANIMATION_END, "onAnimationEnd");
        registerSimpleEvent(ANIMATION_ITERATION, "onAnimationIteration");
        registerSimpleEvent(ANIMATION_START, "onAnimationStart");
        registerSimpleEvent("dblclick", "onDoubleClick");
        registerSimpleEvent("focusin", "onFocus");
        registerSimpleEvent("focusout", "onBlur");
        registerSimpleEvent(TRANSITION_RUN, "onTransitionRun");
        registerSimpleEvent(TRANSITION_START, "onTransitionStart");
        registerSimpleEvent(TRANSITION_CANCEL, "onTransitionCancel");
        registerSimpleEvent(TRANSITION_END, "onTransitionEnd");
      })();
      registerDirectEvent("onMouseEnter", ["mouseout", "mouseover"]);
      registerDirectEvent("onMouseLeave", ["mouseout", "mouseover"]);
      registerDirectEvent("onPointerEnter", ["pointerout", "pointerover"]);
      registerDirectEvent("onPointerLeave", ["pointerout", "pointerover"]);
      registerTwoPhaseEvent(
        "onChange",
        "change click focusin focusout input keydown keyup selectionchange".split(
          " "
        )
      );
      registerTwoPhaseEvent(
        "onSelect",
        "focusout contextmenu dragend focusin keydown keyup mousedown mouseup selectionchange".split(
          " "
        )
      );
      registerTwoPhaseEvent("onBeforeInput", [
        "compositionend",
        "keypress",
        "textInput",
        "paste"
      ]);
      registerTwoPhaseEvent(
        "onCompositionEnd",
        "compositionend focusout keydown keypress keyup mousedown".split(" ")
      );
      registerTwoPhaseEvent(
        "onCompositionStart",
        "compositionstart focusout keydown keypress keyup mousedown".split(" ")
      );
      registerTwoPhaseEvent(
        "onCompositionUpdate",
        "compositionupdate focusout keydown keypress keyup mousedown".split(" ")
      );
      var mediaEventTypes = "abort canplay canplaythrough durationchange emptied encrypted ended error loadeddata loadedmetadata loadstart pause play playing progress ratechange resize seeked seeking stalled suspend timeupdate volumechange waiting".split(
        " "
      ), nonDelegatedEvents = new Set(
        "beforetoggle cancel close invalid load scroll scrollend toggle".split(" ").concat(mediaEventTypes)
      ), listeningMarker = "_reactListening" + Math.random().toString(36).slice(2), didWarnControlledToUncontrolled = false, didWarnUncontrolledToControlled = false, didWarnFormActionType = false, didWarnFormActionName = false, didWarnFormActionTarget = false, didWarnFormActionMethod = false, didWarnPopoverTargetObject = false;
      var didWarnForNewBooleanPropsWithEmptyValue = {};
      var NORMALIZE_NEWLINES_REGEX = /\r\n?/g, NORMALIZE_NULL_AND_REPLACEMENT_REGEX = /\u0000|\uFFFD/g, xlinkNamespace = "http://www.w3.org/1999/xlink", xmlNamespace = "http://www.w3.org/XML/1998/namespace", EXPECTED_FORM_ACTION_URL = "javascript:throw new Error('React form unexpectedly submitted.')", SUPPRESS_HYDRATION_WARNING = "suppressHydrationWarning", ACTIVITY_START_DATA = "&", ACTIVITY_END_DATA = "/&", SUSPENSE_START_DATA = "$", SUSPENSE_END_DATA = "/$", SUSPENSE_PENDING_START_DATA = "$?", SUSPENSE_QUEUED_START_DATA = "$~", SUSPENSE_FALLBACK_START_DATA = "$!", PREAMBLE_CONTRIBUTION_HTML = "html", PREAMBLE_CONTRIBUTION_BODY = "body", PREAMBLE_CONTRIBUTION_HEAD = "head", FORM_STATE_IS_MATCHING = "F!", FORM_STATE_IS_NOT_MATCHING = "F", DOCUMENT_READY_STATE_LOADING = "loading", STYLE = "style", HostContextNamespaceNone = 0, HostContextNamespaceSvg = 1, HostContextNamespaceMath = 2, eventsEnabled = null, selectionInformation = null, warnedUnknownTags = { dialog: true, webview: true }, currentPopstateTransitionEvent = null, schedulerEvent = void 0, scheduleTimeout = "function" === typeof setTimeout ? setTimeout : void 0, cancelTimeout = "function" === typeof clearTimeout ? clearTimeout : void 0, noTimeout = -1, localPromise = "function" === typeof Promise ? Promise : void 0, scheduleMicrotask = "function" === typeof queueMicrotask ? queueMicrotask : "undefined" !== typeof localPromise ? function(callback) {
        return localPromise.resolve(null).then(callback).catch(handleErrorInNextTick);
      } : scheduleTimeout, previousHydratableOnEnteringScopedSingleton = null, NotLoaded = 0, Loaded = 1, Errored = 2, Settled = 3, Inserted = 4, preloadPropsMap = /* @__PURE__ */ new Map(), preconnectsSet = /* @__PURE__ */ new Set(), previousDispatcher = ReactDOMSharedInternals.d;
      ReactDOMSharedInternals.d = {
        f: function() {
          var previousWasRendering = previousDispatcher.f(), wasRendering = flushSyncWork$1();
          return previousWasRendering || wasRendering;
        },
        r: function(form) {
          var formInst = getInstanceFromNode(form);
          null !== formInst && 5 === formInst.tag && "form" === formInst.type ? requestFormReset$1(formInst) : previousDispatcher.r(form);
        },
        D: function(href) {
          previousDispatcher.D(href);
          preconnectAs("dns-prefetch", href, null);
        },
        C: function(href, crossOrigin) {
          previousDispatcher.C(href, crossOrigin);
          preconnectAs("preconnect", href, crossOrigin);
        },
        L: function(href, as, options) {
          previousDispatcher.L(href, as, options);
          var ownerDocument = globalDocument;
          if (ownerDocument && href && as) {
            var preloadSelector = 'link[rel="preload"][as="' + escapeSelectorAttributeValueInsideDoubleQuotes(as) + '"]';
            "image" === as ? options && options.imageSrcSet ? (preloadSelector += '[imagesrcset="' + escapeSelectorAttributeValueInsideDoubleQuotes(
              options.imageSrcSet
            ) + '"]', "string" === typeof options.imageSizes && (preloadSelector += '[imagesizes="' + escapeSelectorAttributeValueInsideDoubleQuotes(
              options.imageSizes
            ) + '"]')) : preloadSelector += '[href="' + escapeSelectorAttributeValueInsideDoubleQuotes(href) + '"]' : preloadSelector += '[href="' + escapeSelectorAttributeValueInsideDoubleQuotes(href) + '"]';
            var key = preloadSelector;
            switch (as) {
              case "style":
                key = getStyleKey(href);
                break;
              case "script":
                key = getScriptKey(href);
            }
            preloadPropsMap.has(key) || (href = assign(
              {
                rel: "preload",
                href: "image" === as && options && options.imageSrcSet ? void 0 : href,
                as
              },
              options
            ), preloadPropsMap.set(key, href), null !== ownerDocument.querySelector(preloadSelector) || "style" === as && ownerDocument.querySelector(
              getStylesheetSelectorFromKey(key)
            ) || "script" === as && ownerDocument.querySelector(getScriptSelectorFromKey(key)) || (as = ownerDocument.createElement("link"), setInitialProperties(as, "link", href), markNodeAsHoistable(as), ownerDocument.head.appendChild(as)));
          }
        },
        m: function(href, options) {
          previousDispatcher.m(href, options);
          var ownerDocument = globalDocument;
          if (ownerDocument && href) {
            var as = options && "string" === typeof options.as ? options.as : "script", preloadSelector = 'link[rel="modulepreload"][as="' + escapeSelectorAttributeValueInsideDoubleQuotes(as) + '"][href="' + escapeSelectorAttributeValueInsideDoubleQuotes(href) + '"]', key = preloadSelector;
            switch (as) {
              case "audioworklet":
              case "paintworklet":
              case "serviceworker":
              case "sharedworker":
              case "worker":
              case "script":
                key = getScriptKey(href);
            }
            if (!preloadPropsMap.has(key) && (href = assign({ rel: "modulepreload", href }, options), preloadPropsMap.set(key, href), null === ownerDocument.querySelector(preloadSelector))) {
              switch (as) {
                case "audioworklet":
                case "paintworklet":
                case "serviceworker":
                case "sharedworker":
                case "worker":
                case "script":
                  if (ownerDocument.querySelector(getScriptSelectorFromKey(key)))
                    return;
              }
              as = ownerDocument.createElement("link");
              setInitialProperties(as, "link", href);
              markNodeAsHoistable(as);
              ownerDocument.head.appendChild(as);
            }
          }
        },
        X: function(src, options) {
          previousDispatcher.X(src, options);
          var ownerDocument = globalDocument;
          if (ownerDocument && src) {
            var scripts = getResourcesFromRoot(ownerDocument).hoistableScripts, key = getScriptKey(src), resource = scripts.get(key);
            resource || (resource = ownerDocument.querySelector(
              getScriptSelectorFromKey(key)
            ), resource || (src = assign({ src, async: true }, options), (options = preloadPropsMap.get(key)) && adoptPreloadPropsForScript(src, options), resource = ownerDocument.createElement("script"), markNodeAsHoistable(resource), setInitialProperties(resource, "link", src), ownerDocument.head.appendChild(resource)), resource = {
              type: "script",
              instance: resource,
              count: 1,
              state: null
            }, scripts.set(key, resource));
          }
        },
        S: function(href, precedence, options) {
          previousDispatcher.S(href, precedence, options);
          var ownerDocument = globalDocument;
          if (ownerDocument && href) {
            var styles2 = getResourcesFromRoot(ownerDocument).hoistableStyles, key = getStyleKey(href);
            precedence = precedence || "default";
            var resource = styles2.get(key);
            if (!resource) {
              var state = { loading: NotLoaded, preload: null };
              if (resource = ownerDocument.querySelector(
                getStylesheetSelectorFromKey(key)
              ))
                state.loading = Loaded | Inserted;
              else {
                href = assign(
                  {
                    rel: "stylesheet",
                    href,
                    "data-precedence": precedence
                  },
                  options
                );
                (options = preloadPropsMap.get(key)) && adoptPreloadPropsForStylesheet(href, options);
                var link = resource = ownerDocument.createElement("link");
                markNodeAsHoistable(link);
                setInitialProperties(link, "link", href);
                link._p = new Promise(function(resolve, reject) {
                  link.onload = resolve;
                  link.onerror = reject;
                });
                link.addEventListener("load", function() {
                  state.loading |= Loaded;
                });
                link.addEventListener("error", function() {
                  state.loading |= Errored;
                });
                state.loading |= Inserted;
                insertStylesheet(resource, precedence, ownerDocument);
              }
              resource = {
                type: "stylesheet",
                instance: resource,
                count: 1,
                state
              };
              styles2.set(key, resource);
            }
          }
        },
        M: function(src, options) {
          previousDispatcher.M(src, options);
          var ownerDocument = globalDocument;
          if (ownerDocument && src) {
            var scripts = getResourcesFromRoot(ownerDocument).hoistableScripts, key = getScriptKey(src), resource = scripts.get(key);
            resource || (resource = ownerDocument.querySelector(
              getScriptSelectorFromKey(key)
            ), resource || (src = assign({ src, async: true, type: "module" }, options), (options = preloadPropsMap.get(key)) && adoptPreloadPropsForScript(src, options), resource = ownerDocument.createElement("script"), markNodeAsHoistable(resource), setInitialProperties(resource, "link", src), ownerDocument.head.appendChild(resource)), resource = {
              type: "script",
              instance: resource,
              count: 1,
              state: null
            }, scripts.set(key, resource));
          }
        }
      };
      var globalDocument = "undefined" === typeof document ? null : document, tagCaches = null, SUSPENSEY_STYLESHEET_TIMEOUT = 6e4, SUSPENSEY_IMAGE_TIMEOUT = 800, SUSPENSEY_IMAGE_TIME_ESTIMATE = 500, estimatedBytesWithinLimit = 0, LAST_PRECEDENCE = null, precedencesByRoot = null, NotPendingTransition = NotPending, HostTransitionContext = {
        $$typeof: REACT_CONTEXT_TYPE,
        Provider: null,
        Consumer: null,
        _currentValue: NotPendingTransition,
        _currentValue2: NotPendingTransition,
        _threadCount: 0
      }, badgeFormat = "%c%s%c", badgeStyle = "background: #e6e6e6;background: light-dark(rgba(0,0,0,0.1), rgba(255,255,255,0.25));color: #000000;color: light-dark(#000000, #ffffff);border-radius: 2px", resetStyle = "", pad2 = " ", bind2 = Function.prototype.bind;
      var didWarnAboutNestedUpdates = false;
      var overrideHookState = null, overrideHookStateDeletePath = null, overrideHookStateRenamePath = null, overrideProps = null, overridePropsDeletePath = null, overridePropsRenamePath = null, scheduleUpdate = null, scheduleRetry = null, setErrorHandler = null, setSuspenseHandler = null;
      overrideHookState = function(fiber, id, path2, value) {
        id = findHook(fiber, id);
        null !== id && (path2 = copyWithSetImpl(id.memoizedState, path2, 0, value), id.memoizedState = path2, id.baseState = path2, fiber.memoizedProps = assign({}, fiber.memoizedProps), path2 = enqueueConcurrentRenderForLane(fiber, 2), null !== path2 && scheduleUpdateOnFiber(path2, fiber, 2));
      };
      overrideHookStateDeletePath = function(fiber, id, path2) {
        id = findHook(fiber, id);
        null !== id && (path2 = copyWithDeleteImpl(id.memoizedState, path2, 0), id.memoizedState = path2, id.baseState = path2, fiber.memoizedProps = assign({}, fiber.memoizedProps), path2 = enqueueConcurrentRenderForLane(fiber, 2), null !== path2 && scheduleUpdateOnFiber(path2, fiber, 2));
      };
      overrideHookStateRenamePath = function(fiber, id, oldPath, newPath) {
        id = findHook(fiber, id);
        null !== id && (oldPath = copyWithRename(id.memoizedState, oldPath, newPath), id.memoizedState = oldPath, id.baseState = oldPath, fiber.memoizedProps = assign({}, fiber.memoizedProps), oldPath = enqueueConcurrentRenderForLane(fiber, 2), null !== oldPath && scheduleUpdateOnFiber(oldPath, fiber, 2));
      };
      overrideProps = function(fiber, path2, value) {
        fiber.pendingProps = copyWithSetImpl(fiber.memoizedProps, path2, 0, value);
        fiber.alternate && (fiber.alternate.pendingProps = fiber.pendingProps);
        path2 = enqueueConcurrentRenderForLane(fiber, 2);
        null !== path2 && scheduleUpdateOnFiber(path2, fiber, 2);
      };
      overridePropsDeletePath = function(fiber, path2) {
        fiber.pendingProps = copyWithDeleteImpl(fiber.memoizedProps, path2, 0);
        fiber.alternate && (fiber.alternate.pendingProps = fiber.pendingProps);
        path2 = enqueueConcurrentRenderForLane(fiber, 2);
        null !== path2 && scheduleUpdateOnFiber(path2, fiber, 2);
      };
      overridePropsRenamePath = function(fiber, oldPath, newPath) {
        fiber.pendingProps = copyWithRename(
          fiber.memoizedProps,
          oldPath,
          newPath
        );
        fiber.alternate && (fiber.alternate.pendingProps = fiber.pendingProps);
        oldPath = enqueueConcurrentRenderForLane(fiber, 2);
        null !== oldPath && scheduleUpdateOnFiber(oldPath, fiber, 2);
      };
      scheduleUpdate = function(fiber) {
        var root2 = enqueueConcurrentRenderForLane(fiber, 2);
        null !== root2 && scheduleUpdateOnFiber(root2, fiber, 2);
      };
      scheduleRetry = function(fiber) {
        var lane = claimNextRetryLane(), root2 = enqueueConcurrentRenderForLane(fiber, lane);
        null !== root2 && scheduleUpdateOnFiber(root2, fiber, lane);
      };
      setErrorHandler = function(newShouldErrorImpl) {
        shouldErrorImpl = newShouldErrorImpl;
      };
      setSuspenseHandler = function(newShouldSuspendImpl) {
        shouldSuspendImpl = newShouldSuspendImpl;
      };
      var _enabled = true, return_targetInst = null, hasScheduledReplayAttempt = false, queuedFocus = null, queuedDrag = null, queuedMouse = null, queuedPointers = /* @__PURE__ */ new Map(), queuedPointerCaptures = /* @__PURE__ */ new Map(), queuedExplicitHydrationTargets = [], discreteReplayableEvents = "mousedown mouseup touchcancel touchend touchstart auxclick dblclick pointercancel pointerdown pointerup dragend dragstart drop compositionend compositionstart keydown keypress keyup input textInput copy cut paste click change contextmenu reset".split(
        " "
      ), lastScheduledReplayQueue = null;
      ReactDOMHydrationRoot.prototype.render = ReactDOMRoot.prototype.render = function(children) {
        var root2 = this._internalRoot;
        if (null === root2) throw Error("Cannot update an unmounted root.");
        var args = arguments;
        "function" === typeof args[1] ? console.error(
          "does not support the second callback argument. To execute a side effect after rendering, declare it in a component body with useEffect()."
        ) : isValidContainer(args[1]) ? console.error(
          "You passed a container to the second argument of root.render(...). You don't need to pass it again since you already passed it to create the root."
        ) : "undefined" !== typeof args[1] && console.error(
          "You passed a second argument to root.render(...) but it only accepts one argument."
        );
        args = children;
        var current2 = root2.current, lane = requestUpdateLane(current2);
        updateContainerImpl(current2, lane, args, root2, null, null);
      };
      ReactDOMHydrationRoot.prototype.unmount = ReactDOMRoot.prototype.unmount = function() {
        var args = arguments;
        "function" === typeof args[0] && console.error(
          "does not support a callback argument. To execute a side effect after rendering, declare it in a component body with useEffect()."
        );
        args = this._internalRoot;
        if (null !== args) {
          this._internalRoot = null;
          var container = args.containerInfo;
          (executionContext & (RenderContext | CommitContext)) !== NoContext && console.error(
            "Attempted to synchronously unmount a root while React was already rendering. React cannot finish unmounting the root until the current render has completed, which may lead to a race condition."
          );
          updateContainerImpl(args.current, 2, null, args, null, null);
          flushSyncWork$1();
          container[internalContainerInstanceKey] = null;
        }
      };
      ReactDOMHydrationRoot.prototype.unstable_scheduleHydration = function(target2) {
        if (target2) {
          var updatePriority = resolveUpdatePriority();
          target2 = { blockedOn: null, target: target2, priority: updatePriority };
          for (var i = 0; i < queuedExplicitHydrationTargets.length && 0 !== updatePriority && updatePriority < queuedExplicitHydrationTargets[i].priority; i++) ;
          queuedExplicitHydrationTargets.splice(i, 0, target2);
          0 === i && attemptExplicitHydrationTarget(target2);
        }
      };
      (function() {
        var isomorphicReactPackageVersion = React7.version;
        if ("19.2.3" !== isomorphicReactPackageVersion)
          throw Error(
            'Incompatible React versions: The "react" and "react-dom" packages must have the exact same version. Instead got:\n  - react:      ' + (isomorphicReactPackageVersion + "\n  - react-dom:  19.2.3\nLearn more: https://react.dev/warnings/version-mismatch")
          );
      })();
      "function" === typeof Map && null != Map.prototype && "function" === typeof Map.prototype.forEach && "function" === typeof Set && null != Set.prototype && "function" === typeof Set.prototype.clear && "function" === typeof Set.prototype.forEach || console.error(
        "React depends on Map and Set built-in types. Make sure that you load a polyfill in older browsers. https://react.dev/link/react-polyfills"
      );
      ReactDOMSharedInternals.findDOMNode = function(componentOrElement) {
        var fiber = componentOrElement._reactInternals;
        if (void 0 === fiber) {
          if ("function" === typeof componentOrElement.render)
            throw Error("Unable to find node on an unmounted component.");
          componentOrElement = Object.keys(componentOrElement).join(",");
          throw Error(
            "Argument appears to not be a ReactComponent. Keys: " + componentOrElement
          );
        }
        componentOrElement = findCurrentFiberUsingSlowPath(fiber);
        componentOrElement = null !== componentOrElement ? findCurrentHostFiberImpl(componentOrElement) : null;
        componentOrElement = null === componentOrElement ? null : componentOrElement.stateNode;
        return componentOrElement;
      };
      if (!(function() {
        var internals = {
          bundleType: 1,
          version: "19.2.3",
          rendererPackageName: "react-dom",
          currentDispatcherRef: ReactSharedInternals,
          reconcilerVersion: "19.2.3"
        };
        internals.overrideHookState = overrideHookState;
        internals.overrideHookStateDeletePath = overrideHookStateDeletePath;
        internals.overrideHookStateRenamePath = overrideHookStateRenamePath;
        internals.overrideProps = overrideProps;
        internals.overridePropsDeletePath = overridePropsDeletePath;
        internals.overridePropsRenamePath = overridePropsRenamePath;
        internals.scheduleUpdate = scheduleUpdate;
        internals.scheduleRetry = scheduleRetry;
        internals.setErrorHandler = setErrorHandler;
        internals.setSuspenseHandler = setSuspenseHandler;
        internals.scheduleRefresh = scheduleRefresh;
        internals.scheduleRoot = scheduleRoot;
        internals.setRefreshHandler = setRefreshHandler;
        internals.getCurrentFiber = getCurrentFiberForDevTools;
        return injectInternals(internals);
      })() && canUseDOM && window.top === window.self && (-1 < navigator.userAgent.indexOf("Chrome") && -1 === navigator.userAgent.indexOf("Edge") || -1 < navigator.userAgent.indexOf("Firefox"))) {
        var protocol = window.location.protocol;
        /^(https?|file):$/.test(protocol) && console.info(
          "%cDownload the React DevTools for a better development experience: https://react.dev/link/react-devtools" + ("file:" === protocol ? "\nYou might need to use a local HTTP server (instead of file://): https://react.dev/link/react-devtools-faq" : ""),
          "font-weight:bold"
        );
      }
      exports.createRoot = function(container, options) {
        if (!isValidContainer(container))
          throw Error("Target container is not a DOM element.");
        warnIfReactDOMContainerInDEV(container);
        var isStrictMode = false, identifierPrefix = "", onUncaughtError = defaultOnUncaughtError, onCaughtError = defaultOnCaughtError, onRecoverableError = defaultOnRecoverableError;
        null !== options && void 0 !== options && (options.hydrate ? console.warn(
          "hydrate through createRoot is deprecated. Use ReactDOMClient.hydrateRoot(container, <App />) instead."
        ) : "object" === typeof options && null !== options && options.$$typeof === REACT_ELEMENT_TYPE && console.error(
          "You passed a JSX element to createRoot. You probably meant to call root.render instead. Example usage:\n\n  let root = createRoot(domContainer);\n  root.render(<App />);"
        ), true === options.unstable_strictMode && (isStrictMode = true), void 0 !== options.identifierPrefix && (identifierPrefix = options.identifierPrefix), void 0 !== options.onUncaughtError && (onUncaughtError = options.onUncaughtError), void 0 !== options.onCaughtError && (onCaughtError = options.onCaughtError), void 0 !== options.onRecoverableError && (onRecoverableError = options.onRecoverableError));
        options = createFiberRoot(
          container,
          1,
          false,
          null,
          null,
          isStrictMode,
          identifierPrefix,
          null,
          onUncaughtError,
          onCaughtError,
          onRecoverableError,
          defaultOnDefaultTransitionIndicator
        );
        container[internalContainerInstanceKey] = options.current;
        listenToAllSupportedEvents(container);
        return new ReactDOMRoot(options);
      };
      exports.hydrateRoot = function(container, initialChildren, options) {
        if (!isValidContainer(container))
          throw Error("Target container is not a DOM element.");
        warnIfReactDOMContainerInDEV(container);
        void 0 === initialChildren && console.error(
          "Must provide initial children as second argument to hydrateRoot. Example usage: hydrateRoot(domContainer, <App />)"
        );
        var isStrictMode = false, identifierPrefix = "", onUncaughtError = defaultOnUncaughtError, onCaughtError = defaultOnCaughtError, onRecoverableError = defaultOnRecoverableError, formState = null;
        null !== options && void 0 !== options && (true === options.unstable_strictMode && (isStrictMode = true), void 0 !== options.identifierPrefix && (identifierPrefix = options.identifierPrefix), void 0 !== options.onUncaughtError && (onUncaughtError = options.onUncaughtError), void 0 !== options.onCaughtError && (onCaughtError = options.onCaughtError), void 0 !== options.onRecoverableError && (onRecoverableError = options.onRecoverableError), void 0 !== options.formState && (formState = options.formState));
        initialChildren = createFiberRoot(
          container,
          1,
          true,
          initialChildren,
          null != options ? options : null,
          isStrictMode,
          identifierPrefix,
          formState,
          onUncaughtError,
          onCaughtError,
          onRecoverableError,
          defaultOnDefaultTransitionIndicator
        );
        initialChildren.context = getContextForSubtree(null);
        options = initialChildren.current;
        isStrictMode = requestUpdateLane(options);
        isStrictMode = getBumpedLaneForHydrationByLane(isStrictMode);
        identifierPrefix = createUpdate(isStrictMode);
        identifierPrefix.callback = null;
        enqueueUpdate(options, identifierPrefix, isStrictMode);
        startUpdateTimerByLane(isStrictMode, "hydrateRoot()", null);
        options = isStrictMode;
        initialChildren.current.lanes = options;
        markRootUpdated$1(initialChildren, options);
        ensureRootIsScheduled(initialChildren);
        container[internalContainerInstanceKey] = initialChildren.current;
        listenToAllSupportedEvents(container);
        return new ReactDOMHydrationRoot(initialChildren);
      };
      exports.version = "19.2.3";
      "undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ && "function" === typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop && __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(Error());
    })();
  }
});

// ../../node_modules/.pnpm/react-dom@19.2.3_react@19.2.3/node_modules/react-dom/client.js
var require_client = __commonJS({
  "../../node_modules/.pnpm/react-dom@19.2.3_react@19.2.3/node_modules/react-dom/client.js"(exports, module) {
    "use strict";
    if (false) {
      checkDCE();
      module.exports = null;
    } else {
      module.exports = require_react_dom_client_development();
    }
  }
});

// ../core/src/relations.ts
function normalizeRelationDirection(value) {
  return typeof value === "string" && RELATION_DIRECTIONS.has(value) ? value : void 0;
}
function normalizeRelationEndpoint(value) {
  if (!value || typeof value !== "object" || Array.isArray(value)) return null;
  const input = value;
  const kind = input.kind;
  const port = normalizeEndpointPort(input.port);
  const portRatio = normalizeEndpointPortRatio(input.portRatio);
  if (kind === "summary") {
    const summaryId = typeof input.summaryId === "string" ? input.summaryId.trim() : "";
    if (!summaryId) return null;
    return {
      kind: "summary",
      summaryId,
      ...port ? { port } : {},
      ...portRatio !== void 0 ? { portRatio } : {}
    };
  }
  const nodeId = typeof input.nodeId === "string" ? input.nodeId.trim() : "";
  if (!nodeId) return null;
  return {
    kind: "node",
    nodeId,
    ...port ? { port } : {},
    ...portRatio !== void 0 ? { portRatio } : {}
  };
}
function relationEndpointKey(endpoint) {
  return endpoint.kind === "summary" ? `summary:${endpoint.summaryId}` : `node:${endpoint.nodeId}`;
}
function relationEndpointPort(endpoint) {
  return endpoint.port;
}
function relationEndpointPortRatio(endpoint) {
  return endpoint.portRatio;
}
function relationEndpointExists(doc3, endpoint) {
  return endpoint.kind === "summary" ? doc3.summaries.some((summary) => summary.id === endpoint.summaryId) : Boolean(doc3.nodes[endpoint.nodeId]);
}
function getRelationEndpointRootId(doc3, endpoint) {
  return endpoint.kind === "summary" ? getSummaryRootId(doc3, endpoint.summaryId) : getNodeRootIdFromDocument(doc3, endpoint.nodeId);
}
function normalizeThemeRelationOverride(raw) {
  if (!raw || typeof raw !== "object" || Array.isArray(raw)) return void 0;
  const strokeColor = raw.strokeColor;
  const strokeWidth = raw.strokeWidth;
  const dasharray = raw.dasharray;
  const direction = normalizeRelationDirection(raw.direction);
  const next = {};
  if (typeof strokeColor === "string" && strokeColor.trim().length > 0) next.strokeColor = strokeColor.trim();
  if (typeof strokeWidth === "number" && Number.isFinite(strokeWidth)) next.strokeWidth = Math.max(0.5, Math.min(12, Math.round(strokeWidth * 10) / 10));
  if (typeof dasharray === "string" && dasharray.trim().length > 0) next.dasharray = dasharray.trim();
  if (direction) next.direction = direction;
  return Object.keys(next).length > 0 ? next : void 0;
}
function normalizeRelationForDocument(doc3, relation) {
  const from2 = normalizeRelationEndpoint(relation.from);
  const to = normalizeRelationEndpoint(relation.to);
  if (!from2 || !to) return null;
  if (!relationEndpointExists(doc3, from2) || !relationEndpointExists(doc3, to)) return null;
  if (relationEndpointKey(from2) === relationEndpointKey(to)) return null;
  return {
    ...relation,
    from: from2,
    to,
    direction: normalizeRelationDirection(relation.direction),
    style: normalizeRelationInstanceStyle(relation.style)
  };
}
function relationEndpointsShareRoot(doc3, relation) {
  const fromRootId = getRelationEndpointRootId(doc3, relation.from);
  if (!fromRootId) return null;
  const toRootId = getRelationEndpointRootId(doc3, relation.to);
  return fromRootId && fromRootId === toRootId ? fromRootId : null;
}
function normalizeEndpointPort(value) {
  return typeof value === "string" && NODE_PORTS.has(value) ? value : void 0;
}
function normalizeEndpointPortRatio(value) {
  if (typeof value !== "number" || !Number.isFinite(value)) return void 0;
  return Math.max(0, Math.min(1, value));
}
function normalizeRelationInstanceStyle(style2) {
  if (!style2 || typeof style2 !== "object") return void 0;
  const next = {};
  if (typeof style2.strokeColor === "string" && style2.strokeColor.trim().length > 0) next.strokeColor = style2.strokeColor.trim();
  if (typeof style2.strokeWidth === "number" && Number.isFinite(style2.strokeWidth)) next.strokeWidth = Math.max(0.5, Math.min(12, Math.round(style2.strokeWidth * 10) / 10));
  if (typeof style2.strokeDasharray === "string" && style2.strokeDasharray.trim().length > 0) next.strokeDasharray = style2.strokeDasharray.trim();
  return Object.keys(next).length > 0 ? next : void 0;
}
function getNodeRootIdFromDocument(doc3, nodeId) {
  const rootSet = new Set(doc3.roots);
  const summaryById = new Map(doc3.summaries.map((summary) => [summary.id, summary]));
  const visitedNodes = /* @__PURE__ */ new Set();
  let current = nodeId;
  while (current) {
    if (visitedNodes.has(current)) return null;
    visitedNodes.add(current);
    if (rootSet.has(current)) return current;
    const node = doc3.nodes[current];
    if (!node) return null;
    if (node.parentId) {
      current = node.parentId;
      continue;
    }
    if (node.parentSummaryId) {
      current = getSummaryParentNodeId(summaryById, node.parentSummaryId);
      continue;
    }
    return null;
  }
  return null;
}
function getSummaryRootId(doc3, summaryId) {
  const summaryById = new Map(doc3.summaries.map((summary) => [summary.id, summary]));
  const parentNodeId = getSummaryParentNodeId(summaryById, summaryId);
  return parentNodeId ? getNodeRootIdFromDocument(doc3, parentNodeId) : null;
}
function getSummaryParentNodeId(summaryById, summaryId) {
  const visited = /* @__PURE__ */ new Set();
  let current = summaryId;
  while (current) {
    if (visited.has(current)) return null;
    visited.add(current);
    const summary = summaryById.get(current);
    if (!summary) return null;
    const parentId = summary.parentId;
    if (summaryById.has(parentId)) {
      current = parentId;
      continue;
    }
    return parentId;
  }
  return null;
}
var RELATION_DIRECTIONS, NODE_PORTS;
var init_relations = __esm({
  "../core/src/relations.ts"() {
    "use strict";
    RELATION_DIRECTIONS = /* @__PURE__ */ new Set(["none", "forward", "backward", "both"]);
    NODE_PORTS = /* @__PURE__ */ new Set(["top", "right", "bottom", "left"]);
  }
});

// ../core/src/theme.ts
function createDefaultThemeDefinition() {
  const baseLayout = {
    fontFamily: "ui-sans-serif, system-ui, sans-serif",
    fontSize: 14,
    fontWeight: 400,
    lineHeight: 1.4,
    textAlign: "left",
    paddingX: 12,
    paddingY: 8,
    nodeMinWidth: 60,
    nodeMinHeight: 34
  };
  const lightPaint = {
    bg: "#f8fafc",
    panel: "#ffffff",
    text: "#0f172a",
    muted: "#64748b",
    border: "#e2e8f0",
    nodeFill: "#ffffff",
    nodeFillSelected: "#eff6ff",
    nodeStroke: "#cbd5e1",
    nodeStrokeSelected: "#2563eb",
    edgeStroke: "#94a3b8",
    relationStroke: "#f59e0b",
    relationStrokeSelected: "#fb7185",
    summaryStroke: "#94a3b8"
  };
  const darkPaint = {
    bg: "#0b1220",
    panel: "#0f172a",
    text: "#e2e8f0",
    muted: "#94a3b8",
    border: "rgba(148, 163, 184, 0.25)",
    nodeFill: "#0b1220",
    nodeFillSelected: "#0b1b3a",
    nodeStroke: "rgba(148, 163, 184, 0.45)",
    nodeStrokeSelected: "#60a5fa",
    edgeStroke: "rgba(148, 163, 184, 0.55)",
    relationStroke: "#f59e0b",
    relationStrokeSelected: "#fb7185",
    summaryStroke: "rgba(148, 163, 184, 0.55)"
  };
  const baseEdges = {
    routeType: "cubic",
    strokeWidth: 2,
    cap: "round",
    join: "round"
  };
  const baseRelations = {
    strokeWidth: 2,
    cap: "round",
    join: "round"
  };
  const baseShape = {
    type: "rounded-rect",
    radius: 10,
    strokeWidth: 2
  };
  const baseRainbow = {
    enabled: false,
    palette: DEFAULT_RAINBOW_PALETTE
  };
  return {
    schemaVersion: 1,
    id: DEFAULT_THEME_ID,
    name: "KMind Default",
    variants: {
      light: {
        tokens: {
          layout: { ...baseLayout },
          paint: lightPaint
        },
        edges: baseEdges,
        relations: baseRelations,
        nodeShape: baseShape,
        rainbow: baseRainbow
      },
      dark: {
        tokens: {
          layout: { ...baseLayout },
          paint: darkPaint
        },
        edges: baseEdges,
        relations: baseRelations,
        nodeShape: baseShape,
        rainbow: baseRainbow
      }
    }
  };
}
function createDefaultDocumentThemeState(defaultTheme2) {
  return {
    schemaVersion: 1,
    defaultTheme: defaultTheme2,
    appearance: { mode: "fixed", fixed: "light" },
    rainbow: { enabled: false, branchColors: {}, paletteOverride: void 0 },
    overrides: void 0,
    rootThemes: void 0
  };
}
function buildNodeDepthIndex(doc3) {
  const summaryById = new Map(doc3.summaries.map((summary) => [summary.id, summary]));
  const summaryDepthById = {};
  const nodeDepthById = {};
  const resolveSummaryDepth = (summaryId, visited) => {
    if (typeof summaryId !== "string" || summaryId.length === 0) return null;
    if (Object.prototype.hasOwnProperty.call(summaryDepthById, summaryId)) return summaryDepthById[summaryId];
    const key = `s:${summaryId}`;
    if (visited.has(key)) return null;
    visited.add(key);
    const summary = summaryById.get(summaryId);
    if (!summary) return null;
    const parentId = summary.parentId;
    if (typeof parentId !== "string" || parentId.length === 0) return null;
    const parentNode2 = doc3.nodes[parentId];
    if (parentNode2) {
      const base3 = resolveNodeDepth(parentId, visited);
      if (base3 == null) return null;
      const depth2 = base3 + 1;
      summaryDepthById[summaryId] = depth2;
      return depth2;
    }
    const parentSummary = summaryById.get(parentId);
    if (!parentSummary) return null;
    const base2 = resolveSummaryDepth(parentId, visited);
    if (base2 == null) return null;
    const depth = base2 + 1;
    summaryDepthById[summaryId] = depth;
    return depth;
  };
  const resolveNodeDepth = (nodeId, visited) => {
    if (typeof nodeId !== "string" || nodeId.length === 0) return null;
    if (Object.prototype.hasOwnProperty.call(nodeDepthById, nodeId)) return nodeDepthById[nodeId];
    const key = `n:${nodeId}`;
    if (visited.has(key)) return null;
    visited.add(key);
    const node = doc3.nodes[nodeId];
    if (!node) return null;
    if (!node.parentId && !node.parentSummaryId) {
      nodeDepthById[nodeId] = 0;
      return 0;
    }
    if (node.parentId) {
      const base2 = resolveNodeDepth(node.parentId, visited);
      if (base2 == null) return null;
      const depth = base2 + 1;
      nodeDepthById[nodeId] = depth;
      return depth;
    }
    const parentSummaryId = node.parentSummaryId;
    if (parentSummaryId) {
      const base2 = resolveSummaryDepth(parentSummaryId, visited);
      if (base2 == null) return null;
      const depth = base2 + 1;
      nodeDepthById[nodeId] = depth;
      return depth;
    }
    nodeDepthById[nodeId] = 0;
    return 0;
  };
  for (const rootId of doc3.roots) {
    nodeDepthById[rootId] = 0;
  }
  for (const nodeId of Object.keys(doc3.nodes)) {
    resolveNodeDepth(nodeId, /* @__PURE__ */ new Set());
  }
  for (const nodeId of Object.keys(doc3.nodes)) {
    if (Object.prototype.hasOwnProperty.call(nodeDepthById, nodeId)) continue;
    nodeDepthById[nodeId] = 0;
  }
  for (const summaryId of summaryById.keys()) {
    resolveSummaryDepth(summaryId, /* @__PURE__ */ new Set());
  }
  for (const summaryId of summaryById.keys()) {
    if (Object.prototype.hasOwnProperty.call(summaryDepthById, summaryId)) continue;
    summaryDepthById[summaryId] = 0;
  }
  return { nodeDepthById, summaryDepthById };
}
function resolveThemeVariantId(policy, env) {
  const fallback = "light";
  if (!policy) return fallback;
  if (policy.mode === "fixed") return policy.fixed;
  if (policy.mode === "system") return env.systemPrefersDark ? "dark" : "light";
  if (policy.mode === "external") {
    const value = env.external?.[policy.external.key];
    if (value === "dark" || value === "light") return value;
    if (typeof value === "boolean") return value ? "dark" : "light";
    return fallback;
  }
  const now = env.now ?? /* @__PURE__ */ new Date();
  const timezone = policy.time.timezone ?? "local";
  const minutes = timezone === "utc" ? now.getUTCHours() * 60 + now.getUTCMinutes() : now.getHours() * 60 + now.getMinutes();
  const lightAt = parseTimeToMinutes(policy.time.lightAt);
  const darkAt = parseTimeToMinutes(policy.time.darkAt);
  if (lightAt == null || darkAt == null) return fallback;
  if (darkAt > lightAt) {
    return minutes >= darkAt || minutes < lightAt ? "dark" : "light";
  }
  return minutes >= darkAt && minutes < lightAt ? "dark" : "light";
}
function computeLayoutFingerprint(layout, shape) {
  const radius = shape?.radius ?? "";
  const shapeKey = shape ? `${shape.type}:${radius}` : "";
  return [
    "v1",
    NODE_BODY_CSS_VERSION,
    layout.fontFamily,
    String(layout.fontSize),
    String(layout.fontWeight ?? ""),
    String(layout.lineHeight),
    String(layout.textAlign ?? ""),
    String(layout.paddingX),
    String(layout.paddingY),
    String(layout.nodeMinWidth ?? ""),
    String(layout.nodeMinHeight ?? ""),
    shapeKey
  ].join("|");
}
function resolveThemeDefinition(ref, assets) {
  if (ref.source === "inline") {
    return isThemeDefinition(ref.value) ? ref.value : null;
  }
  if (ref.source === "asset") {
    const asset = assets?.[ref.assetId];
    if (!asset || asset.kind !== "json") return null;
    return isThemeDefinition(asset.data) ? asset.data : null;
  }
  return null;
}
function resolveThemeVariant(definition, variantId) {
  return definition.variants[variantId] ?? definition.variants.light ?? Object.values(definition.variants)[0];
}
function resolveDocumentTheme(doc3, env = {}) {
  const themeState = normalizeThemeState(doc3.theme, doc3.assets ?? {}) ?? createDefaultDocumentThemeState({
    source: "inline",
    value: createDefaultThemeDefinition()
  });
  const variantId = resolveThemeVariantId(themeState.appearance, env);
  const definition = resolveThemeDefinition(themeState.defaultTheme, doc3.assets) ?? createDefaultThemeDefinition();
  const variant = resolveThemeVariant(definition, variantId);
  return toResolvedDocumentTheme(variantId, variant);
}
function resolveRootTheme(doc3, rootId, env = {}) {
  const themeState = normalizeThemeState(doc3.theme, doc3.assets ?? {}) ?? createDefaultDocumentThemeState({
    source: "inline",
    value: createDefaultThemeDefinition()
  });
  const variantId = resolveThemeVariantId(themeState.appearance, env);
  const ref = themeState.rootThemes?.[rootId] ?? themeState.defaultTheme;
  const definition = resolveThemeDefinition(ref, doc3.assets) ?? createDefaultThemeDefinition();
  const variant = resolveThemeVariant(definition, variantId);
  return toResolvedDocumentTheme(variantId, variant);
}
function resolveNodeTheme(doc3, nodeId, env = {}, options = {}) {
  const themeState = normalizeThemeState(doc3.theme, doc3.assets ?? {}) ?? createDefaultDocumentThemeState({
    source: "inline",
    value: createDefaultThemeDefinition()
  });
  const variantId = resolveThemeVariantId(themeState.appearance, env);
  const rootId = getNodeRootId(doc3, nodeId) ?? doc3.roots[0] ?? nodeId;
  const ref = themeState.rootThemes?.[rootId] ?? themeState.defaultTheme;
  const definition = resolveThemeDefinition(ref, doc3.assets) ?? createDefaultThemeDefinition();
  const variant = resolveThemeVariant(definition, variantId);
  const base2 = toResolvedDocumentTheme(variantId, variant);
  const index = options.depthIndex ?? buildNodeDepthIndex(doc3);
  const depth = index.nodeDepthById[nodeId] ?? 0;
  const matchedRuleIds = [];
  const withRules = applyNodeRules(base2, variant.rules?.nodeRules, depth, matchedRuleIds);
  const rainbowEnabled = typeof themeState.rootRainbowEdges?.[rootId] === "boolean" ? Boolean(themeState.rootRainbowEdges[rootId]) : Boolean(themeState.rainbow?.enabled);
  const branchColor = resolveRainbowBranchColor(doc3, themeState, definition, rootId, nodeId, rainbowEnabled);
  const withRainbow = applyRainbow(withRules, branchColor);
  const override = themeState.overrides?.nodes?.[nodeId];
  const withOverride = override ? applyNodePatch(withRainbow, override) : withRainbow;
  const rootEdgeRoute = themeState.rootEdgeRoutes?.[rootId];
  const hasExplicitOverrideRouteType = typeof override?.incomingEdge?.routeType === "string" && override.incomingEdge.routeType.length > 0;
  const withRootEdgeRoute = rootEdgeRoute && nodeId !== rootId && !hasExplicitOverrideRouteType ? { ...withOverride, incomingEdge: { ...withOverride.incomingEdge ?? {}, routeType: rootEdgeRoute } } : withOverride;
  const edgeStyleScopes = themeState.edgeStyleScopes;
  const withEdgeStyleScope = (() => {
    if (!edgeStyleScopes) return withRootEdgeRoute;
    if (nodeId === rootId) return withRootEdgeRoute;
    const summaryById = new Map(doc3.summaries.map((summary) => [summary.id, summary]));
    const visitedNodes = /* @__PURE__ */ new Set();
    const visitedSummaries = /* @__PURE__ */ new Set();
    const resolveSummaryParentNodeId3 = (summaryId) => {
      let current2 = summaryId;
      while (current2) {
        if (visitedSummaries.has(current2)) return null;
        visitedSummaries.add(current2);
        const summary = summaryById.get(current2);
        if (!summary) return null;
        const parent = summary.parentId;
        if (typeof parent !== "string" || parent.length === 0) return null;
        if (doc3.nodes[parent]) return parent;
        if (summaryById.has(parent)) {
          current2 = parent;
          continue;
        }
        return null;
      }
      return null;
    };
    let dasharray;
    let strokeWidth;
    let current = nodeId;
    while (current) {
      if (visitedNodes.has(current)) break;
      visitedNodes.add(current);
      const scope = edgeStyleScopes[current];
      if (scope) {
        if (dasharray === void 0 && typeof scope.dasharray === "string" && scope.dasharray.trim().length > 0) {
          dasharray = scope.dasharray.trim();
        }
        if (strokeWidth === void 0 && typeof scope.strokeWidth === "number" && Number.isFinite(scope.strokeWidth)) {
          const value = Math.round(scope.strokeWidth * 10) / 10;
          strokeWidth = Math.max(0.5, Math.min(12, value));
        }
      }
      if (dasharray !== void 0 && strokeWidth !== void 0) break;
      if (current === rootId) break;
      const node = doc3.nodes[current];
      if (!node) break;
      if (node.parentId && typeof node.parentId === "string" && doc3.nodes[node.parentId]) {
        current = node.parentId;
        continue;
      }
      if (node.parentSummaryId) {
        current = resolveSummaryParentNodeId3(node.parentSummaryId);
        continue;
      }
      break;
    }
    if (dasharray === void 0 && strokeWidth === void 0) return withRootEdgeRoute;
    const nextIncoming = { ...withRootEdgeRoute.incomingEdge ?? {} };
    if (dasharray !== void 0 && nextIncoming.dasharray === void 0) nextIncoming.dasharray = dasharray;
    if (strokeWidth !== void 0 && nextIncoming.strokeWidth === void 0) nextIncoming.strokeWidth = strokeWidth;
    return { ...withRootEdgeRoute, incomingEdge: nextIncoming };
  })();
  const incomingEdgeRule = withEdgeStyleScope.incomingEdge;
  const incomingEdgeOverride = themeState.overrides?.edges?.[nodeId];
  const incomingEdge = mergeIncomingEdge(incomingEdgeRule, incomingEdgeOverride);
  const result = {
    ...withEdgeStyleScope,
    incomingEdge
  };
  if (options.debug) {
    result.debug = { depth, matchedRuleIds };
  }
  return result;
}
function resolveNodeThemes(doc3, env = {}, options = {}) {
  const assets = doc3.assets ?? {};
  const fallbackDefinition = createDefaultThemeDefinition();
  const fallbackThemeState = createDefaultDocumentThemeState({ source: "inline", value: fallbackDefinition });
  const themeState = normalizeThemeState(doc3.theme, assets) ?? fallbackThemeState;
  const variantId = resolveThemeVariantId(themeState.appearance, env);
  const depthIndex = options.depthIndex ?? buildNodeDepthIndex(doc3);
  const summaryById = /* @__PURE__ */ new Map();
  for (const summary of doc3.summaries) summaryById.set(summary.id, summary);
  const summaryParentNodeIdMemo = /* @__PURE__ */ new Map();
  const resolveSummaryParentNodeIdCached = (summaryId) => {
    const existing = summaryParentNodeIdMemo.get(summaryId);
    if (existing !== void 0) return existing;
    const visited = [];
    const seen = /* @__PURE__ */ new Set();
    let current = summaryId;
    let resolved = null;
    while (current) {
      if (seen.has(current)) {
        resolved = null;
        break;
      }
      seen.add(current);
      visited.push(current);
      const summary = summaryById.get(current);
      if (!summary) break;
      const parentId = summary.parentId;
      if (typeof parentId !== "string" || parentId.length === 0) break;
      if (doc3.nodes[parentId]) {
        resolved = parentId;
        break;
      }
      if (summaryById.has(parentId)) {
        current = parentId;
        continue;
      }
      break;
    }
    for (const id of visited) summaryParentNodeIdMemo.set(id, resolved);
    return resolved;
  };
  const parentNodeIdByNodeId = /* @__PURE__ */ new Map();
  for (const [nodeId, node] of Object.entries(doc3.nodes)) {
    const parentId = node.parentId;
    if (parentId && typeof parentId === "string" && doc3.nodes[parentId]) {
      parentNodeIdByNodeId.set(nodeId, parentId);
      continue;
    }
    const parentSummaryId = node.parentSummaryId;
    if (parentSummaryId && typeof parentSummaryId === "string" && summaryById.has(parentSummaryId)) {
      parentNodeIdByNodeId.set(nodeId, resolveSummaryParentNodeIdCached(parentSummaryId));
      continue;
    }
    parentNodeIdByNodeId.set(nodeId, null);
  }
  const rootIdMemo = /* @__PURE__ */ new Map();
  const resolveRootIdCached = (nodeId) => {
    const cached = rootIdMemo.get(nodeId);
    if (cached !== void 0) return cached;
    const path2 = [];
    const visited = /* @__PURE__ */ new Set();
    let current = nodeId;
    while (current) {
      if (visited.has(current)) {
        for (const id of path2) rootIdMemo.set(id, null);
        rootIdMemo.set(nodeId, null);
        return null;
      }
      visited.add(current);
      path2.push(current);
      const parent = parentNodeIdByNodeId.get(current) ?? null;
      if (!parent) {
        for (const id of path2) rootIdMemo.set(id, current);
        return current;
      }
      const parentCached = rootIdMemo.get(parent);
      if (parentCached !== void 0) {
        for (const id of path2) rootIdMemo.set(id, parentCached);
        return parentCached;
      }
      current = parent;
    }
    for (const id of path2) rootIdMemo.set(id, null);
    return null;
  };
  const rootIdByNodeId = {};
  const defaultRootId = doc3.roots[0];
  for (const nodeId of Object.keys(doc3.nodes)) {
    const resolved = resolveRootIdCached(nodeId);
    rootIdByNodeId[nodeId] = resolved ?? defaultRootId ?? nodeId;
  }
  const branchIdMemo = /* @__PURE__ */ new Map();
  const resolveBranchIdCached = (nodeId) => {
    const existing = branchIdMemo.get(nodeId);
    if (existing !== void 0) return existing;
    const rootId = rootIdByNodeId[nodeId] ?? defaultRootId ?? nodeId;
    if (nodeId === rootId) {
      branchIdMemo.set(nodeId, null);
      return null;
    }
    const visited = /* @__PURE__ */ new Set();
    let current = nodeId;
    while (current) {
      if (visited.has(current)) {
        branchIdMemo.set(nodeId, null);
        return null;
      }
      visited.add(current);
      const parent = parentNodeIdByNodeId.get(current) ?? null;
      if (!parent) break;
      if (parent === rootId) {
        branchIdMemo.set(nodeId, current);
        return current;
      }
      current = parent;
    }
    branchIdMemo.set(nodeId, null);
    return null;
  };
  const edgeStyleScopes = themeState.edgeStyleScopes;
  const edgeStyleMemo = /* @__PURE__ */ new Map();
  const resolveEdgeStyleCached = (nodeId) => {
    if (!edgeStyleScopes) return null;
    const existing = edgeStyleMemo.get(nodeId);
    if (existing !== void 0) return existing;
    const scope = edgeStyleScopes[nodeId];
    const parent = parentNodeIdByNodeId.get(nodeId) ?? null;
    const inherited = parent ? resolveEdgeStyleCached(parent) : null;
    const dasharray = (() => {
      if (typeof scope?.dasharray === "string" && scope.dasharray.trim().length > 0) return scope.dasharray.trim();
      return inherited?.dasharray;
    })();
    const strokeWidth = (() => {
      if (typeof scope?.strokeWidth === "number" && Number.isFinite(scope.strokeWidth)) {
        const value = Math.round(scope.strokeWidth * 10) / 10;
        return Math.max(0.5, Math.min(12, value));
      }
      return inherited?.strokeWidth;
    })();
    const next = dasharray === void 0 && strokeWidth === void 0 ? null : { dasharray, strokeWidth };
    edgeStyleMemo.set(nodeId, next);
    return next;
  };
  const rootCtxById = /* @__PURE__ */ new Map();
  const resolveRootCtx = (rootId) => {
    const cached = rootCtxById.get(rootId);
    if (cached) return cached;
    const ref = themeState.rootThemes?.[rootId] ?? themeState.defaultTheme;
    const definition = resolveThemeDefinition(ref, doc3.assets) ?? fallbackDefinition;
    const variant = resolveThemeVariant(definition, variantId);
    const base2 = toResolvedDocumentTheme(variantId, variant);
    const sortedNodeRules = variant.rules?.nodeRules ? [...variant.rules.nodeRules].sort((a2, b2) => (a2.priority ?? 0) - (b2.priority ?? 0)) : void 0;
    const rainbowEnabled = typeof themeState.rootRainbowEdges?.[rootId] === "boolean" ? Boolean(themeState.rootRainbowEdges[rootId]) : Boolean(themeState.rainbow?.enabled);
    const branchIndexById = /* @__PURE__ */ new Map();
    const root = doc3.nodes[rootId];
    if (root) {
      for (const [index, id] of root.children.entries()) {
        branchIndexById.set(id, index);
      }
    }
    const ctx = {
      base: base2,
      sortedNodeRules,
      definition,
      rootId,
      rainbowEnabled,
      branchIndexById
    };
    rootCtxById.set(rootId, ctx);
    return ctx;
  };
  const result = {};
  for (const nodeId of Object.keys(doc3.nodes)) {
    const rootId = rootIdByNodeId[nodeId] ?? defaultRootId ?? nodeId;
    const ctx = resolveRootCtx(rootId);
    const base2 = ctx.base;
    const depth = depthIndex.nodeDepthById[nodeId] ?? 0;
    const matchedRuleIds = options.debug ? [] : null;
    const withRules = (() => {
      const rules = ctx.sortedNodeRules;
      if (!rules || rules.length === 0) return base2;
      let current = base2;
      for (const rule of rules) {
        if (!rule || typeof rule !== "object") continue;
        if (!matchesSelector(rule.when, depth)) continue;
        if (matchedRuleIds) matchedRuleIds.push(rule.id);
        current = applyNodePatch(current, rule.apply);
      }
      return current;
    })();
    const withRainbow = (() => {
      if (!ctx.rainbowEnabled) return withRules;
      const branchId = resolveBranchIdCached(nodeId);
      if (!branchId) return withRules;
      const palette = themeState.rainbow?.paletteOverride ?? ctx.definition.variants.light?.rainbow?.palette ?? DEFAULT_RAINBOW_PALETTE;
      const branchColors = themeState.rainbow?.branchColors ?? {};
      const existing = branchColors[branchId];
      if (existing) return applyRainbow(withRules, existing);
      const branchIndex = ctx.branchIndexById.get(branchId);
      if (branchIndex !== void 0) {
        const usable = palette.length > 0 ? palette : DEFAULT_RAINBOW_PALETTE;
        const color = usable[branchIndex % usable.length] ?? usable[0] ?? "#3b82f6";
        return applyRainbow(withRules, color);
      }
      return applyRainbow(withRules, pickNextRainbowColor(branchColors, palette));
    })();
    const override = themeState.overrides?.nodes?.[nodeId];
    const withOverride = override ? applyNodePatch(withRainbow, override) : withRainbow;
    const rootEdgeRoute = themeState.rootEdgeRoutes?.[rootId];
    const hasExplicitOverrideRouteType = typeof override?.incomingEdge?.routeType === "string" && override.incomingEdge.routeType.length > 0;
    const withRootEdgeRoute = rootEdgeRoute && nodeId !== rootId && !hasExplicitOverrideRouteType ? { ...withOverride, incomingEdge: { ...withOverride.incomingEdge ?? {}, routeType: rootEdgeRoute } } : withOverride;
    const withEdgeStyleScope = (() => {
      if (!edgeStyleScopes) return withRootEdgeRoute;
      if (nodeId === rootId) return withRootEdgeRoute;
      const inherited = resolveEdgeStyleCached(nodeId);
      if (!inherited) return withRootEdgeRoute;
      const nextIncoming = { ...withRootEdgeRoute.incomingEdge ?? {} };
      if (inherited.dasharray !== void 0 && nextIncoming.dasharray === void 0) nextIncoming.dasharray = inherited.dasharray;
      if (inherited.strokeWidth !== void 0 && nextIncoming.strokeWidth === void 0) nextIncoming.strokeWidth = inherited.strokeWidth;
      return { ...withRootEdgeRoute, incomingEdge: nextIncoming };
    })();
    const incomingEdgeRule = withEdgeStyleScope.incomingEdge;
    const incomingEdgeOverride = themeState.overrides?.edges?.[nodeId];
    const incomingEdge = mergeIncomingEdge(incomingEdgeRule, incomingEdgeOverride);
    const resolved = {
      ...withEdgeStyleScope,
      incomingEdge
    };
    if (options.debug) {
      resolved.debug = { depth, matchedRuleIds: matchedRuleIds ?? [] };
    }
    result[nodeId] = resolved;
  }
  return result;
}
function getNodeRootId(doc3, nodeId) {
  const summaryById = new Map(doc3.summaries.map((summary) => [summary.id, summary]));
  const visitedNodes = /* @__PURE__ */ new Set();
  const visitedSummaries = /* @__PURE__ */ new Set();
  const resolveSummaryParent = (summaryId) => {
    if (visitedSummaries.has(summaryId)) return null;
    visitedSummaries.add(summaryId);
    const summary = summaryById.get(summaryId);
    if (!summary) return null;
    const parentId = summary.parentId;
    if (typeof parentId !== "string") return null;
    if (doc3.nodes[parentId]) return parentId;
    if (summaryById.has(parentId)) return resolveSummaryParent(parentId);
    return null;
  };
  let current = nodeId;
  while (current) {
    if (visitedNodes.has(current)) return null;
    visitedNodes.add(current);
    const node = doc3.nodes[current];
    if (!node) return null;
    if (!node.parentId && !node.parentSummaryId) return current;
    if (node.parentId) {
      current = node.parentId;
      continue;
    }
    if (node.parentSummaryId) {
      const parent = resolveSummaryParent(node.parentSummaryId);
      if (!parent) return null;
      current = parent;
      continue;
    }
    return null;
  }
  return null;
}
function getNodeBranchId(doc3, nodeId) {
  const rootId = getNodeRootId(doc3, nodeId);
  if (!rootId) return null;
  if (rootId === nodeId) return null;
  const visited = /* @__PURE__ */ new Set();
  let current = nodeId;
  while (true) {
    if (visited.has(current)) return null;
    visited.add(current);
    const node = doc3.nodes[current];
    if (!node) return null;
    const parentNodeId = node.parentId ?? (node.parentSummaryId ? resolveSummaryParentNodeId(doc3.summaries, node.parentSummaryId, /* @__PURE__ */ new Set()) : null);
    if (!parentNodeId) return null;
    if (parentNodeId === rootId) return current;
    current = parentNodeId;
  }
}
function ensureRainbowBranchColor(theme, branchId, palette = DEFAULT_RAINBOW_PALETTE) {
  const rainbow = theme.rainbow ?? { enabled: false, branchColors: {}, paletteOverride: void 0 };
  const branchColors = { ...rainbow.branchColors ?? {} };
  if (branchColors[branchId]) return theme;
  branchColors[branchId] = pickNextRainbowColor(branchColors, palette);
  return { ...theme, rainbow: { ...rainbow, branchColors } };
}
function pickNextRainbowColor(existing, palette) {
  const usable = palette.length > 0 ? palette : DEFAULT_RAINBOW_PALETTE;
  const used = new Set(Object.values(existing));
  for (const color of usable) {
    if (!used.has(color)) return color;
  }
  const index = Object.keys(existing).length % usable.length;
  return usable[index] ?? "#3b82f6";
}
function normalizeThemeState(raw, assets) {
  if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null;
  const schemaVersion = raw.schemaVersion;
  if (schemaVersion !== 1) return null;
  const defaultTheme2 = normalizeThemeRef(raw.defaultTheme, assets);
  if (!defaultTheme2) return null;
  const rootThemesRaw = raw.rootThemes;
  const rootThemes = rootThemesRaw && typeof rootThemesRaw === "object" && !Array.isArray(rootThemesRaw) ? Object.fromEntries(
    Object.entries(rootThemesRaw).map(([id, value]) => [id, normalizeThemeRef(value, assets)]).filter((entry) => Boolean(entry[1]))
  ) : void 0;
  const rootEdgeRoutesRaw = raw.rootEdgeRoutes;
  const rootEdgeRoutes = rootEdgeRoutesRaw && typeof rootEdgeRoutesRaw === "object" && !Array.isArray(rootEdgeRoutesRaw) ? Object.fromEntries(
    Object.entries(rootEdgeRoutesRaw).filter((entry) => {
      const value = entry[1];
      return typeof value === "string" && EDGE_ROUTE_TYPES.has(value);
    })
  ) : void 0;
  const rootRainbowEdgesRaw = raw.rootRainbowEdges;
  const rootRainbowEdges = rootRainbowEdgesRaw && typeof rootRainbowEdgesRaw === "object" && !Array.isArray(rootRainbowEdgesRaw) ? Object.fromEntries(
    Object.entries(rootRainbowEdgesRaw).filter((entry) => typeof entry[1] === "boolean")
  ) : void 0;
  const edgeStyleScopesRaw = raw.edgeStyleScopes;
  const edgeStyleScopes = edgeStyleScopesRaw && typeof edgeStyleScopesRaw === "object" && !Array.isArray(edgeStyleScopesRaw) ? Object.fromEntries(
    Object.entries(edgeStyleScopesRaw).map(([id, value]) => {
      if (!value || typeof value !== "object" || Array.isArray(value)) return [id, null];
      const input = value;
      const dasharrayRaw = input.dasharray;
      const strokeWidthRaw = input.strokeWidth;
      const dasharray = typeof dasharrayRaw === "string" && dasharrayRaw.trim().length > 0 ? dasharrayRaw.trim() : void 0;
      const strokeWidth = typeof strokeWidthRaw === "number" && Number.isFinite(strokeWidthRaw) ? Math.max(0.5, Math.min(12, Math.round(strokeWidthRaw * 10) / 10)) : void 0;
      const next = {};
      if (dasharray) next.dasharray = dasharray;
      if (strokeWidth !== void 0) next.strokeWidth = strokeWidth;
      return [id, Object.keys(next).length > 0 ? next : null];
    }).filter((entry) => {
      const value = entry[1];
      if (!value) return false;
      return Object.keys(value).length > 0;
    })
  ) : void 0;
  const relationStyle = normalizeThemeRelationOverride(raw.relationStyle);
  const rootRelationStylesRaw = raw.rootRelationStyles;
  const rootRelationStyles = rootRelationStylesRaw && typeof rootRelationStylesRaw === "object" && !Array.isArray(rootRelationStylesRaw) ? Object.fromEntries(
    Object.entries(rootRelationStylesRaw).map(([id, value]) => [id, normalizeThemeRelationOverride(value)]).filter((entry) => Boolean(entry[1]))
  ) : void 0;
  const rainbowRaw = raw.rainbow;
  const rainbow = rainbowRaw && typeof rainbowRaw === "object" && !Array.isArray(rainbowRaw) ? normalizeRainbowState(rainbowRaw) : void 0;
  const appearance = normalizeAppearancePolicy(raw.appearance);
  const overridesRaw = raw.overrides;
  const overrides = overridesRaw && typeof overridesRaw === "object" && !Array.isArray(overridesRaw) ? normalizeOverrides(overridesRaw) : void 0;
  return {
    schemaVersion: 1,
    defaultTheme: defaultTheme2,
    rootThemes: rootThemes && Object.keys(rootThemes).length > 0 ? rootThemes : void 0,
    rootEdgeRoutes: rootEdgeRoutes && Object.keys(rootEdgeRoutes).length > 0 ? rootEdgeRoutes : void 0,
    rootRainbowEdges: rootRainbowEdges && Object.keys(rootRainbowEdges).length > 0 ? rootRainbowEdges : void 0,
    edgeStyleScopes: edgeStyleScopes && Object.keys(edgeStyleScopes).length > 0 ? edgeStyleScopes : void 0,
    relationStyle,
    rootRelationStyles: rootRelationStyles && Object.keys(rootRelationStyles).length > 0 ? rootRelationStyles : void 0,
    rainbow,
    appearance,
    overrides
  };
}
function toResolvedDocumentTheme(variantId, variant) {
  const layout = variant.tokens.layout;
  const shape = variant.nodeShape;
  return {
    variantId,
    layout,
    paint: variant.tokens.paint,
    background: variant.background,
    edges: variant.edges,
    relations: variant.relations,
    nodeShape: shape,
    rainbow: variant.rainbow,
    layoutFingerprint: computeLayoutFingerprint(layout, shape)
  };
}
function applyNodeRules(base2, rules, depth, matchedRuleIds) {
  if (!rules || rules.length === 0) return base2;
  const sorted = [...rules].sort((a2, b2) => (a2.priority ?? 0) - (b2.priority ?? 0));
  let current = base2;
  for (const rule of sorted) {
    if (!rule || typeof rule !== "object") continue;
    if (!matchesSelector(rule.when, depth)) continue;
    matchedRuleIds.push(rule.id);
    current = applyNodePatch(current, rule.apply);
  }
  return current;
}
function matchesSelector(selector, depth) {
  if (!selector || typeof selector !== "object") return false;
  if (selector.kind === "depth") return Number.isFinite(selector.depth) && depth === selector.depth;
  if (selector.kind === "depthRange") {
    const min = typeof selector.minDepth === "number" && Number.isFinite(selector.minDepth) ? selector.minDepth : -Infinity;
    const max = typeof selector.maxDepth === "number" && Number.isFinite(selector.maxDepth) ? selector.maxDepth : Infinity;
    return depth >= min && depth <= max;
  }
  if (selector.kind === "and") return selector.all.every((item) => matchesSelector(item, depth));
  if (selector.kind === "or") return selector.any.some((item) => matchesSelector(item, depth));
  if (selector.kind === "not") return !matchesSelector(selector.selector, depth);
  return false;
}
function applyRainbow(theme, branchColor) {
  if (!branchColor) return theme;
  return {
    ...theme,
    paint: {
      ...theme.paint,
      nodeStroke: branchColor,
      edgeStroke: branchColor
    },
    incomingEdge: {
      ...theme.incomingEdge ?? {},
      strokeColor: branchColor
    }
  };
}
function applyNodePatch(theme, patch) {
  const nextLayout = patch.layout ? { ...theme.layout, ...patch.layout } : theme.layout;
  const nextPaint = patch.paint ? { ...theme.paint, ...patch.paint } : theme.paint;
  const nextShape = patch.nodeShape ? { ...theme.nodeShape ?? { type: "rounded-rect", radius: 10 }, ...patch.nodeShape } : theme.nodeShape;
  const nextIncomingEdge = patch.incomingEdge ? { ...theme.incomingEdge ?? {}, ...patch.incomingEdge } : theme.incomingEdge;
  return {
    ...theme,
    layout: nextLayout,
    paint: nextPaint,
    nodeShape: nextShape,
    incomingEdge: nextIncomingEdge,
    layoutFingerprint: computeLayoutFingerprint(nextLayout, nextShape)
  };
}
function mergeIncomingEdge(rule, override) {
  if (!rule && !override) return void 0;
  return {
    ...rule ?? {},
    ...override ?? {}
  };
}
function resolveRainbowBranchColor(doc3, themeState, themeDefinition, rootId, nodeId, rainbowEnabled) {
  if (!rainbowEnabled) return void 0;
  const branchId = getNodeBranchId(doc3, nodeId);
  if (!branchId) return void 0;
  const palette = themeState.rainbow?.paletteOverride ?? themeDefinition.variants.light?.rainbow?.palette ?? DEFAULT_RAINBOW_PALETTE;
  const branchColors = themeState.rainbow?.branchColors ?? {};
  if (branchColors[branchId]) return branchColors[branchId];
  const root = doc3.nodes[rootId];
  if (root) {
    const usable = palette.length > 0 ? palette : DEFAULT_RAINBOW_PALETTE;
    const branchIndex = root.children.indexOf(branchId);
    if (branchIndex >= 0 && usable.length > 0) {
      return usable[branchIndex % usable.length] ?? usable[0] ?? "#3b82f6";
    }
  }
  return pickNextRainbowColor(branchColors, palette);
}
function parseTimeToMinutes(value) {
  if (typeof value !== "string") return null;
  const match = value.trim().match(/^(\d{1,2}):(\d{2})$/);
  if (!match) return null;
  const hours = Number(match[1]);
  const minutes = Number(match[2]);
  if (!Number.isFinite(hours) || !Number.isFinite(minutes)) return null;
  if (hours < 0 || hours > 23) return null;
  if (minutes < 0 || minutes > 59) return null;
  return hours * 60 + minutes;
}
function normalizeThemeRef(raw, assets) {
  if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null;
  const source = raw.source;
  if (source === "inline") {
    const value = raw.value;
    if (isThemeDefinition(value)) return { source: "inline", value };
    return null;
  }
  if (source === "asset") {
    const assetId = raw.assetId;
    if (typeof assetId !== "string") return null;
    const asset = assets[assetId];
    if (asset && asset.kind === "json" && isThemeDefinition(asset.data)) {
      return { source: "asset", assetId };
    }
    return { source: "asset", assetId };
  }
  if (source === "remote") {
    const themeId = raw.themeId;
    const version2 = raw.version;
    if (typeof themeId !== "string" || themeId.length === 0) return null;
    return { source: "remote", themeId, version: typeof version2 === "string" ? version2 : void 0 };
  }
  return null;
}
function normalizeAppearancePolicy(raw) {
  if (!raw || typeof raw !== "object" || Array.isArray(raw)) return void 0;
  const mode = raw.mode;
  if (mode === "fixed") {
    const fixed = raw.fixed;
    if (fixed === "dark" || fixed === "light") return { mode: "fixed", fixed };
    return void 0;
  }
  if (mode === "system") return { mode: "system" };
  if (mode === "time") {
    const time = raw.time;
    if (!time || typeof time !== "object" || Array.isArray(time)) return void 0;
    const lightAt = time.lightAt;
    const darkAt = time.darkAt;
    const timezone = time.timezone;
    if (typeof lightAt !== "string" || typeof darkAt !== "string") return void 0;
    return {
      mode: "time",
      time: {
        lightAt,
        darkAt,
        timezone: timezone === "utc" ? "utc" : "local"
      }
    };
  }
  if (mode === "external") {
    const external = raw.external;
    if (!external || typeof external !== "object" || Array.isArray(external)) return void 0;
    const key = external.key;
    if (typeof key !== "string" || key.length === 0) return void 0;
    return { mode: "external", external: { key } };
  }
  return void 0;
}
function normalizeRainbowState(raw) {
  const enabled = Boolean(raw.enabled);
  const branchColors = normalizeStringRecord(raw.branchColors);
  const paletteOverride = normalizeStringArray(raw.paletteOverride);
  return {
    enabled,
    branchColors,
    paletteOverride
  };
}
function normalizeOverrides(raw) {
  const nodesRaw = raw.nodes;
  const edgesRaw = raw.edges;
  const relationsRaw = raw.relations;
  const summariesRaw = raw.summaries;
  const nodes = nodesRaw && typeof nodesRaw === "object" && !Array.isArray(nodesRaw) ? normalizeRecord(nodesRaw, normalizeNodeStylePatch) : void 0;
  const edges = edgesRaw && typeof edgesRaw === "object" && !Array.isArray(edgesRaw) ? normalizeRecord(edgesRaw, normalizeEdgeOverride) : void 0;
  const relations = relationsRaw && typeof relationsRaw === "object" && !Array.isArray(relationsRaw) ? normalizeRecord(relationsRaw, normalizeRelationOverride) : void 0;
  const summaries = summariesRaw && typeof summariesRaw === "object" && !Array.isArray(summariesRaw) ? normalizeRecord(summariesRaw, normalizeSummaryOverride) : void 0;
  if (!nodes && !edges && !relations && !summaries) return void 0;
  return {
    nodes,
    edges,
    relations,
    summaries
  };
}
function normalizeNodeStylePatch(raw) {
  if (!raw || typeof raw !== "object" || Array.isArray(raw)) return void 0;
  const layout = normalizeObject(raw, "layout");
  const paint = normalizeObject(raw, "paint");
  const nodeShape = normalizeObject(raw, "nodeShape");
  const incomingEdge = normalizeObject(raw, "incomingEdge");
  const patch = {};
  if (layout) patch.layout = layout;
  if (paint) patch.paint = paint;
  if (nodeShape) patch.nodeShape = nodeShape;
  if (incomingEdge) patch.incomingEdge = incomingEdge;
  return Object.keys(patch).length > 0 ? patch : void 0;
}
function normalizeEdgeOverride(raw) {
  if (!raw || typeof raw !== "object" || Array.isArray(raw)) return void 0;
  const strokeColor = raw.strokeColor;
  const strokeWidth = raw.strokeWidth;
  const dasharray = raw.dasharray;
  const next = {};
  if (typeof strokeColor === "string") next.strokeColor = strokeColor;
  if (typeof strokeWidth === "number" && Number.isFinite(strokeWidth)) next.strokeWidth = strokeWidth;
  if (typeof dasharray === "string") next.dasharray = dasharray;
  return Object.keys(next).length > 0 ? next : void 0;
}
function normalizeRelationOverride(raw) {
  return normalizeThemeRelationOverride(raw);
}
function normalizeSummaryOverride(raw) {
  if (!raw || typeof raw !== "object" || Array.isArray(raw)) return void 0;
  const strokeColor = raw.strokeColor;
  const fill = raw.fill;
  const textColor = raw.textColor;
  const next = {};
  if (typeof strokeColor === "string") next.strokeColor = strokeColor;
  if (typeof fill === "string") next.fill = fill;
  if (typeof textColor === "string") next.textColor = textColor;
  return Object.keys(next).length > 0 ? next : void 0;
}
function normalizeObject(raw, key) {
  const value = raw && typeof raw === "object" && !Array.isArray(raw) ? raw[key] : void 0;
  if (!value || typeof value !== "object" || Array.isArray(value)) return void 0;
  return value;
}
function normalizeStringRecord(raw) {
  if (!raw || typeof raw !== "object" || Array.isArray(raw)) return void 0;
  const result = {};
  for (const [key, value] of Object.entries(raw)) {
    if (typeof value !== "string") continue;
    result[key] = value;
  }
  return Object.keys(result).length > 0 ? result : void 0;
}
function normalizeStringArray(raw) {
  if (!Array.isArray(raw)) return void 0;
  const result = raw.filter((item) => typeof item === "string");
  return result.length > 0 ? result : void 0;
}
function normalizeRecord(raw, normalizeValue) {
  const next = {};
  for (const [key, value] of Object.entries(raw)) {
    const normalized = normalizeValue(value);
    if (!normalized) continue;
    next[key] = normalized;
  }
  return Object.keys(next).length > 0 ? next : void 0;
}
function resolveSummaryParentNodeId(summaries, summaryId, visited) {
  if (visited.has(summaryId)) return null;
  visited.add(summaryId);
  const summary = summaries.find((item) => item.id === summaryId);
  if (!summary) return null;
  const parentId = summary.parentId;
  if (typeof parentId !== "string") return null;
  const parentSummary = summaries.find((item) => item.id === parentId);
  if (parentSummary) return resolveSummaryParentNodeId(summaries, parentId, visited);
  return parentId;
}
function isThemeDefinition(raw) {
  if (!raw || typeof raw !== "object" || Array.isArray(raw)) return false;
  if (raw.schemaVersion !== 1) return false;
  if (typeof raw.id !== "string") return false;
  if (typeof raw.name !== "string") return false;
  const variants = raw.variants;
  if (!variants || typeof variants !== "object" || Array.isArray(variants)) return false;
  return true;
}
var DEFAULT_THEME_ID, HOST_COLOR_SCHEME_EXTERNAL_KEY, EDGE_ROUTE_TYPES, DEFAULT_RAINBOW_PALETTE, NODE_BODY_CSS_VERSION;
var init_theme = __esm({
  "../core/src/theme.ts"() {
    "use strict";
    init_relations();
    DEFAULT_THEME_ID = "kmind-default";
    HOST_COLOR_SCHEME_EXTERNAL_KEY = "kmind.host.colorScheme";
    EDGE_ROUTE_TYPES = /* @__PURE__ */ new Set([
      "cubic",
      "quadratic",
      "straight",
      "orthogonal",
      "orthogonal-rounded",
      "tapered",
      "center-quadratic",
      "center-quadratic-tapered",
      "edge-lead-quadratic",
      "edge-lead-quadratic-tapered",
      "cubic-tail",
      "baseline-fork"
    ]);
    DEFAULT_RAINBOW_PALETTE = [
      "#ef4444",
      "#f97316",
      "#eab308",
      "#22c55e",
      "#06b6d4",
      "#3b82f6",
      "#8b5cf6",
      "#ec4899"
    ];
    NODE_BODY_CSS_VERSION = "node-body-v1";
  }
});

// ../core/src/root-positions.ts
function seedMissingRootPositions(args) {
  const { roots } = args;
  const existing = args.existing ?? {};
  const baseX = roots.map((id) => existing[id]).find((pos) => Boolean(pos))?.x ?? DEFAULT_ROOT_POSITION.x;
  const next = {};
  let lastY = null;
  for (const rootId of roots) {
    const current = existing[rootId];
    if (current) {
      next[rootId] = current;
      lastY = current.y;
      continue;
    }
    const y = lastY === null ? DEFAULT_ROOT_POSITION.y : lastY + DEFAULT_ROOT_GAP_Y;
    next[rootId] = { x: baseX, y };
    lastY = y;
  }
  return next;
}
var DEFAULT_ROOT_POSITION, DEFAULT_ROOT_GAP_Y;
var init_root_positions = __esm({
  "../core/src/root-positions.ts"() {
    "use strict";
    DEFAULT_ROOT_POSITION = { x: 120, y: 60 };
    DEFAULT_ROOT_GAP_Y = 260;
  }
});

// ../core/src/pos.ts
function assertValidPos(pos) {
  if (pos.length === 0) throw new Error("Invalid pos: empty string.");
  for (let i = 0; i < pos.length; i += 1) {
    const ch = pos[i];
    if (POS_INDEX[ch] === void 0) throw new Error(`Invalid pos: contains unsupported char "${ch}".`);
  }
}
function comparePos(a2, b2) {
  if (a2 === b2) return 0;
  return a2 < b2 ? -1 : 1;
}
function posBefore(pos) {
  assertValidPos(pos);
  const chars = pos.split("");
  for (let i = chars.length - 1; i >= 0; i -= 1) {
    const ch = chars[i];
    const idx = POS_INDEX[ch];
    if (idx === 0) continue;
    chars[i] = POS_ALPHABET[idx - 1];
    for (let j = i + 1; j < chars.length; j += 1) chars[j] = POS_MAX_CHAR;
    return chars.join("");
  }
  throw new Error("posBefore: cannot generate a key before the minimal pos.");
}
function posAfter(pos) {
  assertValidPos(pos);
  const last = pos[pos.length - 1];
  const idx = POS_INDEX[last];
  if (idx < POS_BASE - 1) {
    return `${pos.slice(0, -1)}${POS_ALPHABET[idx + 1]}`;
  }
  return `${pos}${POS_MID_CHAR}`;
}
function posBetweenFinite(left, right) {
  assertValidPos(left);
  assertValidPos(right);
  if (comparePos(left, right) >= 0) {
    throw new Error("posBetween: left must be < right.");
  }
  let prefix = "";
  let i = 0;
  while (true) {
    const lch = i < left.length ? left[i] : POS_MIN_CHAR;
    const rch = i < right.length ? right[i] : POS_MAX_CHAR;
    if (lch === rch) {
      prefix += lch;
      i += 1;
      continue;
    }
    const li = POS_INDEX[lch];
    const ri = POS_INDEX[rch];
    if (li === void 0 || ri === void 0) {
      throw new Error("posBetween: invalid input pos.");
    }
    if (ri - li > 1) {
      const mid = Math.ceil((li + ri) / 2);
      return `${prefix}${POS_ALPHABET[mid]}`;
    }
    prefix += lch;
    i += 1;
  }
}
function posBetween(left, right) {
  if (!left && !right) return "a0";
  if (!left && right) return posBefore(right);
  if (left && !right) return posAfter(left);
  return posBetweenFinite(left, right);
}
function pow(base2, exp) {
  let acc = 1;
  for (let i = 0; i < exp; i += 1) acc *= base2;
  return acc;
}
function encodeIndexFixedWidth(index, width) {
  let value = Math.max(0, Math.floor(index));
  const chars = new Array(width).fill(POS_MIN_CHAR);
  for (let i = width - 1; i >= 0; i -= 1) {
    chars[i] = POS_ALPHABET[value % POS_BASE];
    value = Math.floor(value / POS_BASE);
  }
  return chars.join("");
}
function renormalizePosList(count) {
  const n = Math.max(0, Math.floor(count));
  if (n === 0) return [];
  if (n === 1) return ["a0"];
  let width = 2;
  while (pow(POS_BASE, width) < n + 2) width += 1;
  const maxIndex = pow(POS_BASE, width) - 1;
  const start = Math.floor((maxIndex - (n - 1)) / 2);
  const result = [];
  for (let i = 0; i < n; i += 1) {
    result.push(encodeIndexFixedWidth(start + i, width));
  }
  return result;
}
var POS_ALPHABET, POS_BASE, POS_MIN_CHAR, POS_MAX_CHAR, POS_MID_CHAR, POS_INDEX;
var init_pos = __esm({
  "../core/src/pos.ts"() {
    "use strict";
    POS_ALPHABET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
    POS_BASE = POS_ALPHABET.length;
    POS_MIN_CHAR = POS_ALPHABET[0];
    POS_MAX_CHAR = POS_ALPHABET[POS_BASE - 1];
    POS_MID_CHAR = POS_ALPHABET[Math.ceil((0 + (POS_BASE - 1)) / 2)];
    POS_INDEX = Object.fromEntries(
      POS_ALPHABET.split("").map((ch, index) => [ch, index])
    );
  }
});

// ../core/src/node-content-width.ts
function isFinitePositiveNumber(value) {
  return typeof value === "number" && Number.isFinite(value) && value > 0;
}
function normalizeWidth(value) {
  return Math.round(value);
}
function normalizeOptionalWidth(value) {
  return isFinitePositiveNumber(value) ? normalizeWidth(value) : void 0;
}
function normalizeNodeContentWidth(contentWidth) {
  if (!contentWidth || typeof contentWidth !== "object" || Array.isArray(contentWidth)) return void 0;
  if (contentWidth.mode === "fixed") {
    const nextWidth = normalizeWidth(isFinitePositiveNumber(contentWidth.width) ? contentWidth.width : DEFAULT_NODE_CONTENT_WRAP_WIDTH);
    const restoreAutoWrapWidth = normalizeOptionalWidth(contentWidth.restoreAutoWrapWidth);
    return restoreAutoWrapWidth !== void 0 ? { mode: "fixed", width: nextWidth, restoreAutoWrapWidth } : { mode: "fixed", width: nextWidth };
  }
  if (contentWidth.mode === "auto") {
    return isFinitePositiveNumber(contentWidth.wrapWidth) ? { mode: "auto", wrapWidth: normalizeWidth(contentWidth.wrapWidth) } : { mode: "auto" };
  }
  return void 0;
}
function mirrorLegacyNodeContentWidth(contentWidth) {
  const normalized = normalizeNodeContentWidth(contentWidth);
  if (!normalized) return {};
  if (normalized.mode === "fixed") {
    return { maxWidth: normalized.width, contentWidthMode: "fixed" };
  }
  if (isFinitePositiveNumber(normalized.wrapWidth)) {
    return { maxWidth: normalized.wrapWidth, contentWidthMode: "auto" };
  }
  return {};
}
function resolveNodeAutoContentWidth(node) {
  const normalized = normalizeNodeContentWidth(node?.contentWidth);
  if (normalized?.mode === "auto") return normalized;
  if (normalized?.mode === "fixed") {
    return normalized.restoreAutoWrapWidth !== void 0 ? { mode: "auto", wrapWidth: normalized.restoreAutoWrapWidth } : { mode: "auto" };
  }
  const legacyWidth = normalizeOptionalWidth(node?.maxWidth);
  if (node?.contentWidthMode === "fixed") return { mode: "auto" };
  if (legacyWidth !== void 0) return { mode: "auto", wrapWidth: legacyWidth };
  return { mode: "auto" };
}
function resolveNodeFixedContentWidth(node, width, options) {
  const normalizedWidth = normalizeWidth(isFinitePositiveNumber(width) ? width : DEFAULT_NODE_CONTENT_WRAP_WIDTH);
  const preservedAutoWrapWidth = normalizeOptionalWidth(options?.restoreAutoWrapWidth) ?? normalizeOptionalWidth(resolveNodeAutoContentWidth(node).wrapWidth);
  return preservedAutoWrapWidth !== void 0 ? { mode: "fixed", width: normalizedWidth, restoreAutoWrapWidth: preservedAutoWrapWidth } : { mode: "fixed", width: normalizedWidth };
}
function applyNodeContentWidth(node, contentWidth) {
  const normalized = normalizeNodeContentWidth(contentWidth);
  const legacy = mirrorLegacyNodeContentWidth(normalized);
  return {
    ...node,
    contentWidth: normalized,
    maxWidth: legacy.maxWidth,
    contentWidthMode: legacy.contentWidthMode
  };
}
function resolveNodeContentWidth(node, options) {
  const defaultWrapWidth = isFinitePositiveNumber(options?.defaultWrapWidth) ? normalizeWidth(options.defaultWrapWidth) : DEFAULT_NODE_CONTENT_WRAP_WIDTH;
  const normalized = normalizeNodeContentWidth(node?.contentWidth);
  if (normalized) {
    if (normalized.mode === "fixed") return normalized;
    return {
      mode: "auto",
      wrapWidth: normalized.wrapWidth,
      width: isFinitePositiveNumber(normalized.wrapWidth) ? normalized.wrapWidth : defaultWrapWidth
    };
  }
  const legacyWidth = isFinitePositiveNumber(node?.maxWidth) ? normalizeWidth(node.maxWidth) : void 0;
  if (node?.contentWidthMode === "fixed") {
    return { mode: "fixed", width: legacyWidth ?? defaultWrapWidth };
  }
  return {
    mode: "auto",
    wrapWidth: legacyWidth,
    width: legacyWidth ?? defaultWrapWidth
  };
}
var DEFAULT_NODE_CONTENT_WRAP_WIDTH, MIN_NODE_CONTENT_WIDTH, MAX_NODE_CONTENT_WIDTH;
var init_node_content_width = __esm({
  "../core/src/node-content-width.ts"() {
    "use strict";
    DEFAULT_NODE_CONTENT_WRAP_WIDTH = 240;
    MIN_NODE_CONTENT_WIDTH = 60;
    MAX_NODE_CONTENT_WIDTH = 960;
  }
});

// ../core/src/document.ts
function createNode(id, options = {}) {
  const contentWidth = options.contentWidth ?? (options.contentWidthMode === "fixed" ? { mode: "fixed", width: options.maxWidth ?? 240 } : typeof options.maxWidth === "number" ? { mode: "auto", wrapWidth: options.maxWidth } : void 0);
  return applyNodeContentWidth({
    id,
    parentId: options.parentId,
    parentSummaryId: options.parentSummaryId,
    pos: options.pos,
    children: options.children ?? [],
    text: options.text ?? "",
    content: options.content,
    attrs: options.attrs,
    subMapId: options.subMapId,
    data: options.data,
    contentWidth: options.contentWidth,
    maxWidth: options.maxWidth,
    contentWidthMode: options.contentWidthMode,
    layout: options.layout,
    branchSide: options.branchSide
  }, contentWidth);
}
function createDocument(idGenerator, options = {}) {
  const rootId = idGenerator.generate("node");
  const rootNode = createNode(rootId, {
    text: options.rootText ?? "Root",
    contentWidth: { mode: "auto", wrapWidth: options.rootMaxWidth ?? 240 },
    pos: posBetween(null, null)
  });
  return {
    version: "1.0.0",
    roots: [rootId],
    rootPositions: {
      [rootId]: { ...DEFAULT_ROOT_POSITION }
    },
    nodes: {
      [rootId]: rootNode
    },
    summaries: [],
    relations: [],
    assets: {},
    theme: createDefaultDocumentThemeState({
      source: "inline",
      value: createDefaultThemeDefinition()
    })
  };
}
var init_document = __esm({
  "../core/src/document.ts"() {
    "use strict";
    init_theme();
    init_root_positions();
    init_pos();
    init_node_content_width();
  }
});

// ../core/src/summaries.ts
function buildSummariesByParent(doc3) {
  const map2 = /* @__PURE__ */ new Map();
  for (const summary of doc3.summaries) {
    const list = map2.get(summary.parentId);
    if (list) {
      list.push(summary);
    } else {
      map2.set(summary.parentId, [summary]);
    }
  }
  return map2;
}
function collectSubtreeIds(doc3, nodeId, summariesByParent) {
  const summaryById = new Map(doc3.summaries.map((summary) => [summary.id, summary]));
  const stack = [nodeId];
  const visited = /* @__PURE__ */ new Set();
  const result = [];
  while (stack.length > 0) {
    const current = stack.pop();
    if (!current) break;
    if (visited.has(current)) continue;
    visited.add(current);
    const node = doc3.nodes[current];
    if (node) {
      result.push(current);
      for (const childId of node.children) {
        stack.push(childId);
      }
    }
    const summaries = summariesByParent.get(current);
    if (summaries) {
      for (const summary2 of summaries) {
        stack.push(summary2.id);
        for (const childId of summary2.children) {
          stack.push(childId);
        }
      }
    }
    const summary = summaryById.get(current);
    if (summary) {
      for (const childId of summary.children) {
        stack.push(childId);
      }
    }
  }
  return result;
}
function sanitizeSummaries(args) {
  const nextNodes = { ...args.nodes };
  let nextRoots = [...args.roots];
  const originalById = new Map(args.originalSummaries.map((summary) => [summary.id, summary]));
  const summaryById = /* @__PURE__ */ new Map();
  for (const summary of args.summaries) {
    summaryById.set(summary.id, { ...summary, childIds: [...summary.childIds], children: [...summary.children] });
  }
  const resolvePromotionTarget = (parentId) => {
    let cursor = parentId;
    const visited = /* @__PURE__ */ new Set();
    while (cursor) {
      if (visited.has(cursor)) break;
      visited.add(cursor);
      if (nextNodes[cursor]) return { type: "node", id: cursor };
      if (summaryById.has(cursor)) return { type: "summary", id: cursor };
      const originalParent = originalById.get(cursor);
      if (!originalParent) break;
      cursor = originalParent.parentId;
    }
    return { type: "root" };
  };
  const resolveParentKind = (parentId) => {
    if (nextNodes[parentId]) return "node";
    if (summaryById.has(parentId) || originalById.has(parentId)) return "summary";
    return "missing";
  };
  const attachToTarget = (nodeId, target2) => {
    const node = nextNodes[nodeId];
    if (!node) return;
    if (target2.type === "root") {
      const baseRoots = nextRoots.filter((id) => id !== nodeId);
      const lastRootId = baseRoots[baseRoots.length - 1] ?? null;
      const lastPos2 = lastRootId ? nextNodes[lastRootId]?.pos ?? null : null;
      const nextPos2 = lastPos2 ? posBetween(lastPos2, null) : posBetween(null, null);
      nextNodes[nodeId] = { ...node, parentId: void 0, parentSummaryId: void 0, pos: nextPos2 };
      nextRoots = [...baseRoots, nodeId];
      return;
    }
    if (target2.type === "node") {
      const parent = nextNodes[target2.id];
      if (!parent) return;
      const baseChildren2 = parent.children.filter((id) => id !== nodeId);
      const lastSiblingId2 = baseChildren2[baseChildren2.length - 1] ?? null;
      const lastPos2 = lastSiblingId2 ? nextNodes[lastSiblingId2]?.pos ?? null : null;
      const nextPos2 = lastPos2 ? posBetween(lastPos2, null) : posBetween(null, null);
      nextNodes[nodeId] = { ...node, parentId: target2.id, parentSummaryId: void 0, pos: nextPos2 };
      nextNodes[target2.id] = { ...parent, children: [...baseChildren2, nodeId] };
      return;
    }
    const parentSummary = summaryById.get(target2.id);
    if (!parentSummary) {
      const baseRoots = nextRoots.filter((id) => id !== nodeId);
      const lastRootId = baseRoots[baseRoots.length - 1] ?? null;
      const lastPos2 = lastRootId ? nextNodes[lastRootId]?.pos ?? null : null;
      const nextPos2 = lastPos2 ? posBetween(lastPos2, null) : posBetween(null, null);
      nextNodes[nodeId] = { ...node, parentId: void 0, parentSummaryId: void 0, pos: nextPos2 };
      nextRoots = [...baseRoots, nodeId];
      return;
    }
    const baseChildren = parentSummary.children.filter((id) => id !== nodeId);
    const lastSiblingId = baseChildren[baseChildren.length - 1] ?? null;
    const lastPos = lastSiblingId ? nextNodes[lastSiblingId]?.pos ?? null : null;
    const nextPos = lastPos ? posBetween(lastPos, null) : posBetween(null, null);
    nextNodes[nodeId] = { ...node, parentId: void 0, parentSummaryId: target2.id, pos: nextPos };
    summaryById.set(target2.id, { ...parentSummary, children: [...baseChildren, nodeId] });
  };
  const normalizeSummaries = () => {
    for (const summary of summaryById.values()) {
      const parentKind = resolveParentKind(summary.parentId);
      summary.childIds = summary.childIds.filter((id) => {
        const child = nextNodes[id];
        if (!child) return false;
        if (parentKind === "node") return child.parentId === summary.parentId;
        if (parentKind === "summary") return child.parentSummaryId === summary.parentId;
        return false;
      });
      if (summary.childIds.length > 0) {
        const containerChildIds = (() => {
          if (parentKind === "node") {
            const parent = nextNodes[summary.parentId];
            if (!parent) return [];
            const resolveSide = (nodeId) => nextNodes[nodeId]?.branchSide === "left" ? "left" : "right";
            const validChildren = parent.children.filter((id) => {
              const child = nextNodes[id];
              if (!child) return false;
              return child.parentId === parent.id;
            });
            const layoutType = parent.layout ?? "logical-right";
            if (layoutType !== "mindmap-both" && layoutType !== "mindmap-both-auto") return validChildren;
            const selectedSides = new Set(summary.childIds.map((id) => resolveSide(id)));
            if (selectedSides.size !== 1) return validChildren;
            const targetSide = selectedSides.has("left") ? "left" : "right";
            return validChildren.filter((id) => resolveSide(id) === targetSide);
          }
          if (parentKind === "summary") {
            const parentSummary = summaryById.get(summary.parentId);
            return parentSummary ? parentSummary.children.filter((id) => {
              const child = nextNodes[id];
              if (!child) return false;
              return child.parentSummaryId === parentSummary.id;
            }) : [];
          }
          return [];
        })();
        const indexById = new Map(containerChildIds.map((id, index) => [id, index]));
        const startId = summary.childIds[0];
        const endId = summary.childIds[summary.childIds.length - 1];
        const startIndex = indexById.get(startId);
        const endIndex = indexById.get(endId);
        if (startIndex !== void 0 && endIndex !== void 0) {
          const rangeStart = Math.min(startIndex, endIndex);
          const rangeEnd = Math.max(startIndex, endIndex);
          summary.childIds = containerChildIds.slice(rangeStart, rangeEnd + 1);
        } else {
          const indices = summary.childIds.map((id) => indexById.get(id)).filter((index) => index !== void 0);
          if (indices.length > 0) {
            const rangeStart = Math.min(...indices);
            const rangeEnd = Math.max(...indices);
            summary.childIds = containerChildIds.slice(rangeStart, rangeEnd + 1);
          }
        }
      }
      summary.children = summary.children.filter((id) => {
        const child = nextNodes[id];
        if (!child) return false;
        return child.parentSummaryId === summary.id;
      });
    }
  };
  normalizeSummaries();
  let changed = true;
  while (changed) {
    changed = false;
    for (const summary of Array.from(summaryById.values())) {
      const parentExists = Boolean(nextNodes[summary.parentId]) || summaryById.has(summary.parentId);
      if (parentExists && summary.childIds.length > 0) continue;
      const target2 = resolvePromotionTarget(summary.parentId);
      for (const childId of summary.children) {
        attachToTarget(childId, target2);
      }
      summaryById.delete(summary.id);
      changed = true;
    }
    if (changed) normalizeSummaries();
  }
  nextRoots = Array.from(new Set(nextRoots)).filter((id) => Boolean(nextNodes[id]));
  nextRoots = nextRoots.filter((id) => {
    const node = nextNodes[id];
    if (!node) return false;
    return !node.parentId && !node.parentSummaryId;
  });
  return {
    nodes: pruneDanglingChildren(nextNodes),
    roots: nextRoots,
    summaries: Array.from(summaryById.values())
  };
}
function pruneDanglingChildren(nodes) {
  const next = {};
  for (const [id, node] of Object.entries(nodes)) {
    next[id] = { ...node, children: node.children.filter((childId) => Boolean(nodes[childId])) };
  }
  return next;
}
var init_summaries = __esm({
  "../core/src/summaries.ts"() {
    "use strict";
    init_pos();
  }
});

// ../core/src/tree.ts
function resolveParentKey(args) {
  const parentId = args.node.parentId;
  if (parentId && args.nodes[parentId]) return { key: `node:${parentId}`, normalizedParent: { parentId } };
  const parentSummaryId = args.node.parentSummaryId;
  if (parentSummaryId && args.summaryIdSet.has(parentSummaryId)) {
    return { key: `summary:${parentSummaryId}`, normalizedParent: { parentSummaryId } };
  }
  return { key: "root", normalizedParent: { parentId: void 0, parentSummaryId: void 0 } };
}
function comparePosThenId(a2, b2) {
  const ap = a2.pos;
  const bp = b2.pos;
  if (ap && bp && ap !== bp) return comparePos(ap, bp);
  if (!ap && bp) return 1;
  if (ap && !bp) return -1;
  return a2.id.localeCompare(b2.id);
}
function getHintOrder(args) {
  if (args.parentKey === "root") return Array.isArray(args.doc.roots) ? args.doc.roots : [];
  if (args.parentKey.startsWith("node:")) {
    const parentId = args.parentKey.slice("node:".length);
    const parent = args.doc.nodes[parentId];
    return parent ? parent.children : [];
  }
  const summaryId = args.parentKey.slice("summary:".length);
  const summary = args.summariesById.get(summaryId);
  return summary ? summary.children : [];
}
function getNodePos(node) {
  const raw = typeof node.pos === "string" ? node.pos.trim() : "";
  return raw.length > 0 ? raw : null;
}
function normalizeTree(doc3) {
  const summariesById = /* @__PURE__ */ new Map();
  for (const summary of doc3.summaries) summariesById.set(summary.id, summary);
  const summaryIdSet = new Set(summariesById.keys());
  const nextNodes = { ...doc3.nodes };
  let posChanged = false;
  let parentChanged = false;
  const idsByParent = /* @__PURE__ */ new Map();
  for (const [id, rawNode] of Object.entries(doc3.nodes)) {
    const { key, normalizedParent } = resolveParentKey({ node: rawNode, nodes: doc3.nodes, summaryIdSet });
    const list = idsByParent.get(key) ?? [];
    list.push(id);
    idsByParent.set(key, list);
    const wantsParentId = normalizedParent.parentId;
    const wantsParentSummaryId = normalizedParent.parentSummaryId;
    if (rawNode.parentId !== wantsParentId || rawNode.parentSummaryId !== wantsParentSummaryId) {
      parentChanged = true;
      nextNodes[id] = { ...rawNode, parentId: wantsParentId, parentSummaryId: wantsParentSummaryId };
    }
  }
  for (const [parentKey, childIds] of idsByParent.entries()) {
    if (childIds.length <= 1) {
      const id = childIds[0];
      if (!id) continue;
      const node = nextNodes[id];
      if (!node) continue;
      if (!getNodePos(node)) {
        posChanged = true;
        nextNodes[id] = { ...node, pos: posBetween(null, null) };
      }
      continue;
    }
    const hint = getHintOrder({ parentKey, doc: doc3, summariesById });
    const childIdSet = new Set(childIds);
    const used = /* @__PURE__ */ new Set();
    const ordered = [];
    for (const id of hint) {
      if (!childIdSet.has(id)) continue;
      if (used.has(id)) continue;
      ordered.push(id);
      used.add(id);
    }
    const remaining = childIds.filter((id) => !used.has(id)).map((id) => ({ id, pos: nextNodes[id] ? getNodePos(nextNodes[id]) : null })).sort(comparePosThenId).map((item) => item.id);
    ordered.push(...remaining);
    const needsRenormalize = childIds.some((id) => {
      const node = nextNodes[id];
      return !node || !getNodePos(node);
    });
    if (!needsRenormalize) continue;
    const positions = renormalizePosList(ordered.length);
    for (let i = 0; i < ordered.length; i += 1) {
      const id = ordered[i];
      const node = nextNodes[id];
      if (!node) continue;
      const nextPos = positions[i] ?? posBetween(null, null);
      if (node.pos === nextPos) continue;
      posChanged = true;
      nextNodes[id] = { ...node, pos: nextPos };
    }
  }
  const itemsByParent = /* @__PURE__ */ new Map();
  for (const [id, rawNode] of Object.entries(nextNodes)) {
    const { key } = resolveParentKey({ node: rawNode, nodes: nextNodes, summaryIdSet });
    const list = itemsByParent.get(key) ?? [];
    list.push({ id, pos: getNodePos(rawNode) });
    itemsByParent.set(key, list);
  }
  const normalizedNodes = {};
  for (const [id, node] of Object.entries(nextNodes)) {
    normalizedNodes[id] = { ...node, children: [] };
  }
  const normalizedSummaries = doc3.summaries.map((summary) => ({ ...summary, children: [] }));
  const normalizedSummariesById = new Map(normalizedSummaries.map((summary) => [summary.id, summary]));
  const roots = [];
  for (const [parentKey, items] of itemsByParent.entries()) {
    const ordered = [...items].sort(comparePosThenId).map((item) => item.id);
    if (parentKey === "root") {
      roots.push(...ordered);
      continue;
    }
    if (parentKey.startsWith("node:")) {
      const parentId = parentKey.slice("node:".length);
      const parent = normalizedNodes[parentId];
      if (parent) normalizedNodes[parentId] = { ...parent, children: ordered };
      continue;
    }
    const summaryId = parentKey.slice("summary:".length);
    const summary = normalizedSummariesById.get(summaryId);
    if (summary) normalizedSummariesById.set(summaryId, { ...summary, children: ordered });
  }
  const treeChanged = parentChanged || posChanged;
  if (!treeChanged) {
    return { ...doc3, roots, nodes: normalizedNodes, summaries: Array.from(normalizedSummariesById.values()) };
  }
  return { ...doc3, roots, nodes: normalizedNodes, summaries: Array.from(normalizedSummariesById.values()) };
}
var init_tree = __esm({
  "../core/src/tree.ts"() {
    "use strict";
    init_pos();
  }
});

// ../core/src/commands.ts
function pruneDanglingInternalLinks(nodes, deletedNodeIds) {
  let changed = false;
  const nextNodes = { ...nodes };
  for (const [nodeId, node] of Object.entries(nodes)) {
    const content = node.content;
    if (!content || content.schemaVersion !== 1) continue;
    if (content.kind !== "blocks") continue;
    let blocksChanged = false;
    const nextBlocks = content.blocks.map((block) => {
      if (block.type !== "links") return block;
      const nextLinks = block.links.filter((link) => {
        if (link.kind !== "internal") return true;
        const normalizedDocId = typeof link.docId === "string" ? link.docId.trim() : "";
        if (normalizedDocId.length > 0) return true;
        return !deletedNodeIds.has(link.nodeId);
      });
      if (nextLinks.length === block.links.length) return block;
      blocksChanged = true;
      return { ...block, links: nextLinks };
    });
    if (!blocksChanged) continue;
    changed = true;
    nextNodes[nodeId] = { ...node, content: { ...content, blocks: nextBlocks } };
  }
  return changed ? nextNodes : nodes;
}
function pruneDanglingInternalLinksInSummaries(summaries, deletedNodeIds) {
  let changed = false;
  const next = summaries.map((summary) => {
    const content = summary.content;
    if (!content || content.schemaVersion !== 1) return summary;
    if (content.kind !== "blocks") return summary;
    let blocksChanged = false;
    const nextBlocks = content.blocks.map((block) => {
      if (block.type !== "links") return block;
      const nextLinks = block.links.filter((link) => {
        if (link.kind !== "internal") return true;
        const normalizedDocId = typeof link.docId === "string" ? link.docId.trim() : "";
        if (normalizedDocId.length > 0) return true;
        return !deletedNodeIds.has(link.nodeId);
      });
      if (nextLinks.length === block.links.length) return block;
      blocksChanged = true;
      return { ...block, links: nextLinks };
    });
    if (!blocksChanged) return summary;
    changed = true;
    return { ...summary, content: { ...content, blocks: nextBlocks } };
  });
  return changed ? next : summaries;
}
function applyCommandImpl(doc3, command2, idGenerator) {
  switch (command2.type) {
    case "undo":
    case "redo": {
      return { doc: doc3, result: { ok: true } };
    }
    case "set_node_content": {
      const { nodeId, content, plainText, assets } = command2.payload;
      const node = doc3.nodes[nodeId];
      if (!node) {
        return { doc: doc3, result: { ok: false, error: `Node not found: ${nodeId}` } };
      }
      const nextNode = {
        ...node,
        content: content ?? void 0,
        text: plainText
      };
      const nextAssets = assets ? { ...doc3.assets ?? {}, ...assets } : doc3.assets;
      return {
        doc: {
          ...doc3,
          nodes: {
            ...doc3.nodes,
            [nodeId]: nextNode
          },
          assets: nextAssets
        },
        result: { ok: true }
      };
    }
    case "set_summary_content": {
      const { summaryId, content, plainText, assets } = command2.payload;
      const index = doc3.summaries.findIndex((summary2) => summary2.id === summaryId);
      if (index === -1) {
        return { doc: doc3, result: { ok: false, error: `Summary not found: ${summaryId}` } };
      }
      const nextSummaries = [...doc3.summaries];
      const summary = nextSummaries[index];
      nextSummaries[index] = { ...summary, content: content ?? void 0, text: plainText };
      const nextAssets = assets ? { ...doc3.assets ?? {}, ...assets } : doc3.assets;
      return {
        doc: {
          ...doc3,
          summaries: nextSummaries,
          assets: nextAssets
        },
        result: { ok: true }
      };
    }
    case "set_node_attrs": {
      const { nodeId, attrs } = command2.payload;
      const node = doc3.nodes[nodeId];
      if (!node) {
        return { doc: doc3, result: { ok: false, error: `Node not found: ${nodeId}` } };
      }
      const nextNode = {
        ...node,
        attrs: attrs ?? void 0
      };
      return {
        doc: {
          ...doc3,
          nodes: {
            ...doc3.nodes,
            [nodeId]: nextNode
          }
        },
        result: { ok: true }
      };
    }
    case "set_node_data": {
      const { nodeId, data } = command2.payload;
      const node = doc3.nodes[nodeId];
      if (!node) {
        return { doc: doc3, result: { ok: false, error: `Node not found: ${nodeId}` } };
      }
      const nextNode = {
        ...node,
        data: data ?? void 0
      };
      return {
        doc: {
          ...doc3,
          nodes: {
            ...doc3.nodes,
            [nodeId]: nextNode
          }
        },
        result: { ok: true }
      };
    }
    case "set_node_submap": {
      const { nodeId, subMapId } = command2.payload;
      const node = doc3.nodes[nodeId];
      if (!node) {
        return { doc: doc3, result: { ok: false, error: `Node not found: ${nodeId}` } };
      }
      const nextNode = {
        ...node,
        subMapId: subMapId ?? void 0
      };
      return {
        doc: {
          ...doc3,
          nodes: {
            ...doc3.nodes,
            [nodeId]: nextNode
          }
        },
        result: { ok: true }
      };
    }
    case "set_node_content_width": {
      const { nodeId, contentWidth, width, mode } = command2.payload;
      const node = doc3.nodes[nodeId];
      if (!node) {
        return { doc: doc3, result: { ok: false, error: `Node not found: ${nodeId}` } };
      }
      const nextContentWidth = (() => {
        if (contentWidth !== void 0) {
          if (contentWidth === null) return null;
          const normalized = normalizeNodeContentWidth(contentWidth);
          if (!normalized) return null;
          if (normalized.mode === "fixed") {
            return resolveNodeFixedContentWidth(node, normalized.width, {
              restoreAutoWrapWidth: normalized.restoreAutoWrapWidth
            });
          }
          if (normalized.wrapWidth !== void 0) {
            return normalized;
          }
          return resolveNodeAutoContentWidth(node);
        }
        if (mode === null) return null;
        if (mode === "fixed") {
          const nextWidth = typeof width === "number" && Number.isFinite(width) ? Math.round(width) : resolveNodeContentWidth(node).width;
          return resolveNodeFixedContentWidth(node, nextWidth);
        }
        if (mode === "auto") {
          if (typeof width === "number" && Number.isFinite(width)) {
            return { mode: "auto", wrapWidth: Math.round(width) };
          }
          return resolveNodeAutoContentWidth(node);
        }
        if (typeof width === "number" && Number.isFinite(width)) {
          const current = resolveNodeContentWidth(node);
          if (current.mode === "fixed") {
            return resolveNodeFixedContentWidth(node, Math.round(width));
          }
          return { mode: "auto", wrapWidth: Math.round(width) };
        }
        if (width === null) return null;
        return normalizeNodeContentWidth(node.contentWidth) ?? null;
      })();
      const nextNode = applyNodeContentWidth(node, nextContentWidth);
      return {
        doc: {
          ...doc3,
          nodes: {
            ...doc3.nodes,
            [nodeId]: nextNode
          }
        },
        result: { ok: true }
      };
    }
    case "set_blur_view_state": {
      const { blur: blur2 } = command2.payload;
      const previousViewState = doc3.viewState;
      const nextViewState = (() => {
        if (blur2) {
          return { ...previousViewState ?? {}, blur: blur2 };
        }
        if (!previousViewState) return void 0;
        const { blur: _removed, ...rest } = previousViewState;
        return Object.keys(rest).length > 0 ? rest : void 0;
      })();
      return {
        doc: {
          ...doc3,
          viewState: nextViewState
        },
        result: { ok: true }
      };
    }
    case "toggle_node_collapsed": {
      const { nodeId } = command2.payload;
      const node = doc3.nodes[nodeId];
      if (!node) return { doc: doc3, result: { ok: false, error: `Node not found: ${nodeId}` } };
      const previous = doc3.viewState?.collapsedNodeIds?.[nodeId] ?? false;
      const nextCollapsed = !previous;
      const nextMap = { ...doc3.viewState?.collapsedNodeIds ?? {} };
      if (nextCollapsed) nextMap[nodeId] = true;
      else delete nextMap[nodeId];
      const nextViewState = (() => {
        const base2 = { ...doc3.viewState ?? {} };
        if (Object.keys(nextMap).length > 0) base2.collapsedNodeIds = nextMap;
        else delete base2.collapsedNodeIds;
        return Object.keys(base2).length > 0 ? base2 : void 0;
      })();
      return { doc: { ...doc3, viewState: nextViewState }, result: { ok: true } };
    }
    case "set_node_collapsed": {
      const { nodeId, collapsed } = command2.payload;
      const node = doc3.nodes[nodeId];
      if (!node) return { doc: doc3, result: { ok: false, error: `Node not found: ${nodeId}` } };
      const nextMap = { ...doc3.viewState?.collapsedNodeIds ?? {} };
      if (collapsed) nextMap[nodeId] = true;
      else delete nextMap[nodeId];
      const nextViewState = (() => {
        const base2 = { ...doc3.viewState ?? {} };
        if (Object.keys(nextMap).length > 0) base2.collapsedNodeIds = nextMap;
        else delete base2.collapsedNodeIds;
        return Object.keys(base2).length > 0 ? base2 : void 0;
      })();
      return { doc: { ...doc3, viewState: nextViewState }, result: { ok: true } };
    }
    case "clear_mindmap_both_pins": {
      const { containerId } = command2.payload;
      const container = doc3.nodes[containerId];
      if (!container) return { doc: doc3, result: { ok: false, error: `Node not found: ${containerId}` } };
      if (!doc3.roots.includes(containerId)) {
        return { doc: doc3, result: { ok: false, error: "clear_mindmap_both_pins: containerId must be a root (V1)" } };
      }
      const layoutType = container.layout ?? "logical-right";
      if (layoutType !== "mindmap-both" && layoutType !== "mindmap-both-auto") {
        return {
          doc: doc3,
          result: {
            ok: false,
            error: `clear_mindmap_both_pins: unsupported root layout ${layoutType}`
          }
        };
      }
      let changed = false;
      const nextNodes = { ...doc3.nodes };
      for (const childId of container.children) {
        const child = nextNodes[childId];
        if (!child) continue;
        if (child.branchSide === void 0) continue;
        changed = true;
        const { branchSide: _removed, ...rest } = child;
        nextNodes[childId] = rest;
      }
      if (!changed) return { doc: doc3, result: { ok: true } };
      return { doc: { ...doc3, nodes: nextNodes }, result: { ok: true } };
    }
    case "rebalance_mindmap_both_auto": {
      const { containerId } = command2.payload;
      const container = doc3.nodes[containerId];
      if (!container) return { doc: doc3, result: { ok: false, error: `Node not found: ${containerId}` } };
      if (!doc3.roots.includes(containerId)) {
        return { doc: doc3, result: { ok: false, error: "rebalance_mindmap_both_auto: containerId must be a root (V1)" } };
      }
      const layoutType = container.layout ?? "logical-right";
      if (layoutType !== "mindmap-both-auto") {
        return {
          doc: doc3,
          result: {
            ok: false,
            error: `rebalance_mindmap_both_auto: unsupported root layout ${layoutType}`
          }
        };
      }
      const summaryById = new Map(doc3.summaries.map((summary) => [summary.id, summary]));
      const summaryIdsByParent = /* @__PURE__ */ new Map();
      for (const summary of doc3.summaries) {
        const key = String(summary.parentId);
        const bucket = summaryIdsByParent.get(key);
        if (bucket) bucket.push(summary.id);
        else summaryIdsByParent.set(key, [summary.id]);
      }
      const isNodeCollapsed = (nodeId) => doc3.viewState?.collapsedNodeIds?.[nodeId] === true;
      const subtreeNodeCountMemo = /* @__PURE__ */ new Map();
      const countVisibleSubtreeNodes = (startNodeId) => {
        const cached = subtreeNodeCountMemo.get(startNodeId);
        if (cached !== void 0) return cached;
        const stack = [startNodeId];
        const visited = /* @__PURE__ */ new Set();
        let count = 0;
        while (stack.length > 0) {
          const current = stack.pop();
          if (!current) break;
          if (visited.has(current)) continue;
          visited.add(current);
          const node = doc3.nodes[current];
          if (node) {
            count += 1;
            const collapsed = isNodeCollapsed(node.id);
            if (!collapsed) {
              for (const childId of node.children) {
                if (!doc3.nodes[childId]) continue;
                stack.push(childId);
              }
              const summaryIds = summaryIdsByParent.get(node.id);
              if (summaryIds) {
                for (const summaryId of summaryIds) stack.push(summaryId);
              }
            }
          }
          const summary = summaryById.get(current);
          if (summary) {
            for (const childId of summary.children) {
              if (!doc3.nodes[childId]) continue;
              stack.push(childId);
            }
            const summaryIds = summaryIdsByParent.get(summary.id);
            if (summaryIds) {
              for (const summaryId of summaryIds) stack.push(summaryId);
            }
          }
        }
        subtreeNodeCountMemo.set(startNodeId, count);
        return count;
      };
      const weightByChild = /* @__PURE__ */ new Map();
      const getWeight = (id) => {
        const existing = weightByChild.get(id);
        if (existing !== void 0) return existing;
        const weight = countVisibleSubtreeNodes(id);
        weightByChild.set(id, weight);
        return weight;
      };
      let leftTotal = 0;
      let rightTotal = 0;
      const mapping = {};
      let tieFlip = "right";
      for (const childId of container.children) {
        const node = doc3.nodes[childId];
        if (!node) continue;
        const weight = getWeight(childId);
        const side = leftTotal < rightTotal ? "left" : rightTotal < leftTotal ? "right" : tieFlip = tieFlip === "left" ? "right" : "left";
        mapping[childId] = side;
        if (side === "left") leftTotal += weight;
        else rightTotal += weight;
      }
      let changed = false;
      const nextNodes = { ...doc3.nodes };
      for (const childId of container.children) {
        const child = nextNodes[childId];
        const nextSide = mapping[childId];
        if (!child || !nextSide) continue;
        if (child.branchSide === nextSide) continue;
        changed = true;
        nextNodes[childId] = { ...child, branchSide: nextSide };
      }
      if (!changed) return { doc: doc3, result: { ok: true } };
      return { doc: { ...doc3, nodes: nextNodes }, result: { ok: true } };
    }
    case "set_node_text": {
      const { nodeId, text: text5 } = command2.payload;
      const node = doc3.nodes[nodeId];
      if (!node) {
        return { doc: doc3, result: { ok: false, error: `Node not found: ${nodeId}` } };
      }
      const nextNode = {
        ...node,
        text: text5
      };
      return {
        doc: {
          ...doc3,
          nodes: {
            ...doc3.nodes,
            [nodeId]: nextNode
          }
        },
        result: { ok: true }
      };
    }
    case "add_child": {
      const { parentId, index, node: partialNode } = command2.payload;
      const parent = doc3.nodes[parentId];
      if (!parent) {
        return { doc: doc3, result: { ok: false, error: `Node not found: ${parentId}` } };
      }
      const createdNodeId = idGenerator.generate("node");
      const insertIndex = typeof index === "number" ? clampIndex(index, parent.children.length) : parent.children.length;
      const leftSiblingId = insertIndex > 0 ? parent.children[insertIndex - 1] ?? null : null;
      const rightSiblingId = insertIndex < parent.children.length ? parent.children[insertIndex] ?? null : null;
      const leftPos = leftSiblingId ? doc3.nodes[leftSiblingId]?.pos ?? null : null;
      const rightPos = rightSiblingId ? doc3.nodes[rightSiblingId]?.pos ?? null : null;
      const nextPos = posBetween(leftPos, rightPos);
      const childNode = createNode(createdNodeId, {
        parentId,
        text: partialNode?.text ?? "",
        contentWidth: partialNode?.contentWidth,
        maxWidth: partialNode?.maxWidth,
        contentWidthMode: partialNode?.contentWidthMode,
        pos: nextPos
      });
      const nextChildren = [...parent.children];
      nextChildren.splice(insertIndex, 0, createdNodeId);
      const nextParent = {
        ...parent,
        children: nextChildren
      };
      return {
        doc: {
          ...doc3,
          nodes: {
            ...doc3.nodes,
            [createdNodeId]: childNode,
            [parentId]: nextParent
          }
        },
        result: { ok: true, createdNodeId }
      };
    }
    case "add_summary_child": {
      const { summaryId, index: childIndex, node: partialNode } = command2.payload;
      const index = doc3.summaries.findIndex((summary2) => summary2.id === summaryId);
      if (index === -1) {
        return { doc: doc3, result: { ok: false, error: `Summary not found: ${summaryId}` } };
      }
      const summary = doc3.summaries[index];
      const createdNodeId = idGenerator.generate("node");
      const insertIndex = typeof childIndex === "number" ? clampIndex(childIndex, summary.children.length) : summary.children.length;
      const leftSiblingId = insertIndex > 0 ? summary.children[insertIndex - 1] ?? null : null;
      const rightSiblingId = insertIndex < summary.children.length ? summary.children[insertIndex] ?? null : null;
      const leftPos = leftSiblingId ? doc3.nodes[leftSiblingId]?.pos ?? null : null;
      const rightPos = rightSiblingId ? doc3.nodes[rightSiblingId]?.pos ?? null : null;
      const nextPos = posBetween(leftPos, rightPos);
      const childNode = createNode(createdNodeId, {
        parentSummaryId: summaryId,
        text: partialNode?.text ?? "",
        contentWidth: partialNode?.contentWidth,
        maxWidth: partialNode?.maxWidth,
        contentWidthMode: partialNode?.contentWidthMode,
        pos: nextPos
      });
      const nextSummaries = [...doc3.summaries];
      const nextChildren = [...summary.children];
      nextChildren.splice(insertIndex, 0, createdNodeId);
      nextSummaries[index] = {
        ...summary,
        children: nextChildren
      };
      return {
        doc: {
          ...doc3,
          nodes: {
            ...doc3.nodes,
            [createdNodeId]: childNode
          },
          summaries: nextSummaries
        },
        result: { ok: true, createdNodeId }
      };
    }
    case "add_root": {
      const createdNodeId = idGenerator.generate("node");
      const partialNode = command2.payload?.node;
      const requestedPosition = command2.payload?.position;
      const insertIndex = typeof command2.payload?.index === "number" ? clampIndex(command2.payload.index, doc3.roots.length) : doc3.roots.length;
      const leftRootId = insertIndex > 0 ? doc3.roots[insertIndex - 1] ?? null : null;
      const rightRootId = insertIndex < doc3.roots.length ? doc3.roots[insertIndex] ?? null : null;
      const leftPos = leftRootId ? doc3.nodes[leftRootId]?.pos ?? null : null;
      const rightPos = rightRootId ? doc3.nodes[rightRootId]?.pos ?? null : null;
      const nextPos = posBetween(leftPos, rightPos);
      const rootNode = createNode(createdNodeId, {
        text: partialNode?.text ?? "Root",
        contentWidth: partialNode?.contentWidth ?? { mode: "auto", wrapWidth: partialNode?.maxWidth ?? 240 },
        maxWidth: partialNode?.maxWidth ?? 240,
        contentWidthMode: partialNode?.contentWidthMode,
        layout: partialNode?.layout,
        pos: nextPos
      });
      const nextRoots = [...doc3.roots];
      nextRoots.splice(insertIndex, 0, createdNodeId);
      const nextRootPositions = seedMissingRootPositions({ roots: nextRoots, existing: doc3.rootPositions });
      if (requestedPosition && Number.isFinite(requestedPosition.x) && Number.isFinite(requestedPosition.y)) {
        nextRootPositions[createdNodeId] = { x: requestedPosition.x, y: requestedPosition.y };
      }
      return {
        doc: {
          ...doc3,
          roots: nextRoots,
          rootPositions: nextRootPositions,
          nodes: {
            ...doc3.nodes,
            [createdNodeId]: rootNode
          }
        },
        result: { ok: true, createdNodeId }
      };
    }
    case "move_root": {
      const { rootId, direction } = command2.payload;
      const index = doc3.roots.indexOf(rootId);
      if (index === -1) {
        return { doc: doc3, result: { ok: false, error: `Root not found: ${rootId}` } };
      }
      const nextIndex = direction === "up" ? index - 1 : index + 1;
      if (nextIndex < 0 || nextIndex >= doc3.roots.length) {
        return { doc: doc3, result: { ok: true } };
      }
      const nextRoots = [...doc3.roots];
      nextRoots.splice(index, 1);
      nextRoots.splice(nextIndex, 0, rootId);
      const leftId = nextIndex > 0 ? nextRoots[nextIndex - 1] : null;
      const rightId = nextIndex < nextRoots.length - 1 ? nextRoots[nextIndex + 1] : null;
      const leftPos = leftId ? doc3.nodes[leftId]?.pos ?? null : null;
      const rightPos = rightId ? doc3.nodes[rightId]?.pos ?? null : null;
      const node = doc3.nodes[rootId];
      const nextPos = posBetween(leftPos, rightPos);
      return {
        doc: {
          ...doc3,
          roots: nextRoots,
          nodes: node ? { ...doc3.nodes, [rootId]: { ...node, pos: nextPos } } : doc3.nodes
        },
        result: { ok: true }
      };
    }
    case "set_node_layout": {
      const { nodeId, layout } = command2.payload;
      const node = doc3.nodes[nodeId];
      if (!node) {
        return { doc: doc3, result: { ok: false, error: `Node not found: ${nodeId}` } };
      }
      return {
        doc: {
          ...doc3,
          nodes: {
            ...doc3.nodes,
            [nodeId]: {
              ...node,
              layout: layout ?? void 0
            }
          }
        },
        result: { ok: true }
      };
    }
    case "delete_node": {
      const { nodeId } = command2.payload;
      const node = doc3.nodes[nodeId];
      if (!node) {
        return { doc: doc3, result: { ok: false, error: `Node not found: ${nodeId}` } };
      }
      const isRoot = doc3.roots.includes(nodeId);
      if (isRoot && doc3.roots.length <= 1) {
        return { doc: doc3, result: { ok: false, error: "Cannot delete the last root" } };
      }
      const summariesByParent = buildSummariesByParent(doc3);
      const deletedNodeIds = new Set(collectSubtreeIds(doc3, nodeId, summariesByParent));
      const nextNodes = { ...doc3.nodes };
      for (const id of deletedNodeIds) {
        delete nextNodes[id];
      }
      const nextRoots = doc3.roots.filter((id) => !deletedNodeIds.has(id));
      const sanitized = sanitizeSummaries({
        nodes: nextNodes,
        roots: nextRoots,
        summaries: doc3.summaries,
        originalSummaries: doc3.summaries
      });
      const rootPositions = doc3.rootPositions ?? {};
      const sanitizedRootSet = new Set(sanitized.roots);
      const sanitizedRootPositions = {};
      for (const [id, position] of Object.entries(rootPositions)) {
        if (!sanitizedRootSet.has(id)) continue;
        sanitizedRootPositions[id] = position;
      }
      const collapsedNodeIds = doc3.viewState?.collapsedNodeIds;
      const sanitizedCollapsedNodeIds = collapsedNodeIds ? Object.fromEntries(
        Object.entries(collapsedNodeIds).filter(([id, value]) => !deletedNodeIds.has(id) && value === true)
      ) : void 0;
      const nextViewState = (() => {
        if (!doc3.viewState) return void 0;
        const next = { ...doc3.viewState };
        if (sanitizedCollapsedNodeIds && Object.keys(sanitizedCollapsedNodeIds).length > 0) next.collapsedNodeIds = sanitizedCollapsedNodeIds;
        else delete next.collapsedNodeIds;
        return Object.keys(next).length > 0 ? next : void 0;
      })();
      const nodes = pruneDanglingInternalLinks(sanitized.nodes, deletedNodeIds);
      const summaries = pruneDanglingInternalLinksInSummaries(sanitized.summaries, deletedNodeIds);
      return {
        doc: {
          ...doc3,
          roots: sanitized.roots,
          nodes,
          summaries,
          rootPositions: sanitizedRootPositions,
          relations: doc3.relations.filter((rel2) => {
            const nextDoc = { ...doc3, roots: nextRoots, nodes, summaries };
            return relationEndpointExists(nextDoc, rel2.from) && relationEndpointExists(nextDoc, rel2.to);
          }),
          viewState: nextViewState
        },
        result: { ok: true }
      };
    }
    case "create_summary": {
      const { parentId, childIds, summary: partial } = command2.payload;
      const parentNode2 = doc3.nodes[parentId];
      const parentSummary = doc3.summaries.find((item) => item.id === parentId);
      if (!parentNode2 && !parentSummary) {
        return { doc: doc3, result: { ok: false, error: `Parent not found: ${parentId}` } };
      }
      const uniqueChildIds = Array.from(new Set(childIds)).filter((id) => Boolean(doc3.nodes[id]));
      if (uniqueChildIds.length === 0) {
        return { doc: doc3, result: { ok: false, error: "Summary must include at least one child node" } };
      }
      for (const childId of uniqueChildIds) {
        const child = doc3.nodes[childId];
        const isValid = parentNode2 ? child?.parentId === parentId : child?.parentSummaryId === parentId;
        if (!isValid) {
          return {
            doc: doc3,
            result: { ok: false, error: `Summary child must be a direct child of ${parentId}: ${childId}` }
          };
        }
      }
      const containerChildIds = (() => {
        if (parentSummary) return parentSummary.children.filter((id) => Boolean(doc3.nodes[id]));
        if (!parentNode2) return [];
        const layoutType = parentNode2.layout ?? "logical-right";
        if (layoutType !== "mindmap-both" && layoutType !== "mindmap-both-auto") {
          return parentNode2.children.filter((id) => Boolean(doc3.nodes[id]));
        }
        const resolveSide = (nodeId) => doc3.nodes[nodeId]?.branchSide === "left" ? "left" : "right";
        const selectedSides = new Set(uniqueChildIds.map((id) => resolveSide(id)));
        if (selectedSides.size > 1) {
          return [];
        }
        const targetSide = selectedSides.has("left") ? "left" : "right";
        return parentNode2.children.filter((id) => Boolean(doc3.nodes[id]) && resolveSide(id) === targetSide);
      })();
      if (containerChildIds.length === 0) {
        if (parentNode2 && (parentNode2.layout === "mindmap-both" || parentNode2.layout === "mindmap-both-auto")) {
          return { doc: doc3, result: { ok: false, error: `${parentNode2.layout}: summary selection must stay on the same side (left/right)` } };
        }
      }
      const indexById = new Map(containerChildIds.map((id, index) => [id, index]));
      const indices = uniqueChildIds.map((id) => indexById.get(id)).filter((index) => index !== void 0);
      if (indices.length !== uniqueChildIds.length) {
        return { doc: doc3, result: { ok: false, error: "Summary childIds must belong to the same parent container" } };
      }
      const startIndex = Math.min(...indices);
      const endIndex = Math.max(...indices);
      const coveredIds = containerChildIds.slice(startIndex, endIndex + 1);
      const coveredSet = new Set(coveredIds);
      for (const id of uniqueChildIds) {
        if (!coveredSet.has(id)) {
          return { doc: doc3, result: { ok: false, error: "Summary selection must be contiguous siblings" } };
        }
      }
      for (const existing of doc3.summaries) {
        if (existing.parentId !== parentId) continue;
        const existingIndices = existing.childIds.map((id) => indexById.get(id)).filter((index) => index !== void 0);
        if (existingIndices.length !== existing.childIds.length) continue;
        if (existingIndices.length === 0) continue;
        const existingStart = Math.min(...existingIndices);
        const existingEnd = Math.max(...existingIndices);
        if (endIndex < existingStart || startIndex > existingEnd) continue;
        if (startIndex === existingStart && endIndex === existingEnd) {
          return { doc: doc3, result: { ok: true, createdSummaryId: existing.id } };
        }
        return { doc: doc3, result: { ok: false, error: `Summary overlaps with existing summary: ${existing.id}` } };
      }
      const createdSummaryId = idGenerator.generate("summary");
      const summary = {
        id: createdSummaryId,
        parentId,
        childIds: coveredIds,
        text: partial?.text ?? "",
        content: partial?.content,
        maxWidth: partial?.maxWidth,
        layout: partial?.layout,
        children: []
      };
      return {
        doc: {
          ...doc3,
          summaries: [...doc3.summaries, summary]
        },
        result: { ok: true, createdSummaryId }
      };
    }
    case "update_summary_text": {
      const { summaryId, text: text5 } = command2.payload;
      const index = doc3.summaries.findIndex((summary) => summary.id === summaryId);
      if (index === -1) {
        return { doc: doc3, result: { ok: false, error: `Summary not found: ${summaryId}` } };
      }
      const nextSummaries = [...doc3.summaries];
      nextSummaries[index] = { ...nextSummaries[index], text: text5 };
      return { doc: { ...doc3, summaries: nextSummaries }, result: { ok: true } };
    }
    case "set_summary_layout": {
      const { summaryId, layout } = command2.payload;
      const index = doc3.summaries.findIndex((summary) => summary.id === summaryId);
      if (index === -1) {
        return { doc: doc3, result: { ok: false, error: `Summary not found: ${summaryId}` } };
      }
      const nextSummaries = [...doc3.summaries];
      nextSummaries[index] = {
        ...nextSummaries[index],
        layout: layout ?? void 0
      };
      return { doc: { ...doc3, summaries: nextSummaries }, result: { ok: true } };
    }
    case "delete_summary": {
      const { summaryId } = command2.payload;
      const index = doc3.summaries.findIndex((summary) => summary.id === summaryId);
      if (index === -1) {
        return { doc: doc3, result: { ok: false, error: `Summary not found: ${summaryId}` } };
      }
      const summariesByParent = buildSummariesByParent(doc3);
      const deletedNodeIds = new Set(
        collectSubtreeIds(doc3, summaryId, summariesByParent)
      );
      const nextNodes = { ...doc3.nodes };
      for (const id of deletedNodeIds) {
        delete nextNodes[id];
      }
      const nextRoots = doc3.roots.filter((id) => !deletedNodeIds.has(id));
      const nextSummaries = doc3.summaries.filter((item) => item.id !== summaryId);
      const sanitized = sanitizeSummaries({
        nodes: nextNodes,
        roots: nextRoots,
        summaries: nextSummaries,
        originalSummaries: doc3.summaries
      });
      const nodes = pruneDanglingInternalLinks(sanitized.nodes, deletedNodeIds);
      const summaries = pruneDanglingInternalLinksInSummaries(sanitized.summaries, deletedNodeIds);
      return {
        doc: {
          ...doc3,
          roots: sanitized.roots,
          nodes,
          summaries,
          relations: doc3.relations.filter((rel2) => {
            const nextDoc = { ...doc3, roots: nextRoots, nodes, summaries };
            return relationEndpointExists(nextDoc, rel2.from) && relationEndpointExists(nextDoc, rel2.to);
          })
        },
        result: { ok: true }
      };
    }
    case "create_relation": {
      const { label, style: style2 } = command2.payload;
      const from2 = normalizeRelationEndpoint(command2.payload.from);
      const to = normalizeRelationEndpoint(command2.payload.to);
      if (!from2) {
        return { doc: doc3, result: { ok: false, error: "Invalid relation source endpoint" } };
      }
      if (!to) {
        return { doc: doc3, result: { ok: false, error: "Invalid relation target endpoint" } };
      }
      if (!relationEndpointExists(doc3, from2)) {
        return { doc: doc3, result: { ok: false, error: `Relation endpoint not found: ${relationEndpointKey(from2)}` } };
      }
      if (!relationEndpointExists(doc3, to)) {
        return { doc: doc3, result: { ok: false, error: `Relation endpoint not found: ${relationEndpointKey(to)}` } };
      }
      if (relationEndpointKey(from2) === relationEndpointKey(to)) {
        return { doc: doc3, result: { ok: false, error: "Cannot create a relation to itself" } };
      }
      const createdRelationId = idGenerator.generate("relation");
      const relation = {
        id: createdRelationId,
        from: from2,
        to,
        routeType: "curved",
        direction: normalizeRelationDirection(command2.payload.direction) ?? "forward",
        label,
        style: style2
      };
      return {
        doc: { ...doc3, relations: [...doc3.relations, relation] },
        result: { ok: true, createdRelationId }
      };
    }
    case "delete_relation": {
      const { relationId } = command2.payload;
      const nextRelations = doc3.relations.filter((rel2) => rel2.id !== relationId);
      if (nextRelations.length === doc3.relations.length) {
        return { doc: doc3, result: { ok: false, error: `Relation not found: ${relationId}` } };
      }
      return { doc: { ...doc3, relations: nextRelations }, result: { ok: true } };
    }
    case "set_relation_label": {
      const { relationId, label } = command2.payload;
      const index = doc3.relations.findIndex((rel2) => rel2.id === relationId);
      if (index === -1) {
        return { doc: doc3, result: { ok: false, error: `Relation not found: ${relationId}` } };
      }
      const normalized = (() => {
        if (!label) return void 0;
        if (label.schemaVersion !== 1) return void 0;
        if (label.kind !== "plain-text") return void 0;
        const text5 = String(label.text ?? "");
        if (text5.trim().length === 0) return void 0;
        return { ...label, text: text5 };
      })();
      const prev = doc3.relations[index];
      const next = { ...prev, label: normalized };
      const nextRelations = doc3.relations.slice();
      nextRelations[index] = next;
      return { doc: { ...doc3, relations: nextRelations }, result: { ok: true } };
    }
    case "set_relation_direction": {
      const { relationId, direction } = command2.payload;
      const index = doc3.relations.findIndex((rel2) => rel2.id === relationId);
      if (index === -1) {
        return { doc: doc3, result: { ok: false, error: `Relation not found: ${relationId}` } };
      }
      const normalizedDirection = direction == null ? void 0 : normalizeRelationDirection(direction);
      const prev = doc3.relations[index];
      const next = { ...prev, direction: normalizedDirection };
      const nextRelations = doc3.relations.slice();
      nextRelations[index] = next;
      const currentTheme = ensureDocumentTheme(doc3);
      const overrides = { ...currentTheme.overrides ?? {} };
      const relations = { ...overrides.relations ?? {} };
      const relationOverride = { ...relations[relationId] ?? {} };
      if (normalizedDirection) {
        relationOverride.direction = normalizedDirection;
        relations[relationId] = relationOverride;
      } else {
        delete relationOverride.direction;
        if (Object.keys(relationOverride).length > 0) relations[relationId] = relationOverride;
        else delete relations[relationId];
      }
      const nextOverrides = {
        ...overrides,
        relations: Object.keys(relations).length > 0 ? relations : void 0
      };
      const nextTheme = {
        ...currentTheme,
        overrides: Object.values(nextOverrides).some((value) => value !== void 0) ? nextOverrides : void 0
      };
      return { doc: { ...doc3, relations: nextRelations, theme: nextTheme }, result: { ok: true } };
    }
    case "set_relation_style": {
      const { relationId, style: style2 } = command2.payload;
      const index = doc3.relations.findIndex((rel2) => rel2.id === relationId);
      if (index === -1) {
        return { doc: doc3, result: { ok: false, error: `Relation not found: ${relationId}` } };
      }
      const normalized = (() => {
        if (!style2) return void 0;
        const next2 = {
          strokeColor: style2.strokeColor,
          strokeWidth: style2.strokeWidth,
          strokeDasharray: style2.strokeDasharray
        };
        const hasAny = Boolean(next2.strokeColor || next2.strokeDasharray || typeof next2.strokeWidth === "number" && !Number.isNaN(next2.strokeWidth));
        if (!hasAny) return void 0;
        return next2;
      })();
      const prev = doc3.relations[index];
      const next = { ...prev, style: normalized };
      const nextRelations = doc3.relations.slice();
      nextRelations[index] = next;
      return { doc: { ...doc3, relations: nextRelations }, result: { ok: true } };
    }
    case "set_relation_curve": {
      const { relationId, curve } = command2.payload;
      const index = doc3.relations.findIndex((rel2) => rel2.id === relationId);
      if (index === -1) {
        return { doc: doc3, result: { ok: false, error: `Relation not found: ${relationId}` } };
      }
      const normalized = (() => {
        if (!curve) return void 0;
        if (curve.schemaVersion !== 1) return void 0;
        if (curve.kind !== "cubic") return void 0;
        return {
          ...curve,
          control1: { x: Number(curve.control1.x ?? 0), y: Number(curve.control1.y ?? 0) },
          control2: { x: Number(curve.control2.x ?? 0), y: Number(curve.control2.y ?? 0) }
        };
      })();
      const prev = doc3.relations[index];
      const next = { ...prev, curve: normalized };
      const nextRelations = doc3.relations.slice();
      nextRelations[index] = next;
      return { doc: { ...doc3, relations: nextRelations }, result: { ok: true } };
    }
    case "set_relation_ports": {
      const { relationId, fromPort, toPort } = command2.payload;
      const index = doc3.relations.findIndex((rel2) => rel2.id === relationId);
      if (index === -1) {
        return { doc: doc3, result: { ok: false, error: `Relation not found: ${relationId}` } };
      }
      const prev = doc3.relations[index];
      const nextFromPort = fromPort == null ? void 0 : fromPort;
      const nextToPort = toPort == null ? void 0 : toPort;
      const nextFromPortRatio = (() => {
        if (!nextFromPort) return void 0;
        return prev.from.port === nextFromPort ? prev.from.portRatio : void 0;
      })();
      const nextToPortRatio = (() => {
        if (!nextToPort) return void 0;
        return prev.to.port === nextToPort ? prev.to.portRatio : void 0;
      })();
      const next = {
        ...prev,
        from: { ...prev.from, port: nextFromPort, portRatio: nextFromPortRatio },
        to: { ...prev.to, port: nextToPort, portRatio: nextToPortRatio }
      };
      const nextRelations = doc3.relations.slice();
      nextRelations[index] = next;
      return { doc: { ...doc3, relations: nextRelations }, result: { ok: true } };
    }
    case "set_relation_endpoint": {
      const { relationId, endpoint, port, portRatio } = command2.payload;
      const index = doc3.relations.findIndex((rel2) => rel2.id === relationId);
      if (index === -1) {
        return { doc: doc3, result: { ok: false, error: `Relation not found: ${relationId}` } };
      }
      const normalizeRatio = (value) => {
        if (value == null) return void 0;
        const next2 = Number(value);
        if (!Number.isFinite(next2)) return void 0;
        return Math.max(0, Math.min(1, next2));
      };
      const prev = doc3.relations[index];
      const nextPort = port == null ? void 0 : port;
      const nextPortRatio = nextPort ? normalizeRatio(portRatio) : void 0;
      const next = {
        ...prev,
        [endpoint]: {
          ...endpoint === "from" ? prev.from : prev.to,
          port: nextPort,
          portRatio: nextPortRatio
        }
      };
      const nextRelations = doc3.relations.slice();
      nextRelations[index] = next;
      return { doc: { ...doc3, relations: nextRelations }, result: { ok: true } };
    }
    case "insert_subtree": {
      const { parentId, subtree } = command2.payload;
      if (parentId && !doc3.nodes[parentId]) {
        return { doc: doc3, result: { ok: false, error: `Node not found: ${parentId}` } };
      }
      const idMap = /* @__PURE__ */ new Map();
      for (const oldId of Object.keys(subtree.nodes)) {
        idMap.set(oldId, idGenerator.generate("node"));
      }
      const assetIdMap = /* @__PURE__ */ new Map();
      const subtreeAssets = subtree.assets ?? {};
      const nextNodes = { ...doc3.nodes };
      for (const [oldId, oldNode] of Object.entries(subtree.nodes)) {
        const newId = idMap.get(oldId);
        if (!newId) continue;
        nextNodes[newId] = {
          ...oldNode,
          id: newId,
          // Best practice: when pasting subtree as a child, drop layout overrides to avoid
          // bringing in layouts that are invalid under the target root/subtree layout whitelist.
          // When pasting as new roots (parentId=null), keep the original root layout overrides.
          layout: parentId ? void 0 : oldNode.layout,
          parentId: oldNode.parentId ? idMap.get(oldNode.parentId) ?? void 0 : void 0,
          parentSummaryId: void 0,
          children: oldNode.children.map((childId) => idMap.get(childId) ?? childId),
          content: rewriteContentIds(oldNode.content, { nodeIdMap: idMap, assetIdMap })
        };
      }
      const newRootIds = subtree.roots.map((rootId) => idMap.get(rootId) ?? rootId);
      const nextAssets = { ...doc3.assets ?? {} };
      for (const [assetId, asset] of Object.entries(subtreeAssets)) {
        if (nextAssets[assetId]) continue;
        nextAssets[assetId] = { ...asset, id: assetId };
      }
      let nextRoots = doc3.roots;
      if (!parentId) {
        const lastRootId = doc3.roots[doc3.roots.length - 1] ?? null;
        let cursorPos = lastRootId ? doc3.nodes[lastRootId]?.pos ?? null : null;
        for (const rootId of newRootIds) {
          const pastedRoot = nextNodes[rootId];
          if (!pastedRoot) continue;
          const nextPos = cursorPos ? posBetween(cursorPos, null) : posBetween(null, null);
          pastedRoot.pos = nextPos;
          cursorPos = nextPos;
        }
        nextRoots = [...doc3.roots, ...newRootIds];
      } else {
        const parentNode2 = nextNodes[parentId] ?? doc3.nodes[parentId];
        if (!parentNode2) {
          return { doc: doc3, result: { ok: false, error: `Node not found: ${parentId}` } };
        }
        nextNodes[parentId] = {
          ...parentNode2,
          children: [...parentNode2.children, ...newRootIds]
        };
        const lastSiblingId = parentNode2.children[parentNode2.children.length - 1] ?? null;
        let cursorPos = lastSiblingId ? doc3.nodes[lastSiblingId]?.pos ?? null : null;
        for (const rootId of newRootIds) {
          const pastedRoot = nextNodes[rootId];
          if (pastedRoot) {
            pastedRoot.parentId = parentId;
            const nextPos = cursorPos ? posBetween(cursorPos, null) : posBetween(null, null);
            pastedRoot.pos = nextPos;
            cursorPos = nextPos;
          }
        }
      }
      const nextRootPositions = !parentId ? seedMissingRootPositions({ roots: nextRoots, existing: doc3.rootPositions }) : doc3.rootPositions;
      return {
        doc: {
          ...doc3,
          roots: nextRoots,
          rootPositions: nextRootPositions,
          nodes: nextNodes,
          assets: nextAssets
        },
        result: { ok: true }
      };
    }
    case "move_node": {
      const { nodeId, to } = command2.payload;
      const node = doc3.nodes[nodeId];
      if (!node) {
        return { doc: doc3, result: { ok: false, error: `Node not found: ${nodeId}` } };
      }
      const rootPositions = doc3.rootPositions ?? {};
      const isRoot = doc3.roots.includes(nodeId);
      const currentRootIndex = isRoot ? doc3.roots.indexOf(nodeId) : -1;
      if (isRoot && doc3.roots.length <= 1 && to.type !== "root") {
        return { doc: doc3, result: { ok: false, error: "Cannot move the last root" } };
      }
      if (to.type === "node" && !isRoot && !node.parentSummaryId && to.parentId === node.parentId) {
        const wantsBranchSideChange = (() => {
          if (to.branchSide === void 0) return false;
          const next = to.branchSide === null ? void 0 : to.branchSide;
          return node.branchSide !== next;
        })();
        if (to.index === void 0 && !wantsBranchSideChange) return { doc: doc3, result: { ok: true } };
        if (to.index === void 0) {
        } else {
          const parent = doc3.nodes[to.parentId];
          if (parent) {
            const siblings = parent.children.filter((id) => id !== nodeId);
            const nextIndex = clampIndex(to.index, siblings.length);
            const nextChildren = [...siblings];
            nextChildren.splice(nextIndex, 0, nodeId);
            if (arraysEqual(nextChildren, parent.children) && !wantsBranchSideChange) {
              return { doc: doc3, result: { ok: true } };
            }
          }
        }
      }
      if (to.type === "summary" && !isRoot && !node.parentId && to.summaryId === node.parentSummaryId) {
        if (to.index === void 0) return { doc: doc3, result: { ok: true } };
        const summary = doc3.summaries.find((item) => item.id === to.summaryId);
        if (summary) {
          const siblings = summary.children.filter((id) => id !== nodeId);
          const nextIndex = clampIndex(to.index, siblings.length);
          const nextChildren = [...siblings];
          nextChildren.splice(nextIndex, 0, nodeId);
          if (arraysEqual(nextChildren, summary.children)) {
            return { doc: doc3, result: { ok: true } };
          }
        }
      }
      if (to.type === "root" && isRoot && !node.parentId && !node.parentSummaryId) {
        const currentPosition = rootPositions[nodeId];
        const nextPosition = to.position;
        const positionUnchanged = !nextPosition ? currentPosition === void 0 : currentPosition !== void 0 && currentPosition.x === nextPosition.x && currentPosition.y === nextPosition.y;
        if (to.index === void 0) {
          if (positionUnchanged) return { doc: doc3, result: { ok: true } };
        } else {
          const rootsWithout = doc3.roots.filter((id) => id !== nodeId);
          const nextIndex = clampIndex(to.index, rootsWithout.length);
          const nextRoots2 = [...rootsWithout];
          nextRoots2.splice(nextIndex, 0, nodeId);
          if (positionUnchanged && arraysEqual(nextRoots2, doc3.roots)) {
            return { doc: doc3, result: { ok: true } };
          }
        }
      }
      const summariesByParent = buildSummariesByParent(doc3);
      const descendants = new Set(collectSubtreeIds(doc3, nodeId, summariesByParent));
      if (to.type === "node") {
        const parent = doc3.nodes[to.parentId];
        if (!parent) {
          return { doc: doc3, result: { ok: false, error: `Node not found: ${to.parentId}` } };
        }
        if (descendants.has(to.parentId)) {
          return { doc: doc3, result: { ok: false, error: "Cannot move a node into its own subtree" } };
        }
      }
      if (to.type === "summary") {
        const summaryById = new Map(doc3.summaries.map((item) => [item.id, item]));
        const summary = summaryById.get(to.summaryId);
        if (!summary) {
          return { doc: doc3, result: { ok: false, error: `Summary not found: ${to.summaryId}` } };
        }
        let anchorNodeId = null;
        let cursor = summary;
        const visitedSummaries = /* @__PURE__ */ new Set();
        while (cursor) {
          if (visitedSummaries.has(cursor.id)) break;
          visitedSummaries.add(cursor.id);
          const parentId = cursor.parentId;
          if (doc3.nodes[parentId]) {
            anchorNodeId = parentId;
            break;
          }
          cursor = summaryById.get(parentId);
        }
        if (anchorNodeId && descendants.has(anchorNodeId)) {
          return { doc: doc3, result: { ok: false, error: "Cannot move a node into its own subtree" } };
        }
      }
      const nextNodes = { ...doc3.nodes };
      let nextRoots = [...doc3.roots];
      let nextSummaries = doc3.summaries.map((summary) => ({ ...summary, childIds: [...summary.childIds], children: [...summary.children] }));
      const nextRootPositions = { ...rootPositions };
      if (isRoot) {
        nextRoots = nextRoots.filter((id) => id !== nodeId);
      } else if (node.parentId) {
        const parent = nextNodes[node.parentId];
        if (parent) {
          nextNodes[node.parentId] = { ...parent, children: parent.children.filter((id) => id !== nodeId) };
        }
      } else if (node.parentSummaryId) {
        nextSummaries = nextSummaries.map(
          (summary) => summary.id === node.parentSummaryId ? { ...summary, children: summary.children.filter((id) => id !== nodeId) } : summary
        );
      } else {
        for (const candidate of Object.values(nextNodes)) {
          if (!candidate.children.includes(nodeId)) continue;
          nextNodes[candidate.id] = { ...candidate, children: candidate.children.filter((id) => id !== nodeId) };
        }
        nextSummaries = nextSummaries.map((summary) => ({
          ...summary,
          children: summary.children.filter((id) => id !== nodeId)
        }));
      }
      if (isRoot && to.type !== "root") {
        delete nextRootPositions[nodeId];
      }
      const nextNode = { ...node, parentId: void 0, parentSummaryId: void 0 };
      if (to.type === "root") {
        const base2 = nextRoots.filter((id) => id !== nodeId);
        const insertIndex = typeof to.index === "number" ? clampIndex(to.index, base2.length) : isRoot && currentRootIndex >= 0 ? clampIndex(currentRootIndex, base2.length) : base2.length;
        base2.splice(insertIndex, 0, nodeId);
        nextRoots = base2;
        const shouldUpdatePos = !isRoot || typeof to.index === "number";
        if (shouldUpdatePos) {
          const leftId = insertIndex > 0 ? base2[insertIndex - 1] : null;
          const rightId = insertIndex < base2.length - 1 ? base2[insertIndex + 1] : null;
          const leftPos = leftId ? nextNodes[leftId]?.pos ?? doc3.nodes[leftId]?.pos ?? null : null;
          const rightPos = rightId ? nextNodes[rightId]?.pos ?? doc3.nodes[rightId]?.pos ?? null : null;
          nextNode.pos = posBetween(leftPos, rightPos);
        }
        if (to.position) {
          nextRootPositions[nodeId] = { x: to.position.x, y: to.position.y };
        } else if (!isRoot) {
          delete nextRootPositions[nodeId];
        }
      } else if (to.type === "node") {
        const parent = nextNodes[to.parentId];
        if (!parent) {
          return { doc: doc3, result: { ok: false, error: `Node not found: ${to.parentId}` } };
        }
        const wasSameParent = !isRoot && !node.parentSummaryId && node.parentId === to.parentId;
        nextNode.parentId = to.parentId;
        if (to.branchSide !== void 0) {
          nextNode.branchSide = to.branchSide === null ? void 0 : to.branchSide;
        }
        const siblings = parent.children.filter((id) => id !== nodeId);
        const insertIndex = (() => {
          if (typeof to.index === "number") return clampIndex(to.index, siblings.length);
          if (!wasSameParent) return siblings.length;
          const originalParent = doc3.nodes[to.parentId];
          const originalIndex = originalParent ? originalParent.children.indexOf(nodeId) : -1;
          if (originalIndex < 0) return siblings.length;
          return clampIndex(originalIndex, siblings.length);
        })();
        siblings.splice(insertIndex, 0, nodeId);
        nextNodes[to.parentId] = { ...parent, children: siblings };
        const shouldUpdatePos = !wasSameParent || typeof to.index === "number";
        if (shouldUpdatePos) {
          const leftId = insertIndex > 0 ? siblings[insertIndex - 1] : null;
          const rightId = insertIndex < siblings.length - 1 ? siblings[insertIndex + 1] : null;
          const leftPos = leftId ? nextNodes[leftId]?.pos ?? doc3.nodes[leftId]?.pos ?? null : null;
          const rightPos = rightId ? nextNodes[rightId]?.pos ?? doc3.nodes[rightId]?.pos ?? null : null;
          nextNode.pos = posBetween(leftPos, rightPos);
        }
      } else {
        const wasSameSummary = !isRoot && !node.parentId && node.parentSummaryId === to.summaryId;
        nextNode.parentSummaryId = to.summaryId;
        const summaryIndex = nextSummaries.findIndex((summary2) => summary2.id === to.summaryId);
        if (summaryIndex === -1) {
          return { doc: doc3, result: { ok: false, error: `Summary not found: ${to.summaryId}` } };
        }
        const summary = nextSummaries[summaryIndex];
        const siblings = summary.children.filter((id) => id !== nodeId);
        const insertIndex = typeof to.index === "number" ? clampIndex(to.index, siblings.length) : siblings.length;
        siblings.splice(insertIndex, 0, nodeId);
        nextSummaries = nextSummaries.slice();
        nextSummaries[summaryIndex] = { ...summary, children: siblings };
        const shouldUpdatePos = !wasSameSummary || typeof to.index === "number";
        if (shouldUpdatePos) {
          const leftId = insertIndex > 0 ? siblings[insertIndex - 1] : null;
          const rightId = insertIndex < siblings.length - 1 ? siblings[insertIndex + 1] : null;
          const leftPos = leftId ? nextNodes[leftId]?.pos ?? doc3.nodes[leftId]?.pos ?? null : null;
          const rightPos = rightId ? nextNodes[rightId]?.pos ?? doc3.nodes[rightId]?.pos ?? null : null;
          nextNode.pos = posBetween(leftPos, rightPos);
        }
      }
      nextNodes[nodeId] = nextNode;
      const sanitized = sanitizeSummaries({
        nodes: nextNodes,
        roots: nextRoots,
        summaries: nextSummaries,
        originalSummaries: doc3.summaries
      });
      const sanitizedRootSet = new Set(sanitized.roots);
      const sanitizedRootPositions = {};
      for (const [id, position] of Object.entries(nextRootPositions)) {
        if (!sanitizedRootSet.has(id)) continue;
        sanitizedRootPositions[id] = position;
      }
      return {
        doc: {
          ...doc3,
          roots: sanitized.roots,
          nodes: sanitized.nodes,
          summaries: sanitized.summaries,
          rootPositions: sanitizedRootPositions
        },
        result: { ok: true }
      };
    }
    case "set_document_theme": {
      const currentTheme = ensureDocumentTheme(doc3);
      const nextTheme = {
        ...currentTheme,
        defaultTheme: command2.payload.theme
      };
      return {
        doc: { ...doc3, theme: nextTheme },
        result: { ok: true }
      };
    }
    case "set_root_theme": {
      const { rootId, theme } = command2.payload;
      if (!doc3.roots.includes(rootId)) {
        return { doc: doc3, result: { ok: false, error: `Root not found: ${rootId}` } };
      }
      const currentTheme = ensureDocumentTheme(doc3);
      const rootThemes = { ...currentTheme.rootThemes ?? {} };
      if (theme) {
        rootThemes[rootId] = theme;
      } else {
        delete rootThemes[rootId];
      }
      const nextTheme = {
        ...currentTheme,
        rootThemes: Object.keys(rootThemes).length > 0 ? rootThemes : void 0
      };
      return {
        doc: { ...doc3, theme: nextTheme },
        result: { ok: true }
      };
    }
    case "set_theme_root_edge_route": {
      const { rootId, routeType } = command2.payload;
      if (!doc3.roots.includes(rootId)) {
        return { doc: doc3, result: { ok: false, error: `Root not found: ${rootId}` } };
      }
      const currentTheme = ensureDocumentTheme(doc3);
      const rootEdgeRoutes = { ...currentTheme.rootEdgeRoutes ?? {} };
      if (routeType) {
        rootEdgeRoutes[rootId] = routeType;
      } else {
        delete rootEdgeRoutes[rootId];
      }
      const nextTheme = {
        ...currentTheme,
        rootEdgeRoutes: Object.keys(rootEdgeRoutes).length > 0 ? rootEdgeRoutes : void 0
      };
      return {
        doc: { ...doc3, theme: nextTheme },
        result: { ok: true }
      };
    }
    case "set_theme_root_rainbow_enabled": {
      const { rootId, enabled } = command2.payload;
      if (!doc3.roots.includes(rootId)) {
        return { doc: doc3, result: { ok: false, error: `Root not found: ${rootId}` } };
      }
      const currentTheme = ensureDocumentTheme(doc3);
      const rootRainbowEdges = { ...currentTheme.rootRainbowEdges ?? {} };
      if (enabled === null) {
        delete rootRainbowEdges[rootId];
      } else {
        rootRainbowEdges[rootId] = Boolean(enabled);
      }
      const nextTheme = {
        ...currentTheme,
        rootRainbowEdges: Object.keys(rootRainbowEdges).length > 0 ? rootRainbowEdges : void 0
      };
      return {
        doc: { ...doc3, theme: nextTheme },
        result: { ok: true }
      };
    }
    case "set_theme_edge_style_scope": {
      const { nodeId, patch } = command2.payload;
      if (!doc3.nodes[nodeId]) {
        return { doc: doc3, result: { ok: false, error: `Node not found: ${nodeId}` } };
      }
      const currentTheme = ensureDocumentTheme(doc3);
      const edgeStyleScopes = { ...currentTheme.edgeStyleScopes ?? {} };
      if (patch) {
        edgeStyleScopes[nodeId] = patch;
      } else {
        delete edgeStyleScopes[nodeId];
      }
      const nextTheme = {
        ...currentTheme,
        edgeStyleScopes: Object.keys(edgeStyleScopes).length > 0 ? edgeStyleScopes : void 0
      };
      return {
        doc: { ...doc3, theme: nextTheme },
        result: { ok: true }
      };
    }
    case "set_theme_relation_style": {
      const currentTheme = ensureDocumentTheme(doc3);
      const patch = normalizeThemeRelationOverride(command2.payload.patch);
      const nextTheme = {
        ...currentTheme,
        relationStyle: patch
      };
      return { doc: { ...doc3, theme: nextTheme }, result: { ok: true } };
    }
    case "set_theme_root_relation_style": {
      const { rootId } = command2.payload;
      if (!doc3.roots.includes(rootId)) {
        return { doc: doc3, result: { ok: false, error: `Root not found: ${rootId}` } };
      }
      const currentTheme = ensureDocumentTheme(doc3);
      const rootRelationStyles = { ...currentTheme.rootRelationStyles ?? {} };
      const patch = normalizeThemeRelationOverride(command2.payload.patch);
      if (patch) {
        rootRelationStyles[rootId] = patch;
      } else {
        delete rootRelationStyles[rootId];
      }
      const nextTheme = {
        ...currentTheme,
        rootRelationStyles: Object.keys(rootRelationStyles).length > 0 ? rootRelationStyles : void 0
      };
      return { doc: { ...doc3, theme: nextTheme }, result: { ok: true } };
    }
    case "set_theme_appearance": {
      const currentTheme = ensureDocumentTheme(doc3);
      const nextTheme = {
        ...currentTheme,
        appearance: command2.payload.appearance ?? void 0
      };
      return { doc: { ...doc3, theme: nextTheme }, result: { ok: true } };
    }
    case "set_theme_rainbow": {
      const currentTheme = ensureDocumentTheme(doc3);
      const currentRainbow = currentTheme.rainbow ?? { enabled: false, branchColors: {}, paletteOverride: void 0 };
      const paletteOverrideRaw = command2.payload.paletteOverride;
      const wantsClearPaletteOverride = paletteOverrideRaw === null;
      const explicitPalette = Array.isArray(paletteOverrideRaw) ? paletteOverrideRaw : void 0;
      const storedPaletteOverride = !wantsClearPaletteOverride && Array.isArray(currentRainbow.paletteOverride) ? currentRainbow.paletteOverride : void 0;
      const nextPaletteOverride = explicitPalette ?? storedPaletteOverride;
      let nextTheme = {
        ...currentTheme,
        rainbow: {
          ...currentRainbow,
          enabled: Boolean(command2.payload.enabled),
          paletteOverride: nextPaletteOverride,
          branchColors: currentRainbow.branchColors ?? {}
        }
      };
      if (nextTheme.rainbow?.enabled) {
        const variantId = resolveThemeVariantId(currentTheme.appearance, {});
        for (const rootId of doc3.roots) {
          const root = doc3.nodes[rootId];
          if (!root) continue;
          const themeRef = currentTheme.rootThemes?.[rootId] ?? currentTheme.defaultTheme;
          const themeDefinition = resolveThemeDefinition(themeRef, doc3.assets ?? {}) ?? createDefaultThemeDefinition();
          const variant = resolveThemeVariant(themeDefinition, variantId);
          const themePalette = Array.isArray(variant.rainbow?.palette) ? variant.rainbow.palette : void 0;
          const palette = explicitPalette ?? storedPaletteOverride ?? themePalette ?? DEFAULT_RAINBOW_PALETTE;
          for (const childId of root.children) {
            if (!doc3.nodes[childId]) continue;
            nextTheme = ensureRainbowBranchColor(nextTheme, childId, palette);
          }
        }
      }
      return { doc: { ...doc3, theme: nextTheme }, result: { ok: true } };
    }
    case "set_theme_rainbow_branch_color": {
      const { branchId, color } = command2.payload;
      const currentTheme = ensureDocumentTheme(doc3);
      const rainbow = currentTheme.rainbow ?? { enabled: false, branchColors: {}, paletteOverride: void 0 };
      const branchColors = { ...rainbow.branchColors ?? {} };
      if (color) {
        branchColors[branchId] = color;
      } else {
        delete branchColors[branchId];
      }
      const nextTheme = {
        ...currentTheme,
        rainbow: {
          ...rainbow,
          branchColors
        }
      };
      return { doc: { ...doc3, theme: nextTheme }, result: { ok: true } };
    }
    case "set_theme_node_override": {
      const { nodeId, patch } = command2.payload;
      if (!doc3.nodes[nodeId]) {
        return { doc: doc3, result: { ok: false, error: `Node not found: ${nodeId}` } };
      }
      const currentTheme = ensureDocumentTheme(doc3);
      const overrides = { ...currentTheme.overrides ?? {} };
      const nodes = { ...overrides.nodes ?? {} };
      if (patch) {
        nodes[nodeId] = patch;
      } else {
        delete nodes[nodeId];
      }
      overrides.nodes = Object.keys(nodes).length > 0 ? nodes : void 0;
      const nextTheme = {
        ...currentTheme,
        overrides: Object.keys(overrides).length > 0 ? overrides : void 0
      };
      return { doc: { ...doc3, theme: nextTheme }, result: { ok: true } };
    }
    case "upsert_assets": {
      const nextAssets = { ...doc3.assets ?? {}, ...command2.payload.assets };
      return {
        doc: { ...doc3, assets: nextAssets },
        result: { ok: true }
      };
    }
    case "materialize_theme_asset": {
      const currentTheme = ensureDocumentTheme(doc3);
      const assetId = generateUniqueAssetId(doc3.assets ?? {}, idGenerator);
      const asset = { id: assetId, kind: "json", data: command2.payload.theme };
      const nextAssets = { ...doc3.assets ?? {}, [assetId]: asset };
      const themeRef = { source: "asset", assetId };
      let nextTheme = currentTheme;
      if (command2.payload.scope === "document") {
        nextTheme = { ...currentTheme, defaultTheme: themeRef };
      } else {
        if (!doc3.roots.includes(command2.payload.rootId)) {
          return { doc: doc3, result: { ok: false, error: `Root not found: ${command2.payload.rootId}` } };
        }
        const rootThemes = { ...currentTheme.rootThemes ?? {} };
        rootThemes[command2.payload.rootId] = themeRef;
        nextTheme = { ...currentTheme, rootThemes };
      }
      return {
        doc: { ...doc3, assets: nextAssets, theme: nextTheme },
        result: { ok: true, createdAssetId: assetId }
      };
    }
  }
}
function ensureDocumentTheme(doc3) {
  const assets = doc3.assets ?? {};
  const normalized = normalizeThemeState(doc3.theme, assets);
  if (normalized) return normalized;
  return createDefaultDocumentThemeState({
    source: "inline",
    value: createDefaultThemeDefinition()
  });
}
function generateUniqueAssetId(existing, idGenerator) {
  for (let attempt = 0; attempt < 50; attempt += 1) {
    const candidate = idGenerator.generate("asset");
    if (!existing[candidate]) return candidate;
  }
  let counter = 0;
  while (true) {
    const candidate = `${idGenerator.generate("asset")}_${counter}`;
    if (!existing[candidate]) return candidate;
    counter += 1;
  }
}
function rewriteContentIds(content, maps) {
  if (!content) return content;
  if (content.schemaVersion !== 1) return content;
  if (content.kind === "blocks") {
    const nextBlocks = content.blocks.map((block) => {
      if (block.type === "image") {
        const remapped = maps.assetIdMap.get(block.assetId);
        return remapped ? { ...block, assetId: remapped } : block;
      }
      if (block.type === "embed") {
        const assetId = block.embed.assetId;
        if (!assetId) return block;
        const remapped = maps.assetIdMap.get(assetId);
        return remapped ? { ...block, embed: { ...block.embed, assetId: remapped } } : block;
      }
      if (block.type === "links") {
        const nextLinks = block.links.map((link) => {
          if (link.kind !== "internal") return link;
          if (typeof link.docId === "string" && link.docId.trim().length > 0) return link;
          const remapped = maps.nodeIdMap.get(link.nodeId);
          return remapped ? { ...link, nodeId: remapped } : link;
        });
        return { ...block, links: nextLinks };
      }
      return block;
    });
    return { ...content, blocks: nextBlocks };
  }
  return content;
}
function clampIndex(index, length) {
  if (!Number.isFinite(index)) return length;
  return Math.max(0, Math.min(length, Math.trunc(index)));
}
function arraysEqual(a2, b2) {
  if (a2.length !== b2.length) return false;
  for (let index = 0; index < a2.length; index += 1) {
    if (a2[index] !== b2[index]) return false;
  }
  return true;
}
function shouldCanonicalizeTree(command2) {
  switch (command2.type) {
    case "add_child":
    case "add_summary_child":
    case "add_root":
    case "move_root":
    case "delete_node":
    case "insert_subtree":
    case "move_node":
    case "delete_summary":
      return true;
    default:
      return false;
  }
}
function canonicalizeTree(doc3) {
  const normalized = normalizeTree(doc3);
  const rootPositions = seedMissingRootPositions({ roots: normalized.roots, existing: normalized.rootPositions });
  return { ...normalized, rootPositions };
}
function applyCommand(doc3, command2, idGenerator) {
  const out = applyCommandImpl(doc3, command2, idGenerator);
  if (!out.result.ok) return out;
  if (out.doc === doc3) return out;
  if (!shouldCanonicalizeTree(command2)) return out;
  return { ...out, doc: canonicalizeTree(out.doc) };
}
var init_commands = __esm({
  "../core/src/commands.ts"() {
    "use strict";
    init_document();
    init_node_content_width();
    init_theme();
    init_root_positions();
    init_summaries();
    init_pos();
    init_tree();
    init_relations();
  }
});

// ../core/src/id.ts
function createKmindId(prefix, options) {
  const normalizedPrefix = sanitizeKmindIdPrefix(prefix);
  const now = typeof options?.now === "number" && Number.isFinite(options.now) ? options.now : Date.now();
  return `${normalizedPrefix}_${formatUtcTimestamp(now)}_${createUlid(now)}`;
}
function formatUtcTimestamp(now) {
  const date = new Date(now);
  const yyyy = String(date.getUTCFullYear()).padStart(4, "0");
  const MM = String(date.getUTCMonth() + 1).padStart(2, "0");
  const dd = String(date.getUTCDate()).padStart(2, "0");
  const hh = String(date.getUTCHours()).padStart(2, "0");
  const mm = String(date.getUTCMinutes()).padStart(2, "0");
  const ss = String(date.getUTCSeconds()).padStart(2, "0");
  const SSS = String(date.getUTCMilliseconds()).padStart(3, "0");
  return `${yyyy}${MM}${dd}T${hh}${mm}${ss}${SSS}Z`;
}
function createUlid(now) {
  const time = Math.max(0, Math.min(Number.isFinite(now) ? Math.trunc(now) : 0, 281474976710655));
  return `${encodeBase32(time, 10)}${encodeRandomBase32(16)}`;
}
function sanitizeKmindIdPrefix(prefix) {
  const trimmed = String(prefix ?? "").trim();
  const safe = trimmed.replace(/[^a-zA-Z0-9_-]/g, "_").replace(/_+/g, "_").replace(/^_+/, "").replace(/_+$/, "");
  return safe || "id";
}
function encodeBase32(value, length) {
  let remaining = value;
  let out = "";
  for (let i = 0; i < length; i += 1) {
    const mod = remaining % 32;
    out = `${CROCKFORD_BASE32[mod] ?? "0"}${out}`;
    remaining = Math.floor(remaining / 32);
  }
  return out;
}
function encodeRandomBase32(length) {
  const bytes = new Uint8Array(length);
  fillRandomBytes(bytes);
  let out = "";
  for (const byte of bytes) {
    out += CROCKFORD_BASE32[byte & 31] ?? "0";
  }
  return out;
}
function fillRandomBytes(bytes) {
  const cryptoObj = globalThis.crypto;
  if (cryptoObj && typeof cryptoObj.getRandomValues === "function") {
    cryptoObj.getRandomValues(bytes);
    return;
  }
  for (let i = 0; i < bytes.length; i += 1) {
    bytes[i] = Math.floor(Math.random() * 256);
  }
}
var CROCKFORD_BASE32, DefaultIdGenerator;
var init_id = __esm({
  "../core/src/id.ts"() {
    "use strict";
    CROCKFORD_BASE32 = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
    DefaultIdGenerator = class {
      generate(kind) {
        switch (kind) {
          case "node":
            return createKmindId("n");
          case "summary":
            return createKmindId("summary");
          case "relation":
            return createKmindId("rel");
          case "asset":
            return createKmindId("asset");
        }
      }
    };
  }
});

// ../core/src/core.ts
function normalizeDocument(doc3, idGenerator) {
  const rawSummaries = Array.isArray(doc3.summaries) ? doc3.summaries : [];
  const rawRelations = Array.isArray(doc3.relations) ? doc3.relations : [];
  const rawRootPositions = doc3.rootPositions;
  const rawAssets = doc3.assets;
  const rawViewState = doc3.viewState;
  const rawTheme = doc3.theme;
  const rawRoots = Array.isArray(doc3.roots) ? doc3.roots : [];
  const normalizedSummaries = rawSummaries.map((summary) => {
    const children = Array.isArray(summary.children) ? summary.children : [];
    return {
      ...summary,
      children: children.filter((id) => typeof id === "string")
    };
  });
  const normalized = {
    ...doc3,
    summaries: normalizedSummaries,
    relations: rawRelations,
    rootPositions: normalizeRootPositions(rawRootPositions, rawRoots),
    assets: normalizeAssets(rawAssets),
    viewState: normalizeViewState(rawViewState),
    theme: void 0
  };
  const assets = normalized.assets ?? {};
  const normalizedTheme = normalizeThemeState(rawTheme, assets) ?? createDefaultDocumentThemeState({
    source: "inline",
    value: createDefaultThemeDefinition()
  });
  normalized.theme = normalizedTheme;
  const treeNormalized = normalizeTree(normalized);
  const roots = treeNormalized.roots;
  treeNormalized.rootPositions = seedMissingRootPositions({
    roots,
    existing: normalizeRootPositions(treeNormalized.rootPositions, roots)
  });
  treeNormalized.relations = rawRelations.map((relation) => normalizeRelationForDocument(treeNormalized, relation)).filter((relation) => Boolean(relation));
  if (treeNormalized.roots.length > 0) return treeNormalized;
  return createDocument(idGenerator);
}
function normalizeRootPositions(raw, roots) {
  if (!raw || typeof raw !== "object" || Array.isArray(raw)) return {};
  const result = {};
  const rootSet = new Set(roots);
  for (const [key, value] of Object.entries(raw)) {
    if (!rootSet.has(key)) continue;
    if (!value || typeof value !== "object" || Array.isArray(value)) continue;
    const x5 = value.x;
    const y = value.y;
    if (typeof x5 !== "number" || !Number.isFinite(x5)) continue;
    if (typeof y !== "number" || !Number.isFinite(y)) continue;
    result[key] = { x: x5, y };
  }
  return result;
}
function normalizeAssets(raw) {
  if (!raw || typeof raw !== "object" || Array.isArray(raw)) return {};
  const next = {};
  for (const [id, value] of Object.entries(raw)) {
    if (!value || typeof value !== "object" || Array.isArray(value)) continue;
    const kind = value.kind;
    if (kind === "image" || kind === "blob") {
      const mimeType = value.mimeType;
      const dataUrl = value.dataUrl;
      if (typeof mimeType !== "string" || typeof dataUrl !== "string") continue;
      const width = value.width;
      const height = value.height;
      next[id] = {
        ...value,
        id,
        kind,
        mimeType,
        dataUrl,
        width: typeof width === "number" ? width : void 0,
        height: typeof height === "number" ? height : void 0
      };
      continue;
    }
    if (kind === "json") {
      next[id] = {
        ...value,
        id,
        kind: "json"
      };
    }
  }
  return next;
}
function normalizeViewState(raw) {
  if (!raw || typeof raw !== "object" || Array.isArray(raw)) return void 0;
  const result = {};
  const blur2 = raw.blur;
  if (blur2 && typeof blur2 === "object" && !Array.isArray(blur2)) {
    const defaultVisibility = blur2.defaultVisibility;
    if (defaultVisibility === "hidden" || defaultVisibility === "revealed") {
      const nodeOverrides = blur2.nodeOverrides;
      const segmentOverrides = blur2.segmentOverrides;
      result.blur = {
        defaultVisibility,
        nodeOverrides: nodeOverrides && typeof nodeOverrides === "object" && !Array.isArray(nodeOverrides) ? nodeOverrides : void 0,
        segmentOverrides: segmentOverrides && typeof segmentOverrides === "object" && !Array.isArray(segmentOverrides) ? segmentOverrides : void 0
      };
    }
  }
  const collapsedNodeIdsRaw = raw.collapsedNodeIds;
  if (collapsedNodeIdsRaw && typeof collapsedNodeIdsRaw === "object" && !Array.isArray(collapsedNodeIdsRaw)) {
    const collapsedNodeIds = {};
    for (const [id, value] of Object.entries(collapsedNodeIdsRaw)) {
      if (typeof value !== "boolean") continue;
      collapsedNodeIds[id] = value;
    }
    if (Object.keys(collapsedNodeIds).length > 0) {
      result.collapsedNodeIds = collapsedNodeIds;
    }
  }
  return Object.keys(result).length > 0 ? result : void 0;
}
function cloneDocument(doc3) {
  if (typeof structuredClone === "function") {
    return structuredClone(doc3);
  }
  return JSON.parse(JSON.stringify(doc3));
}
var MindMapCore;
var init_core = __esm({
  "../core/src/core.ts"() {
    "use strict";
    init_commands();
    init_id();
    init_document();
    init_theme();
    init_root_positions();
    init_tree();
    init_relations();
    MindMapCore = class {
      id;
      listeners = /* @__PURE__ */ new Set();
      idGenerator;
      state;
      history;
      maxHistory;
      constructor(options = {}) {
        this.id = options.id ?? "kmind";
        this.idGenerator = options.idGenerator ?? new DefaultIdGenerator();
        this.maxHistory = options.maxHistory ?? 200;
        this.history = { past: [], future: [] };
        const initialDocument = options.initialDocument ?? createDocument(this.idGenerator);
        this.state = { document: normalizeDocument(cloneDocument(initialDocument), this.idGenerator) };
      }
      getState() {
        return this.state;
      }
      subscribe(listener) {
        this.listeners.add(listener);
        return () => {
          this.listeners.delete(listener);
        };
      }
      dispatch(command2) {
        if (command2.type === "undo") {
          return this.undo();
        }
        if (command2.type === "redo") {
          return this.redo();
        }
        const currentDoc = this.state.document;
        const { doc: nextDoc, result } = applyCommand(currentDoc, command2, this.idGenerator);
        if (!result.ok) return result;
        if (nextDoc === currentDoc) return result;
        this.pushHistory(currentDoc);
        this.state = {
          ...this.state,
          document: nextDoc
        };
        this.emit();
        return result;
      }
      dispatchBatch(commands) {
        if (!Array.isArray(commands) || commands.length === 0) return { ok: true, results: [] };
        for (const command2 of commands) {
          if (command2.type === "undo" || command2.type === "redo") {
            return { ok: false, error: "dispatchBatch does not support undo/redo commands" };
          }
        }
        const currentDoc = this.state.document;
        let workingDoc = currentDoc;
        const results = [];
        for (const command2 of commands) {
          const { doc: nextDoc, result } = applyCommand(workingDoc, command2, this.idGenerator);
          if (!result.ok) {
            return { ok: false, error: result.error };
          }
          results.push(result);
          workingDoc = nextDoc;
        }
        if (workingDoc !== currentDoc) {
          this.pushHistory(currentDoc);
          this.state = { ...this.state, document: workingDoc };
          this.emit();
        }
        return { ok: true, results };
      }
      toJSON() {
        return cloneDocument(this.state.document);
      }
      fromJSON(doc3) {
        const nextDoc = normalizeDocument(cloneDocument(doc3), this.idGenerator);
        this.history = { past: [], future: [] };
        this.state = { ...this.state, document: nextDoc };
        this.emit();
      }
      getNode(nodeId) {
        return this.state.document.nodes[nodeId];
      }
      canUndo() {
        return this.history.past.length > 0;
      }
      canRedo() {
        return this.history.future.length > 0;
      }
      undo() {
        const previous = this.history.past.pop();
        if (!previous) return { ok: false, error: "Nothing to undo" };
        const current = this.state.document;
        this.history.future.push(current);
        this.state = { ...this.state, document: previous };
        this.emit();
        return { ok: true };
      }
      redo() {
        const next = this.history.future.pop();
        if (!next) return { ok: false, error: "Nothing to redo" };
        const current = this.state.document;
        this.history.past.push(current);
        this.state = { ...this.state, document: next };
        this.emit();
        return { ok: true };
      }
      emit() {
        for (const listener of this.listeners) {
          listener();
        }
      }
      pushHistory(doc3) {
        this.history.past.push(doc3);
        if (this.history.past.length > this.maxHistory) {
          this.history.past.splice(0, this.history.past.length - this.maxHistory);
        }
        this.history.future = [];
      }
    };
  }
});

// ../core/src/blur.ts
function createBlurViewState(args = {}) {
  return {
    revealPersistence: args.revealPersistence ?? "session",
    defaultVisibility: args.defaultVisibility ?? "hidden",
    nodeOverrides: args.nodeOverrides,
    segmentOverrides: args.segmentOverrides
  };
}
function showAllBlur(state) {
  return {
    ...state,
    defaultVisibility: "revealed",
    nodeOverrides: void 0,
    segmentOverrides: void 0
  };
}
function hideAllBlur(state) {
  return {
    ...state,
    defaultVisibility: "hidden",
    nodeOverrides: void 0,
    segmentOverrides: void 0
  };
}
function toggleBlurForNode(state, nodeId) {
  return {
    ...state,
    nodeOverrides: toggleOverride(state.nodeOverrides, nodeId, state.defaultVisibility)
  };
}
function toggleBlurForSegment(state, segmentId) {
  return {
    ...state,
    segmentOverrides: toggleOverride(state.segmentOverrides, segmentId, state.defaultVisibility)
  };
}
function toggleOverride(overrides, id, defaultVisibility) {
  const next = { ...overrides ?? {} };
  const current = next[id];
  if (current) {
    delete next[id];
    return Object.keys(next).length > 0 ? next : void 0;
  }
  next[id] = defaultVisibility === "hidden" ? "revealed" : "hidden";
  return next;
}
var init_blur = __esm({
  "../core/src/blur.ts"() {
    "use strict";
  }
});

// ../core/src/content.ts
function collectSubtreeNodeIds(doc3, startNodeId) {
  const summariesByParent = /* @__PURE__ */ new Map();
  for (const summary of doc3.summaries) {
    const key = String(summary.parentId);
    const list = summariesByParent.get(key);
    if (list) list.push(summary.id);
    else summariesByParent.set(key, [summary.id]);
  }
  const summaryById = new Map(doc3.summaries.map((summary) => [summary.id, summary]));
  const stack = [startNodeId];
  const visited = /* @__PURE__ */ new Set();
  const result = [];
  while (stack.length > 0) {
    const current = stack.pop();
    if (!current) break;
    if (visited.has(current)) continue;
    visited.add(current);
    const node = doc3.nodes[current];
    if (node) {
      result.push(node.id);
      for (const childId of node.children) stack.push(childId);
    }
    const childSummaryIds = summariesByParent.get(current);
    if (childSummaryIds) {
      for (const summaryId of childSummaryIds) stack.push(summaryId);
    }
    const summary = summaryById.get(current);
    if (summary) {
      for (const childId of summary.children) stack.push(childId);
    }
  }
  return result;
}
function getNodeLinks(node) {
  const content = node.content;
  if (!content || content.schemaVersion !== 1) return [];
  if (content.kind === "blocks") {
    const links = [];
    for (const block of content.blocks) {
      if (block.type !== "links") continue;
      links.push(...block.links);
    }
    return links;
  }
  return [];
}
function buildBacklinksIndex(doc3) {
  const backlinks = /* @__PURE__ */ new Map();
  for (const [sourceId, node] of Object.entries(doc3.nodes)) {
    for (const link of getNodeLinks(node)) {
      if (link.kind !== "internal") continue;
      if (typeof link.docId === "string" && link.docId.trim().length > 0) continue;
      const set = backlinks.get(link.nodeId);
      if (set) set.add(sourceId);
      else backlinks.set(link.nodeId, /* @__PURE__ */ new Set([sourceId]));
    }
  }
  const result = {};
  for (const [targetId, sources] of backlinks.entries()) {
    result[targetId] = Array.from(sources).map((nodeId) => ({ nodeId }));
  }
  return result;
}
function getNodeTaskItems(node) {
  const content = node.content;
  if (!content || content.schemaVersion !== 1) return [];
  if (content.kind === "blocks") {
    const items = [];
    for (const block of content.blocks) {
      if (block.type !== "tasks") continue;
      items.push(...block.items);
    }
    return items;
  }
  return [];
}
function collectReferencedAssetIdsFromHtml(html) {
  const ids = /* @__PURE__ */ new Set();
  const raw = typeof html === "string" ? html : "";
  if (!raw.includes(KMIND_ASSET_URL_PREFIX)) return ids;
  const pattern = /kmind-asset:\/\/([A-Za-z0-9._:-]+)/g;
  for (const match of raw.matchAll(pattern)) {
    const assetId = String(match[1] ?? "").trim();
    if (!assetId) continue;
    ids.add(assetId);
  }
  return ids;
}
function collectReferencedAssetIdsFromContent(content) {
  const ids = /* @__PURE__ */ new Set();
  if (!content || content.schemaVersion !== 1) return ids;
  if (content.kind === "richtext") {
    for (const id of collectReferencedAssetIdsFromHtml(content.html)) ids.add(id);
    return ids;
  }
  if (content.kind !== "blocks") return ids;
  for (const block of content.blocks) {
    if (block.type === "image") {
      ids.add(block.assetId);
      continue;
    }
    if (block.type === "embed" && block.embed.assetId) {
      ids.add(block.embed.assetId);
      continue;
    }
    if (block.type === "icons") {
      for (const icon of block.icons) {
        const value = String(icon.value ?? "").trim();
        if (!value.startsWith("kmind-icon://asset/")) continue;
        const assetId = value.slice("kmind-icon://asset/".length).trim() || "";
        if (!assetId) continue;
        ids.add(assetId);
      }
      continue;
    }
    if (block.type === "richtext" || block.type === "notes" && "html" in block) {
      const html = "html" in block ? block.html : void 0;
      for (const id of collectReferencedAssetIdsFromHtml(html)) ids.add(id);
    }
  }
  return ids;
}
function computeTaskStats(doc3, nodeId) {
  const ids = collectSubtreeNodeIds(doc3, nodeId);
  let done = 0;
  let total = 0;
  for (const id of ids) {
    const node = doc3.nodes[id];
    if (!node) continue;
    for (const item of getNodeTaskItems(node)) {
      total += 1;
      if (item.checked) done += 1;
    }
  }
  return {
    done,
    total,
    ratio: total > 0 ? done / total : 0
  };
}
var KMIND_ASSET_URL_PREFIX;
var init_content = __esm({
  "../core/src/content.ts"() {
    "use strict";
    KMIND_ASSET_URL_PREFIX = "kmind-asset://";
  }
});

// ../core/src/compact-document.ts
var init_compact_document = __esm({
  "../core/src/compact-document.ts"() {
    "use strict";
    init_theme();
    init_summaries();
    init_relations();
  }
});

// ../core/src/layout/logical-right.ts
var init_logical_right = __esm({
  "../core/src/layout/logical-right.ts"() {
    "use strict";
  }
});

// ../core/src/layout/tree-down.ts
var init_tree_down = __esm({
  "../core/src/layout/tree-down.ts"() {
    "use strict";
  }
});

// ../core/src/layout/mindmap-legacy.ts
function resolveRootOptions(options, rootId) {
  const rootOptions = options.rootOptions?.[rootId];
  if (!rootOptions) return options;
  return {
    ...options,
    horizontalGap: rootOptions.horizontalGap ?? options.horizontalGap,
    verticalGap: rootOptions.verticalGap ?? options.verticalGap
  };
}
function normalizeLegacyLayoutType(layoutType) {
  if (layoutType === "mindmap-both" || layoutType === "mindmap-both-auto") return "logical-right";
  if (layoutType === "timeline-right") return "logical-right";
  if (layoutType === "timeline-down") return "tree-down";
  if (layoutType === "fishbone-left") return "logical-right";
  if (layoutType === "fishbone-right") return "logical-left";
  return layoutType;
}
function layoutMindMapLegacy(doc3, nodeSizes, summarySizes, options = {}) {
  const resolvedOptions = {
    horizontalGap: options.horizontalGap ?? defaultOptions.horizontalGap,
    verticalGap: options.verticalGap ?? defaultOptions.verticalGap,
    rootGap: options.rootGap ?? defaultOptions.rootGap,
    rootOptions: options.rootOptions,
    engine: options.engine ?? defaultOptions.engine,
    tidy: {
      logicalAlign: options.tidy?.logicalAlign ?? defaultOptions.tidy.logicalAlign,
      packing: options.tidy?.packing ?? defaultOptions.tidy.packing,
      edgeClearance: options.tidy?.edgeClearance ?? defaultOptions.tidy.edgeClearance
    }
  };
  const nodeLayouts = {};
  const edges = [];
  const summaries = {};
  const rootPositions = doc3.rootPositions ?? {};
  let yCursor = 0;
  for (const rootId of doc3.roots) {
    const rootNode = doc3.nodes[rootId];
    if (!rootNode) continue;
    const rootLayout = layoutRoot({
      doc: doc3,
      rootId,
      nodeSizes,
      summarySizes,
      options: resolveRootOptions(resolvedOptions, rootId)
    });
    const anchored = rootPositions[rootId];
    const rootNodeLayout = rootLayout.nodes[rootId];
    if (anchored && rootNodeLayout) {
      const dx = anchored.x - rootNodeLayout.x;
      const dy = anchored.y - rootNodeLayout.y;
      mergeTranslatedLayout(nodeLayouts, edges, summaries, rootLayout, dx, dy);
      continue;
    }
    mergeTranslatedLayout(nodeLayouts, edges, summaries, rootLayout, 0, yCursor);
    yCursor += rootLayout.bounds.height + resolvedOptions.rootGap;
  }
  const relations = layoutRelations(doc3, nodeLayouts, summaries);
  const bounds = computeBounds(nodeLayouts, Object.values(summaries));
  return {
    nodes: nodeLayouts,
    edges,
    summaries,
    relations,
    bounds
  };
}
function mergeTranslatedLayout(nodeLayouts, edges, summaries, rootLayout, dx, dy) {
  for (const [nodeId, layout] of Object.entries(rootLayout.nodes)) {
    nodeLayouts[nodeId] = {
      ...layout,
      x: layout.x + dx,
      y: layout.y + dy
    };
  }
  for (const edge of rootLayout.edges) {
    edges.push({
      ...edge,
      path: translatePath(edge.path, dx, dy)
    });
  }
  for (const [summaryId, layout] of Object.entries(rootLayout.summaries)) {
    summaries[summaryId] = {
      ...layout,
      x: layout.x + dx,
      y: layout.y + dy,
      bracketPath: translatePath(layout.bracketPath, dx, dy)
    };
  }
}
function translatePath(path2, dx, dy) {
  if (!path2) return path2;
  let coordIndex = 0;
  return path2.replace(/-?\d*\.?\d+/g, (match) => {
    const value = Number(match);
    const next = coordIndex % 2 === 0 ? value + dx : value + dy;
    coordIndex += 1;
    return String(next);
  });
}
function layoutSummaries(doc3, nodes, sizes, options, existingSummaries, processedSummaryIds) {
  const summaries = { ...existingSummaries };
  const created = {};
  const subtreeRightEdgeMemo = /* @__PURE__ */ new Map();
  const subtreeLeftEdgeMemo = /* @__PURE__ */ new Map();
  const subtreeTopEdgeMemo = /* @__PURE__ */ new Map();
  const subtreeBottomEdgeMemo = /* @__PURE__ */ new Map();
  const summarySubtreeRightEdgeMemo = /* @__PURE__ */ new Map();
  const summarySubtreeLeftEdgeMemo = /* @__PURE__ */ new Map();
  const summaryById = new Map(doc3.summaries.map((summary) => [summary.id, summary]));
  const summariesByParent = /* @__PURE__ */ new Map();
  for (const summary of doc3.summaries) {
    const bucket = summariesByParent.get(summary.parentId);
    if (bucket) bucket.push(summary.id);
    else summariesByParent.set(summary.parentId, [summary.id]);
  }
  const layoutMemo = /* @__PURE__ */ new Map();
  const depthMemo = /* @__PURE__ */ new Map();
  const resolveLayoutType = (id, visited) => {
    const cached = layoutMemo.get(id);
    if (cached) return cached;
    if (visited.has(id)) return "logical-right";
    visited.add(id);
    const node = doc3.nodes[id];
    if (node) {
      let inherited = "logical-right";
      if (node.parentId) inherited = resolveLayoutType(node.parentId, visited);
      else if (node.parentSummaryId) inherited = resolveLayoutType(node.parentSummaryId, visited);
      const resolved = normalizeLegacyLayoutType(node.layout ?? inherited);
      layoutMemo.set(id, resolved);
      return resolved;
    }
    const summary = summaryById.get(id);
    if (summary) {
      let inherited = "logical-right";
      const parentId = summary.parentId;
      if (doc3.nodes[parentId]) inherited = resolveLayoutType(parentId, visited);
      else inherited = resolveLayoutType(parentId, visited);
      const resolved = normalizeLegacyLayoutType(summary.layout ?? inherited);
      layoutMemo.set(id, resolved);
      return resolved;
    }
    return "logical-right";
  };
  const resolveContainerDepth = (id, visited) => {
    const cached = depthMemo.get(id);
    if (cached !== void 0) return cached;
    if (visited.has(id)) return 0;
    visited.add(id);
    const node = doc3.nodes[id];
    if (node) {
      const parent = node.parentId ?? node.parentSummaryId;
      const depth = parent ? resolveContainerDepth(String(parent), visited) + 1 : 0;
      depthMemo.set(id, depth);
      visited.delete(id);
      return depth;
    }
    const summary = summaryById.get(id);
    if (summary) {
      const depth = resolveContainerDepth(String(summary.parentId), visited) + 1;
      depthMemo.set(id, depth);
      visited.delete(id);
      return depth;
    }
    visited.delete(id);
    depthMemo.set(id, 0);
    return 0;
  };
  const computeSummarySubtreeRightEdge = (summaryId) => {
    const cached = summarySubtreeRightEdgeMemo.get(summaryId);
    if (cached !== void 0) return cached;
    const layout = summaries[summaryId];
    if (!layout) {
      summarySubtreeRightEdgeMemo.set(summaryId, Number.NEGATIVE_INFINITY);
      return Number.NEGATIVE_INFINITY;
    }
    let maxX = layout.x + layout.width;
    const summary = summaryById.get(summaryId);
    if (summary) {
      for (const childId of summary.children) {
        if (!doc3.nodes[childId]) continue;
        if (!nodes[childId]) continue;
        maxX = Math.max(maxX, computeSubtreeRightEdge(childId));
      }
    }
    const nested = summariesByParent.get(summaryId) ?? [];
    for (const nestedId of nested) {
      maxX = Math.max(maxX, computeSummarySubtreeRightEdge(nestedId));
    }
    summarySubtreeRightEdgeMemo.set(summaryId, maxX);
    return maxX;
  };
  const computeSummarySubtreeLeftEdge = (summaryId) => {
    const cached = summarySubtreeLeftEdgeMemo.get(summaryId);
    if (cached !== void 0) return cached;
    const layout = summaries[summaryId];
    if (!layout) {
      summarySubtreeLeftEdgeMemo.set(summaryId, Number.POSITIVE_INFINITY);
      return Number.POSITIVE_INFINITY;
    }
    let minX = layout.x;
    const summary = summaryById.get(summaryId);
    if (summary) {
      for (const childId of summary.children) {
        if (!doc3.nodes[childId]) continue;
        if (!nodes[childId]) continue;
        minX = Math.min(minX, computeSubtreeLeftEdge(childId));
      }
    }
    const nested = summariesByParent.get(summaryId) ?? [];
    for (const nestedId of nested) {
      minX = Math.min(minX, computeSummarySubtreeLeftEdge(nestedId));
    }
    summarySubtreeLeftEdgeMemo.set(summaryId, minX);
    return minX;
  };
  const computeSubtreeRightEdge = (nodeId) => {
    const cached = subtreeRightEdgeMemo.get(nodeId);
    if (cached !== void 0) return cached;
    const node = doc3.nodes[nodeId];
    const layout = nodes[nodeId];
    if (!node || !layout) {
      subtreeRightEdgeMemo.set(nodeId, Number.NEGATIVE_INFINITY);
      return Number.NEGATIVE_INFINITY;
    }
    let maxX = layout.x + layout.width;
    for (const childId of node.children) {
      if (!doc3.nodes[childId]) continue;
      maxX = Math.max(maxX, computeSubtreeRightEdge(childId));
    }
    const nestedSummaries = summariesByParent.get(nodeId) ?? [];
    for (const summaryId of nestedSummaries) {
      maxX = Math.max(maxX, computeSummarySubtreeRightEdge(summaryId));
    }
    subtreeRightEdgeMemo.set(nodeId, maxX);
    return maxX;
  };
  const computeSubtreeLeftEdge = (nodeId) => {
    const cached = subtreeLeftEdgeMemo.get(nodeId);
    if (cached !== void 0) return cached;
    const node = doc3.nodes[nodeId];
    const layout = nodes[nodeId];
    if (!node || !layout) {
      subtreeLeftEdgeMemo.set(nodeId, Number.POSITIVE_INFINITY);
      return Number.POSITIVE_INFINITY;
    }
    let minX = layout.x;
    for (const childId of node.children) {
      if (!doc3.nodes[childId]) continue;
      minX = Math.min(minX, computeSubtreeLeftEdge(childId));
    }
    const nestedSummaries = summariesByParent.get(nodeId) ?? [];
    for (const summaryId of nestedSummaries) {
      minX = Math.min(minX, computeSummarySubtreeLeftEdge(summaryId));
    }
    subtreeLeftEdgeMemo.set(nodeId, minX);
    return minX;
  };
  const computeSubtreeTopEdge = (nodeId) => {
    const cached = subtreeTopEdgeMemo.get(nodeId);
    if (cached !== void 0) return cached;
    const node = doc3.nodes[nodeId];
    const layout = nodes[nodeId];
    if (!node || !layout) {
      subtreeTopEdgeMemo.set(nodeId, Number.POSITIVE_INFINITY);
      return Number.POSITIVE_INFINITY;
    }
    let minY = layout.y;
    for (const childId of node.children) {
      if (!doc3.nodes[childId]) continue;
      minY = Math.min(minY, computeSubtreeTopEdge(childId));
    }
    subtreeTopEdgeMemo.set(nodeId, minY);
    return minY;
  };
  const computeSubtreeBottomEdge = (nodeId) => {
    const cached = subtreeBottomEdgeMemo.get(nodeId);
    if (cached !== void 0) return cached;
    const node = doc3.nodes[nodeId];
    const layout = nodes[nodeId];
    if (!node || !layout) {
      subtreeBottomEdgeMemo.set(nodeId, Number.NEGATIVE_INFINITY);
      return Number.NEGATIVE_INFINITY;
    }
    let maxY = layout.y + layout.height;
    for (const childId of node.children) {
      if (!doc3.nodes[childId]) continue;
      maxY = Math.max(maxY, computeSubtreeBottomEdge(childId));
    }
    subtreeBottomEdgeMemo.set(nodeId, maxY);
    return maxY;
  };
  const candidates = doc3.summaries.filter((summary) => !processedSummaryIds.has(summary.id)).slice().sort((a2, b2) => {
    const aDepth = resolveContainerDepth(String(a2.parentId), /* @__PURE__ */ new Set());
    const bDepth = resolveContainerDepth(String(b2.parentId), /* @__PURE__ */ new Set());
    if (aDepth !== bDepth) return bDepth - aDepth;
    return a2.id.localeCompare(b2.id);
  });
  for (const summary of candidates) {
    const childLayouts = summary.childIds.map((id) => nodes[id]).filter((layout2) => Boolean(layout2));
    if (childLayouts.length === 0) continue;
    const childTopEdges = summary.childIds.map((id) => computeSubtreeTopEdge(id)).filter((edge) => edge !== Number.POSITIVE_INFINITY);
    const childBottomEdges = summary.childIds.map((id) => computeSubtreeBottomEdge(id)).filter((edge) => edge !== Number.NEGATIVE_INFINITY);
    if (childTopEdges.length === 0 || childBottomEdges.length === 0) continue;
    const minY = Math.min(...childTopEdges);
    const maxY = Math.max(...childBottomEdges);
    const size = sizes[summary.id] ?? { width: 160, height: 56 };
    const centerY = (minY + maxY) / 2;
    const parentLayout = resolveLayoutType(String(summary.parentId), /* @__PURE__ */ new Set());
    const isLeft = parentLayout === "logical-left";
    const bracketGap = Math.max(16, Math.floor(options.horizontalGap / 2));
    const tickLen = Math.max(6, Math.min(18, bracketGap - 6));
    const bracketTick = isLeft ? tickLen : -tickLen;
    const summaryGap = tickLen + 14;
    const summaryY = centerY - size.height / 2;
    if (isLeft) {
      const childLeftEdges = summary.childIds.map((id) => computeSubtreeLeftEdge(id)).filter((edge) => edge !== Number.POSITIVE_INFINITY);
      if (childLeftEdges.length === 0) continue;
      const minX = Math.min(...childLeftEdges);
      const bracketX2 = minX - bracketGap;
      const computedSummaryX2 = bracketX2 - summaryGap - size.width;
      const bracketPath2 = [
        `M ${bracketX2} ${minY}`,
        `L ${bracketX2 + bracketTick} ${minY}`,
        `M ${bracketX2} ${minY}`,
        `L ${bracketX2} ${maxY}`,
        `M ${bracketX2} ${maxY}`,
        `L ${bracketX2 + bracketTick} ${maxY}`
      ].join(" ");
      const layout2 = {
        id: summary.id,
        x: computedSummaryX2,
        y: summaryY,
        width: size.width,
        height: size.height,
        bracketPath: bracketPath2,
        parentId: summary.parentId,
        childIds: summary.childIds
      };
      summaries[summary.id] = layout2;
      created[summary.id] = layout2;
      continue;
    }
    const childRightEdges = summary.childIds.map((id) => computeSubtreeRightEdge(id)).filter((edge) => edge !== Number.NEGATIVE_INFINITY);
    if (childRightEdges.length === 0) continue;
    const maxX = Math.max(...childRightEdges);
    const bracketX = maxX + bracketGap;
    const computedSummaryX = bracketX + summaryGap;
    const bracketPath = [
      `M ${bracketX} ${minY}`,
      `L ${bracketX + bracketTick} ${minY}`,
      `M ${bracketX} ${minY}`,
      `L ${bracketX} ${maxY}`,
      `M ${bracketX} ${maxY}`,
      `L ${bracketX + bracketTick} ${maxY}`
    ].join(" ");
    const layout = {
      id: summary.id,
      x: computedSummaryX,
      y: summaryY,
      width: size.width,
      height: size.height,
      bracketPath,
      parentId: summary.parentId,
      childIds: summary.childIds
    };
    summaries[summary.id] = layout;
    created[summary.id] = layout;
  }
  return created;
}
function layoutRelations(doc3, nodes, summaries) {
  const result = [];
  for (const rel2 of doc3.relations) {
    const from2 = rel2.from.kind === "summary" ? summaries[rel2.from.summaryId] : nodes[rel2.from.nodeId];
    const to = rel2.to.kind === "summary" ? summaries[rel2.to.summaryId] : nodes[rel2.to.nodeId];
    if (!from2 || !to) continue;
    const start = resolvePortPoint(from2, relationEndpointPort(rel2.from) ?? "right", relationEndpointPortRatio(rel2.from));
    const end = resolvePortPoint(to, relationEndpointPort(rel2.to) ?? "left", relationEndpointPortRatio(rel2.to));
    const dx = end.x - start.x;
    const dy = end.y - start.y;
    const curve = Math.max(40, Math.min(220, Math.abs(dx) / 2));
    const defaultControl1 = { x: Math.sign(dx || 1) * curve, y: 0 };
    const defaultControl2 = { x: -Math.sign(dx || 1) * curve, y: 0 };
    const curveV1 = rel2.curve?.schemaVersion === 1 && rel2.curve.kind === "cubic" ? rel2.curve : null;
    const control1 = curveV1?.control1 ?? defaultControl1;
    const control2 = curveV1?.control2 ?? defaultControl2;
    const c1 = { x: start.x + control1.x, y: start.y + control1.y };
    const c2 = { x: end.x + control2.x, y: end.y + control2.y };
    const path2 = `M ${start.x} ${start.y} C ${c1.x} ${c1.y}, ${c2.x} ${c2.y}, ${end.x} ${end.y}`;
    const labelText = rel2.label?.schemaVersion === 1 && rel2.label.kind === "plain-text" ? rel2.label.text : "";
    const label = (() => {
      const text5 = labelText.trim();
      if (text5.length === 0) return void 0;
      const mid = cubicAtHalf(start, c1, c2, end);
      return { text: text5, x: mid.x, y: mid.y };
    })();
    result.push({
      id: rel2.id,
      from: rel2.from,
      to: rel2.to,
      path: path2,
      label,
      style: rel2.style
    });
  }
  return result;
}
function resolvePortPoint(layout, port, portRatio) {
  const ratio = (() => {
    const next = Number(portRatio);
    if (!Number.isFinite(next)) return 0.5;
    return Math.max(0, Math.min(1, next));
  })();
  switch (port) {
    case "top":
      return { x: layout.x + layout.width * ratio, y: layout.y };
    case "bottom":
      return { x: layout.x + layout.width * ratio, y: layout.y + layout.height };
    case "left":
      return { x: layout.x, y: layout.y + layout.height * ratio };
    case "right":
    default:
      return { x: layout.x + layout.width, y: layout.y + layout.height * ratio };
  }
}
function cubicAtHalf(p0, p1, p2, p3) {
  return {
    x: (p0.x + 3 * p1.x + 3 * p2.x + p3.x) / 8,
    y: (p0.y + 3 * p1.y + 3 * p2.y + p3.y) / 8
  };
}
function computeBounds(nodes, summaries) {
  const layouts = [
    ...Object.values(nodes),
    ...summaries
  ];
  if (layouts.length === 0) {
    return { minX: 0, minY: 0, maxX: 0, maxY: 0, width: 0, height: 0 };
  }
  let minX = Number.POSITIVE_INFINITY;
  let minY = Number.POSITIVE_INFINITY;
  let maxX = Number.NEGATIVE_INFINITY;
  let maxY = Number.NEGATIVE_INFINITY;
  for (const layout of layouts) {
    minX = Math.min(minX, layout.x);
    minY = Math.min(minY, layout.y);
    maxX = Math.max(maxX, layout.x + layout.width);
    maxY = Math.max(maxY, layout.y + layout.height);
  }
  return {
    minX,
    minY,
    maxX,
    maxY,
    width: maxX - minX,
    height: maxY - minY
  };
}
function layoutRoot(args) {
  const { doc: doc3, rootId, nodeSizes, summarySizes, options } = args;
  const nodes = {};
  const edges = [];
  const resolvedLayoutByNode = /* @__PURE__ */ new Map();
  const subtreeSizeMemo = /* @__PURE__ */ new Map();
  const childBeforePaddingMemo = /* @__PURE__ */ new Map();
  const summarySubtreeSizeMemo = /* @__PURE__ */ new Map();
  const summariesByParent = /* @__PURE__ */ new Map();
  for (const summary of doc3.summaries) {
    const bucket = summariesByParent.get(summary.parentId);
    if (bucket) {
      bucket.push(summary);
    } else {
      summariesByParent.set(summary.parentId, [summary]);
    }
  }
  const resolveLayout = (inherited, override) => {
    return normalizeLegacyLayoutType(override ?? inherited);
  };
  const isNodeCollapsed = (nodeId) => {
    return doc3.viewState?.collapsedNodeIds?.[nodeId] === true;
  };
  const computeSummarySubtreeSize = (summary, inheritedLayout) => {
    const memoKey = `${summary.id}::${inheritedLayout}`;
    const memoized = summarySubtreeSizeMemo.get(memoKey);
    if (memoized) return memoized;
    const summarySize = summarySizes[summary.id] ?? defaultNodeSize;
    const layoutType = resolveLayout(inheritedLayout, summary.layout);
    const childIds = summary.children.filter((id) => Boolean(doc3.nodes[id]));
    if (childIds.length === 0) {
      summarySubtreeSizeMemo.set(memoKey, summarySize);
      return summarySize;
    }
    const childSizes = childIds.map((childId) => computeSubtreeSize(childId, layoutType));
    if (layoutType === "tree-down" || layoutType === "tree-up") {
      const childrenTotalWidth = childSizes.reduce((sum, child) => sum + child.width, 0) + options.horizontalGap * (childIds.length - 1);
      const width2 = Math.max(summarySize.width, childrenTotalWidth);
      const childrenMaxHeight = Math.max(...childSizes.map((child) => child.height));
      const height2 = summarySize.height + options.verticalGap + childrenMaxHeight;
      const subtree2 = { width: width2, height: height2 };
      summarySubtreeSizeMemo.set(memoKey, subtree2);
      return subtree2;
    }
    const beforePadding = computeChildrenBeforePadding(summary.id, layoutType, childIds, childSizes);
    const paddingTotal = beforePadding.reduce((sum, value) => sum + value, 0);
    const childrenTotalHeight = childSizes.reduce((sum, child) => sum + child.height, 0) + options.verticalGap * (childIds.length - 1) + paddingTotal;
    const height = Math.max(summarySize.height, childrenTotalHeight);
    const childrenMaxWidth = Math.max(...childSizes.map((child) => child.width));
    const width = summarySize.width + options.horizontalGap + childrenMaxWidth;
    const subtree = { width, height };
    summarySubtreeSizeMemo.set(memoKey, subtree);
    return subtree;
  };
  const computeChildrenBeforePadding = (parentId, parentLayout, childIds, childSizes) => {
    const before = new Array(childIds.length + 1).fill(0);
    if (parentLayout === "tree-down" || parentLayout === "tree-up") return before;
    const summaries2 = summariesByParent.get(parentId);
    if (!summaries2 || summaries2.length === 0) return before;
    const count = childIds.length;
    if (count === 0) return before;
    const topPad = new Array(count).fill(0);
    const bottomPad = new Array(count).fill(0);
    const indexById = new Map(childIds.map((id, index) => [id, index]));
    for (const summary of summaries2) {
      const indices = summary.childIds.map((id) => indexById.get(id)).filter((index) => index !== void 0);
      if (indices.length === 0) continue;
      const startIndex = Math.min(...indices);
      const endIndex = Math.max(...indices);
      if (startIndex < 0 || endIndex >= childIds.length) continue;
      let rangeHeight = 0;
      for (let index = startIndex; index <= endIndex; index += 1) {
        rangeHeight += childSizes[index]?.height ?? 0;
      }
      rangeHeight += options.verticalGap * (endIndex - startIndex);
      const summarySubtreeHeight = computeSummarySubtreeSize(summary, parentLayout).height;
      const extraHeight = Math.max(0, summarySubtreeHeight - rangeHeight);
      if (extraHeight <= 0) continue;
      const padTop = extraHeight / 2;
      const padBottom = extraHeight - padTop;
      topPad[startIndex] = Math.max(topPad[startIndex] ?? 0, padTop);
      bottomPad[endIndex] = Math.max(bottomPad[endIndex] ?? 0, padBottom);
    }
    before[0] = topPad[0] ?? 0;
    for (let index = 1; index < count; index += 1) {
      before[index] = (bottomPad[index - 1] ?? 0) + (topPad[index] ?? 0);
    }
    before[count] = bottomPad[count - 1] ?? 0;
    return before;
  };
  const computeSubtreeSize = (nodeId, inheritedLayout) => {
    const key = `${nodeId}::${inheritedLayout}`;
    const cached = subtreeSizeMemo.get(key);
    if (cached) return cached;
    const node = doc3.nodes[nodeId];
    if (!node) {
      const empty2 = { width: 0, height: 0 };
      subtreeSizeMemo.set(key, empty2);
      return empty2;
    }
    const size = nodeSizes[nodeId] ?? defaultNodeSize;
    const layoutType = resolveLayout(inheritedLayout, node.layout);
    const childIds = isNodeCollapsed(nodeId) ? [] : node.children.filter((id) => Boolean(doc3.nodes[id]));
    if (childIds.length === 0) {
      subtreeSizeMemo.set(key, size);
      return size;
    }
    const childSizes = childIds.map((childId) => computeSubtreeSize(childId, layoutType));
    if (layoutType === "tree-down" || layoutType === "tree-up") {
      const childrenTotalWidth = childSizes.reduce((sum, child) => sum + child.width, 0) + options.horizontalGap * (childIds.length - 1);
      const width2 = Math.max(size.width, childrenTotalWidth);
      const childrenMaxHeight = Math.max(...childSizes.map((child) => child.height));
      const height2 = size.height + options.verticalGap + childrenMaxHeight;
      const subtree2 = { width: width2, height: height2 };
      subtreeSizeMemo.set(key, subtree2);
      return subtree2;
    }
    const beforePadding = computeChildrenBeforePadding(nodeId, layoutType, childIds, childSizes);
    childBeforePaddingMemo.set(key, beforePadding);
    const paddingTotal = beforePadding.reduce((sum, value) => sum + value, 0);
    const childrenTotalHeight = childSizes.reduce((sum, child) => sum + child.height, 0) + options.verticalGap * (childIds.length - 1) + paddingTotal;
    const height = Math.max(size.height, childrenTotalHeight);
    const childrenMaxWidth = Math.max(...childSizes.map((child) => child.width));
    const width = size.width + options.horizontalGap + childrenMaxWidth;
    const subtree = { width, height };
    subtreeSizeMemo.set(key, subtree);
    return subtree;
  };
  const layoutNodeSubtree = (nodeId, x5, y, inheritedLayout) => {
    const node = doc3.nodes[nodeId];
    if (!node) return { width: 0, height: 0 };
    const size = nodeSizes[nodeId] ?? defaultNodeSize;
    const layoutType = resolveLayout(inheritedLayout, node.layout);
    resolvedLayoutByNode.set(nodeId, layoutType);
    const childIds = isNodeCollapsed(nodeId) ? [] : node.children.filter((id) => Boolean(doc3.nodes[id]));
    if (childIds.length === 0) {
      nodes[nodeId] = { x: x5, y, width: size.width, height: size.height };
      return size;
    }
    const subtree = computeSubtreeSize(nodeId, inheritedLayout);
    const isTree = layoutType === "tree-down" || layoutType === "tree-up";
    const isUp = layoutType === "tree-up";
    const isLeft = layoutType === "logical-left";
    if (isTree) {
      const subtreeWidth = subtree.width;
      const nodeX2 = x5 + (subtreeWidth - size.width) / 2;
      const childSizes2 = childIds.map((childId) => computeSubtreeSize(childId, layoutType));
      const childrenTotalWidth = childSizes2.reduce((sum, child) => sum + child.width, 0) + options.horizontalGap * (childIds.length - 1);
      const childrenMaxHeight = Math.max(...childSizes2.map((child) => child.height));
      const nodeY2 = isUp ? y + childrenMaxHeight + options.verticalGap : y;
      nodes[nodeId] = { x: nodeX2, y: nodeY2, width: size.width, height: size.height };
      const fromLayout2 = nodes[nodeId];
      let childXCursor = x5 + (subtreeWidth - childrenTotalWidth) / 2;
      for (let index = 0; index < childIds.length; index += 1) {
        const childId = childIds[index];
        const childSize = childSizes2[index];
        const childY = isUp ? y + (childrenMaxHeight - childSize.height) : y + size.height + options.verticalGap;
        layoutNodeSubtree(childId, childXCursor, childY, layoutType);
        const toLayout = nodes[childId];
        if (toLayout) {
          edges.push({
            id: `${nodeId}->${childId}`,
            from: nodeId,
            to: childId,
            path: createCubicPathVertical(fromLayout2, toLayout)
          });
        }
        childXCursor += childSize.width + options.horizontalGap;
      }
      return subtree;
    }
    const childSizes = childIds.map((childId) => computeSubtreeSize(childId, layoutType));
    const key = `${nodeId}::${inheritedLayout}`;
    const beforePadding = childBeforePaddingMemo.get(key) ?? new Array(childIds.length + 1).fill(0);
    const paddingTotal = beforePadding.reduce((sum, value) => sum + value, 0);
    const childrenTotalHeight = childSizes.reduce((sum, child) => sum + child.height, 0) + options.verticalGap * (childIds.length - 1) + paddingTotal;
    const childrenStartY = childrenTotalHeight >= size.height ? y : y + (size.height - childrenTotalHeight) / 2;
    const nodeY = childrenTotalHeight >= size.height ? y + (childrenTotalHeight - size.height) / 2 : y;
    const nodeX = isLeft ? x5 + (subtree.width - size.width) : x5;
    nodes[nodeId] = { x: nodeX, y: nodeY, width: size.width, height: size.height };
    const fromLayout = nodes[nodeId];
    let childYCursor = childrenStartY + beforePadding[0];
    for (let index = 0; index < childIds.length; index += 1) {
      const childId = childIds[index];
      const childSize = childSizes[index];
      const childX = isLeft ? nodeX - options.horizontalGap - childSize.width : nodeX + size.width + options.horizontalGap;
      layoutNodeSubtree(childId, childX, childYCursor, layoutType);
      const toLayout = nodes[childId];
      if (toLayout) {
        edges.push({
          id: `${nodeId}->${childId}`,
          from: nodeId,
          to: childId,
          path: createCubicPathHorizontal(fromLayout, toLayout)
        });
      }
      childYCursor += childSize.height;
      if (index < childIds.length - 1) {
        childYCursor += options.verticalGap + beforePadding[index + 1];
      }
    }
    return subtree;
  };
  layoutNodeSubtree(rootId, 0, 0, "logical-right");
  const summaries = {};
  const summaryById = new Map(doc3.summaries.map((summary) => [summary.id, summary]));
  const processedSummaryIds = /* @__PURE__ */ new Set();
  let progress = true;
  while (progress) {
    progress = false;
    const nextSummaryLayouts = layoutSummaries(doc3, nodes, summarySizes, options, summaries, processedSummaryIds);
    for (const summaryLayout of Object.values(nextSummaryLayouts)) {
      if (processedSummaryIds.has(summaryLayout.id)) continue;
      processedSummaryIds.add(summaryLayout.id);
      summaries[summaryLayout.id] = summaryLayout;
      const summary = summaryById.get(summaryLayout.id);
      if (!summary) continue;
      const inheritedLayout = resolvedLayoutByNode.get(summary.parentId) ?? "logical-right";
      const layoutType = resolveLayout(inheritedLayout, summary.layout);
      resolvedLayoutByNode.set(summary.id, layoutType);
      const childIds = summary.children.filter((childId) => Boolean(doc3.nodes[childId]));
      if (childIds.length === 0) {
        progress = true;
        continue;
      }
      const isTree = layoutType === "tree-down" || layoutType === "tree-up";
      const isUp = layoutType === "tree-up";
      const isLeft = layoutType === "logical-left";
      if (isTree) {
        const childSizes = childIds.map((childId) => computeSubtreeSize(childId, layoutType));
        const childrenTotalWidth = childSizes.reduce((sum, child) => sum + child.width, 0) + options.horizontalGap * (childIds.length - 1);
        const childrenMaxHeight = Math.max(...childSizes.map((child) => child.height));
        let childXCursor = summaryLayout.x + summaryLayout.width / 2 - childrenTotalWidth / 2;
        const childTop = isUp ? summaryLayout.y - options.verticalGap - childrenMaxHeight : summaryLayout.y + summaryLayout.height + options.verticalGap;
        for (let index = 0; index < childIds.length; index += 1) {
          const childId = childIds[index];
          const childSize = childSizes[index];
          const childY = isUp ? childTop + (childrenMaxHeight - childSize.height) : childTop;
          layoutNodeSubtree(childId, childXCursor, childY, layoutType);
          const toLayout = nodes[childId];
          if (toLayout) {
            edges.push({
              id: `summary:${summary.id}->${childId}`,
              from: summary.id,
              to: childId,
              path: createCubicPathVertical(summaryLayout, toLayout)
            });
          }
          childXCursor += childSize.width + options.horizontalGap;
        }
      } else {
        const childSizes = childIds.map((childId) => computeSubtreeSize(childId, layoutType));
        const beforePadding = computeChildrenBeforePadding(summary.id, layoutType, childIds, childSizes);
        const paddingTotal = beforePadding.reduce((sum, value) => sum + value, 0);
        const childrenTotalHeight = childSizes.reduce((sum, child) => sum + child.height, 0) + options.verticalGap * (childIds.length - 1) + paddingTotal;
        const centerY = summaryLayout.y + summaryLayout.height / 2;
        const childrenStartY = centerY - childrenTotalHeight / 2;
        let childYCursor = childrenStartY + beforePadding[0];
        for (let index = 0; index < childIds.length; index += 1) {
          const childId = childIds[index];
          const childSize = childSizes[index];
          const childX = isLeft ? summaryLayout.x - options.horizontalGap - childSize.width : summaryLayout.x + summaryLayout.width + options.horizontalGap;
          layoutNodeSubtree(childId, childX, childYCursor, layoutType);
          const toLayout = nodes[childId];
          if (toLayout) {
            edges.push({
              id: `summary:${summary.id}->${childId}`,
              from: summary.id,
              to: childId,
              path: createCubicPathHorizontal(summaryLayout, toLayout)
            });
          }
          childYCursor += childSize.height;
          if (index < childIds.length - 1) {
            childYCursor += options.verticalGap + beforePadding[index + 1];
          }
        }
      }
      progress = true;
    }
  }
  expandLegacySummaryBracketRanges(doc3, nodes, summaries);
  let bounds = computeBounds(nodes, Object.values(summaries));
  const dx = bounds.minX < 0 ? -bounds.minX : 0;
  const dy = bounds.minY < 0 ? -bounds.minY : 0;
  if (dx !== 0 || dy !== 0) {
    for (const layout of Object.values(nodes)) {
      layout.x += dx;
      layout.y += dy;
    }
    for (const edge of edges) {
      edge.path = translatePath(edge.path, dx, dy);
    }
    for (const summary of Object.values(summaries)) {
      summary.x += dx;
      summary.y += dy;
      summary.bracketPath = translatePath(summary.bracketPath, dx, dy);
    }
    bounds = computeBounds(nodes, Object.values(summaries));
  }
  return { nodes, edges, summaries, bounds };
}
function expandLegacySummaryBracketRanges(doc3, nodes, summaries) {
  if (doc3.summaries.length === 0) return;
  const summaryById = new Map(doc3.summaries.map((summary) => [summary.id, summary]));
  const summariesByParent = /* @__PURE__ */ new Map();
  for (const summary of doc3.summaries) {
    const list = summariesByParent.get(summary.parentId);
    if (list) list.push(summary.id);
    else summariesByParent.set(summary.parentId, [summary.id]);
  }
  for (const [summaryId, summaryLayout] of Object.entries(summaries)) {
    const summary = summaryById.get(summaryId);
    if (!summary) continue;
    const bracket = parseLegacyBracketPath(summaryLayout.bracketPath);
    if (!bracket) continue;
    const range = computeVisualSubtreeYRange({
      startNodeIds: summary.childIds,
      doc: doc3,
      nodes,
      summaries,
      summariesByParent,
      summaryById
    });
    if (!range) continue;
    summaryLayout.bracketPath = buildLegacyBracketPath(bracket.bracketX, bracket.tickDelta, range.minY, range.maxY);
  }
}
function parseLegacyBracketPath(path2) {
  const match = path2.match(/M\s+(-?\d*\.?\d+)\s+(-?\d*\.?\d+)\s+L\s+(-?\d*\.?\d+)\s+(-?\d*\.?\d+)/);
  if (!match) return null;
  const bracketX = Number(match[1]);
  const tickX = Number(match[3]);
  if (!Number.isFinite(bracketX) || !Number.isFinite(tickX)) return null;
  return { bracketX, tickDelta: tickX - bracketX };
}
function buildLegacyBracketPath(bracketX, tickDelta, minY, maxY) {
  return [
    `M ${bracketX} ${minY}`,
    `L ${bracketX + tickDelta} ${minY}`,
    `M ${bracketX} ${minY}`,
    `L ${bracketX} ${maxY}`,
    `M ${bracketX} ${maxY}`,
    `L ${bracketX + tickDelta} ${maxY}`
  ].join(" ");
}
function computeVisualSubtreeYRange(args) {
  const { startNodeIds, doc: doc3, nodes, summaries, summariesByParent, summaryById } = args;
  const visited = /* @__PURE__ */ new Set();
  const stack = [...startNodeIds];
  let minY = Number.POSITIVE_INFINITY;
  let maxY = Number.NEGATIVE_INFINITY;
  while (stack.length > 0) {
    const current = stack.pop();
    if (!current) break;
    if (visited.has(current)) continue;
    visited.add(current);
    const node = doc3.nodes[current];
    if (node) {
      const layout = nodes[current];
      if (layout) {
        minY = Math.min(minY, layout.y);
        maxY = Math.max(maxY, layout.y + layout.height);
      }
      for (const childId of node.children) {
        if (!doc3.nodes[childId]) continue;
        stack.push(childId);
      }
      const attached2 = summariesByParent.get(node.id);
      if (attached2) {
        for (const summaryId of attached2) {
          stack.push(summaryId);
        }
      }
      continue;
    }
    const summary = summaryById.get(current);
    if (!summary) continue;
    const summaryLayout = summaries[summary.id];
    if (summaryLayout) {
      minY = Math.min(minY, summaryLayout.y);
      maxY = Math.max(maxY, summaryLayout.y + summaryLayout.height);
    }
    for (const childId of summary.children) {
      if (!doc3.nodes[childId]) continue;
      stack.push(childId);
    }
    const attached = summariesByParent.get(summary.id);
    if (attached) {
      for (const summaryId of attached) {
        stack.push(summaryId);
      }
    }
  }
  if (!Number.isFinite(minY) || !Number.isFinite(maxY)) return null;
  return { minY, maxY };
}
function createCubicPathHorizontal(from2, to) {
  const fromCx = from2.x + from2.width / 2;
  const toCx = to.x + to.width / 2;
  const goRight = toCx >= fromCx;
  const startX = goRight ? from2.x + from2.width : from2.x;
  const startY = from2.y + from2.height / 2;
  const endX = goRight ? to.x : to.x + to.width;
  const endY = to.y + to.height / 2;
  const c1X = startX + (goRight ? 40 : -40);
  const c1Y = startY;
  const c2X = endX + (goRight ? -40 : 40);
  const c2Y = endY;
  return `M ${startX} ${startY} C ${c1X} ${c1Y}, ${c2X} ${c2Y}, ${endX} ${endY}`;
}
function createCubicPathVertical(from2, to) {
  const startX = from2.x + from2.width / 2;
  const fromCy = from2.y + from2.height / 2;
  const toCy = to.y + to.height / 2;
  const goDown = toCy >= fromCy;
  const startY = goDown ? from2.y + from2.height : from2.y;
  const endX = to.x + to.width / 2;
  const endY = goDown ? to.y : to.y + to.height;
  const c1X = startX;
  const c1Y = startY + (goDown ? 40 : -40);
  const c2X = endX;
  const c2Y = endY + (goDown ? -40 : 40);
  return `M ${startX} ${startY} C ${c1X} ${c1Y}, ${c2X} ${c2Y}, ${endX} ${endY}`;
}
var defaultOptions, defaultNodeSize;
var init_mindmap_legacy = __esm({
  "../core/src/layout/mindmap-legacy.ts"() {
    "use strict";
    init_relations();
    defaultOptions = {
      horizontalGap: 80,
      verticalGap: 20,
      rootGap: 60,
      engine: "legacy",
      tidy: {
        logicalAlign: "level",
        packing: "relaxed",
        edgeClearance: 0
      }
    };
    defaultNodeSize = { width: 160, height: 56 };
  }
});

// ../core/src/layout/mindmap-tidy.ts
function resolveRootOptions2(options, rootId) {
  const rootOptions = options.rootOptions?.[rootId];
  if (!rootOptions) return options;
  return {
    ...options,
    horizontalGap: rootOptions.horizontalGap ?? options.horizontalGap,
    verticalGap: rootOptions.verticalGap ?? options.verticalGap
  };
}
function nextCacheUse() {
  tidyLayoutCacheClock += 1;
  return tidyLayoutCacheClock;
}
function resolvedOptionsSignature(options) {
  return [
    options.horizontalGap,
    options.verticalGap,
    options.rootGap,
    options.tidy.logicalAlign,
    options.tidy.packing,
    options.tidy.edgeClearance
  ].join(":");
}
function sizeSignature(size) {
  const next = size ?? defaultNodeSize2;
  return `${next.width}x${next.height}`;
}
function hashSignatureParts(parts) {
  let hash = 2166136261;
  for (const part of parts) {
    const text5 = String(part ?? "");
    for (let index = 0; index < text5.length; index += 1) {
      hash ^= text5.charCodeAt(index);
      hash = Math.imul(hash, 16777619);
    }
    hash ^= 31;
    hash = Math.imul(hash, 16777619);
  }
  return (hash >>> 0).toString(36);
}
function readCached(cacheMap, key, signature) {
  const cached = cacheMap?.get(key);
  if (!cached || cached.signature !== signature) return null;
  cached.usedAt = nextCacheUse();
  return cached.value;
}
function writeCached(cache, cacheMap, key, signature, value) {
  if (!cache || !cacheMap) return;
  cacheMap.set(key, { signature, value, usedAt: nextCacheUse() });
  pruneTidyCache(cache);
}
function pruneTidyCache(cache) {
  const maxEntries = Math.max(1e3, cache.maxEntries ?? DEFAULT_TIDY_LAYOUT_CACHE_MAX_ENTRIES);
  const total = cache.rootSubtrees.size + cache.nodeSubtrees.size + cache.summarySubtrees.size;
  if (total <= maxEntries) return;
  const entries = [];
  const collect = (map2) => {
    for (const [key, value] of map2.entries()) entries.push({ map: map2, key, usedAt: value.usedAt });
  };
  collect(cache.rootSubtrees);
  collect(cache.nodeSubtrees);
  collect(cache.summarySubtrees);
  entries.sort((a2, b2) => a2.usedAt - b2.usedAt);
  const targetEntries = Math.max(0, Math.floor(maxEntries * TIDY_LAYOUT_CACHE_PRUNE_TARGET_RATIO));
  const removeCount = Math.max(1, total - targetEntries);
  for (let index = 0; index < removeCount; index += 1) {
    const entry = entries[index];
    if (entry) entry.map.delete(entry.key);
  }
}
function layoutMindMapTidy(doc3, nodeSizes, summarySizes, options = {}) {
  const resolvedOptions = {
    ...defaultOptions2,
    ...options,
    engine: "tidy",
    tidy: {
      logicalAlign: options.tidy?.logicalAlign ?? defaultOptions2.tidy.logicalAlign,
      packing: options.tidy?.packing ?? defaultOptions2.tidy.packing,
      edgeClearance: options.tidy?.edgeClearance ?? defaultOptions2.tidy.edgeClearance,
      cache: options.tidy?.cache
    }
  };
  const nodeLayouts = {};
  const edges = [];
  const summaries = {};
  const rootPositions = doc3.rootPositions ?? {};
  let yCursor = 0;
  for (const rootId of doc3.roots) {
    const rootNode = doc3.nodes[rootId];
    if (!rootNode) continue;
    const rootLayout = layoutRootWithTidyFallback({
      doc: doc3,
      rootId,
      nodeSizes,
      summarySizes,
      options: resolveRootOptions2(resolvedOptions, rootId)
    });
    const anchored = rootPositions[rootId];
    const rootNodeLayout = rootLayout.nodes[rootId];
    if (anchored && rootNodeLayout) {
      const dx = anchored.x - rootNodeLayout.x;
      const dy = anchored.y - rootNodeLayout.y;
      mergeTranslatedLayout2(nodeLayouts, edges, summaries, rootLayout, dx, dy);
      continue;
    }
    mergeTranslatedLayout2(nodeLayouts, edges, summaries, rootLayout, 0, yCursor);
    yCursor += rootLayout.bounds.height + resolvedOptions.rootGap;
  }
  const relations = layoutRelations2(doc3, nodeLayouts, summaries);
  const bounds = computeBounds2(nodeLayouts, Object.values(summaries));
  return {
    nodes: nodeLayouts,
    edges,
    summaries,
    relations,
    bounds
  };
}
function layoutRootWithTidyFallback(args) {
  const rootNode = args.doc.nodes[args.rootId];
  const rootLayout = rootNode?.layout;
  const enableFallback = rootLayout === void 0 || rootLayout === "logical-right" || rootLayout === "logical-left" || rootLayout === "mindmap-both" || rootLayout === "mindmap-both-auto";
  if (!enableFallback) {
    return layoutRoot2(args);
  }
  if (!KMIND_TIDY_USE_LEGACY_GLOBAL_EDGE_AVOIDANCE) {
    return layoutRoot2(args);
  }
  const maxPasses = 4;
  const maxVerticalGap = 160;
  const maxEdgeClearance = 48;
  let options = args.options;
  let last = null;
  for (let pass = 0; pass < maxPasses; pass += 1) {
    const layout = layoutRoot2({ ...args, options });
    last = layout;
    if (!hasTidyEdgeNodeIntersections(layout)) {
      return layout;
    }
    options = {
      ...options,
      verticalGap: Math.min(maxVerticalGap, options.verticalGap + 8),
      tidy: {
        ...options.tidy,
        edgeClearance: Math.min(maxEdgeClearance, options.tidy.edgeClearance + 2)
      }
    };
  }
  return last ?? layoutRoot2(args);
}
function layoutRoot2(args) {
  const { doc: doc3, rootId, nodeSizes, summarySizes, options } = args;
  const summariesByParent = /* @__PURE__ */ new Map();
  for (const summary of doc3.summaries) {
    const bucket = summariesByParent.get(summary.parentId);
    if (bucket) bucket.push(summary);
    else summariesByParent.set(summary.parentId, [summary]);
  }
  const summaryById = new Map(doc3.summaries.map((summary) => [summary.id, summary]));
  const summaryIdsByParent = /* @__PURE__ */ new Map();
  for (const [parentId, items] of summariesByParent.entries()) {
    summaryIdsByParent.set(String(parentId), items.map((item) => item.id));
  }
  const resolveLayout = (inherited, override) => {
    if (override) return override;
    if (inherited === "mindmap-both" || inherited === "mindmap-both-auto") return "logical-right";
    if (inherited === "fishbone-left") return "logical-right";
    if (inherited === "fishbone-right") return "logical-left";
    return inherited;
  };
  const translateSubtree = (subtree2, dx2, dy2) => {
    const nextNodes = {};
    const nextSummaries = {};
    const nextEdges = [];
    for (const [nodeId, layout] of Object.entries(subtree2.nodes)) {
      nextNodes[nodeId] = { ...layout, x: layout.x + dx2, y: layout.y + dy2 };
    }
    for (const [summaryId, layout] of Object.entries(subtree2.summaries)) {
      nextSummaries[summaryId] = {
        ...layout,
        x: layout.x + dx2,
        y: layout.y + dy2,
        bracketPath: translatePath2(layout.bracketPath, dx2, dy2)
      };
    }
    for (const edge of subtree2.edges) {
      nextEdges.push({ ...edge, path: translatePath2(edge.path, dx2, dy2) });
    }
    return {
      nodes: nextNodes,
      summaries: nextSummaries,
      edges: nextEdges,
      bounds: {
        minX: subtree2.bounds.minX + dx2,
        minY: subtree2.bounds.minY + dy2,
        maxX: subtree2.bounds.maxX + dx2,
        maxY: subtree2.bounds.maxY + dy2,
        width: subtree2.bounds.width,
        height: subtree2.bounds.height
      }
    };
  };
  const mergeInto = (target2, source) => {
    Object.assign(target2.nodes, source.nodes);
    Object.assign(target2.summaries, source.summaries);
    target2.edges.push(...source.edges);
    target2.bounds = unionBounds(target2.bounds, source.bounds);
  };
  const isNodeCollapsed = (nodeId) => {
    return doc3.viewState?.collapsedNodeIds?.[nodeId] === true;
  };
  const visibleSubtreeNodeCountMemo = /* @__PURE__ */ new Map();
  const countVisibleSubtreeNodes = (startNodeId) => {
    const cached = visibleSubtreeNodeCountMemo.get(startNodeId);
    if (cached !== void 0) return cached;
    const stack = [startNodeId];
    const visited = /* @__PURE__ */ new Set();
    let count = 0;
    while (stack.length > 0) {
      const current = stack.pop();
      if (!current) break;
      if (visited.has(current)) continue;
      visited.add(current);
      const node = doc3.nodes[current];
      if (node) {
        count += 1;
        const collapsed = isNodeCollapsed(node.id);
        if (!collapsed) {
          for (const childId of node.children) {
            if (!doc3.nodes[childId]) continue;
            stack.push(childId);
          }
          const summaryIds = summaryIdsByParent.get(node.id);
          if (summaryIds) {
            for (const summaryId of summaryIds) stack.push(summaryId);
          }
        }
      }
      const summary = summaryById.get(current);
      if (summary) {
        for (const childId of summary.children) {
          if (!doc3.nodes[childId]) continue;
          stack.push(childId);
        }
        const summaryIds = summaryIdsByParent.get(summary.id);
        if (summaryIds) {
          for (const summaryId of summaryIds) stack.push(summaryId);
        }
      }
    }
    visibleSubtreeNodeCountMemo.set(startNodeId, count);
    return count;
  };
  const mindmapBothAutoSideCache = /* @__PURE__ */ new Map();
  const resolveMindmapBothAutoSide = (containerId, childId) => {
    const child = doc3.nodes[childId];
    if (child?.branchSide === "left") return "left";
    if (child?.branchSide === "right") return "right";
    let cached = mindmapBothAutoSideCache.get(containerId);
    if (!cached) {
      const container = doc3.nodes[containerId];
      const mapping = {};
      if (container) {
        let leftTotal = 0;
        let rightTotal = 0;
        const weightByChild = /* @__PURE__ */ new Map();
        const getWeight = (id) => {
          const existing = weightByChild.get(id);
          if (existing !== void 0) return existing;
          const weight = countVisibleSubtreeNodes(id);
          weightByChild.set(id, weight);
          return weight;
        };
        for (const id of container.children) {
          const node = doc3.nodes[id];
          if (!node) continue;
          const weight = getWeight(id);
          if (node.branchSide === "left") {
            mapping[id] = "left";
            leftTotal += weight;
          } else if (node.branchSide === "right") {
            mapping[id] = "right";
            rightTotal += weight;
          }
        }
        let tieFlip = "right";
        for (const id of container.children) {
          if (!doc3.nodes[id]) continue;
          if (mapping[id]) continue;
          const weight = getWeight(id);
          const side = leftTotal < rightTotal ? "left" : rightTotal < leftTotal ? "right" : tieFlip = tieFlip === "left" ? "right" : "left";
          mapping[id] = side;
          if (side === "left") leftTotal += weight;
          else rightTotal += weight;
        }
      }
      cached = mapping;
      mindmapBothAutoSideCache.set(containerId, cached);
    }
    return cached[childId] ?? "right";
  };
  const cache = options.tidy.cache;
  const layoutOptionsKey = resolvedOptionsSignature(options);
  const nodeSignatureMemo = /* @__PURE__ */ new Map();
  const summarySignatureMemo = /* @__PURE__ */ new Map();
  function resolveNodeLayoutType(nodeId, inheritedLayout) {
    const node = doc3.nodes[nodeId];
    if (!node) return inheritedLayout;
    if (node.layout) return node.layout;
    if (inheritedLayout === "mindmap-both") return node.branchSide === "left" ? "logical-left" : "logical-right";
    if (inheritedLayout === "mindmap-both-auto") {
      const parentId = node.parentId;
      if (!parentId) return "logical-right";
      return resolveMindmapBothAutoSide(parentId, nodeId) === "left" ? "logical-left" : "logical-right";
    }
    if (inheritedLayout === "fishbone-left") return "logical-right";
    if (inheritedLayout === "fishbone-right") return "logical-left";
    return inheritedLayout;
  }
  function buildNodeSubtreeSignature(nodeId, inheritedLayout) {
    const memoKey = `${nodeId}|${inheritedLayout}`;
    const memo2 = nodeSignatureMemo.get(memoKey);
    if (memo2) return memo2;
    const node = doc3.nodes[nodeId];
    if (!node) {
      const missing = `missing-node:${nodeId}`;
      nodeSignatureMemo.set(memoKey, missing);
      return missing;
    }
    const layoutType = resolveNodeLayoutType(nodeId, inheritedLayout);
    const childIds = isNodeCollapsed(nodeId) ? [] : node.children.filter((id) => Boolean(doc3.nodes[id]));
    const attachedSummaryIds = (summariesByParent.get(nodeId) ?? []).map((summary) => summary.id);
    const signature = hashSignatureParts([
      "node",
      node.id,
      layoutType,
      node.branchSide ?? "",
      isNodeCollapsed(nodeId) ? "collapsed" : "expanded",
      sizeSignature(nodeSizes[nodeId]),
      childIds.join(","),
      hashSignatureParts(childIds.map((childId) => buildNodeSubtreeSignature(childId, layoutType))),
      attachedSummaryIds.join(","),
      hashSignatureParts(attachedSummaryIds.map((summaryId) => buildSummarySubtreeSignature(summaryId, layoutType)))
    ]);
    nodeSignatureMemo.set(memoKey, signature);
    return signature;
  }
  function buildSummarySubtreeSignature(summaryId, inheritedLayout) {
    const memoKey = `${summaryId}|${inheritedLayout}`;
    const memo2 = summarySignatureMemo.get(memoKey);
    if (memo2) return memo2;
    const summary = summaryById.get(summaryId);
    if (!summary) {
      const missing = `missing-summary:${summaryId}`;
      summarySignatureMemo.set(memoKey, missing);
      return missing;
    }
    const layoutType = resolveLayout(inheritedLayout, summary.layout);
    const childIds = summary.children.filter((id) => Boolean(doc3.nodes[id]));
    const attachedSummaryIds = (summariesByParent.get(summaryId) ?? []).map((childSummary) => childSummary.id);
    const signature = hashSignatureParts([
      "summary",
      summary.id,
      String(summary.parentId),
      layoutType,
      sizeSignature(summarySizes[summaryId]),
      summary.childIds.filter((id) => Boolean(doc3.nodes[id])).join(","),
      childIds.join(","),
      hashSignatureParts(childIds.map((childId) => buildNodeSubtreeSignature(childId, layoutType))),
      attachedSummaryIds.join(","),
      hashSignatureParts(attachedSummaryIds.map((childSummaryId) => buildSummarySubtreeSignature(childSummaryId, layoutType)))
    ]);
    summarySignatureMemo.set(memoKey, signature);
    return signature;
  }
  const layoutSummarySubtree = (summaryId, inheritedLayout) => {
    const summary = summaryById.get(summaryId);
    if (!summary) return emptySubtree();
    const signature = buildSummarySubtreeSignature(summaryId, inheritedLayout);
    const cacheKey = `${layoutOptionsKey}|summary|${summaryId}|${inheritedLayout}`;
    const cached = readCached(cache?.summarySubtrees, cacheKey, signature);
    if (cached) return cached;
    const size = summarySizes[summaryId] ?? defaultNodeSize2;
    const layoutType = resolveLayout(inheritedLayout, summary.layout);
    const childIds = summary.children.filter((id) => Boolean(doc3.nodes[id]));
    const attachedSummaries = summariesByParent.get(summaryId) ?? [];
    const root = {
      id: summaryId,
      x: 0,
      y: 0,
      width: size.width,
      height: size.height,
      bracketPath: "",
      parentId: summary.parentId,
      childIds: summary.childIds
    };
    const subtree2 = {
      nodes: {},
      summaries: { [summaryId]: root },
      edges: [],
      bounds: computeBounds2({}, [root])
    };
    if (childIds.length === 0) {
      subtree2.bounds = computeBounds2(subtree2.nodes, Object.values(subtree2.summaries));
      writeCached(cache, cache?.summarySubtrees, cacheKey, signature, subtree2);
      return subtree2;
    }
    const children = layoutChildrenBlocks({
      doc: doc3,
      containerId: summaryId,
      containerKind: "summary",
      layoutType,
      containerSize: size,
      childIds,
      attachedSummaries,
      inheritedLayout: layoutType,
      nodeSizes,
      summarySizes,
      summariesByParent,
      resolveLayout,
      layoutNodeSubtree,
      layoutSummarySubtree,
      resolveMindmapBothAutoSide,
      options
    });
    mergeInto(subtree2, children.subtree);
    const fromLayout = subtree2.summaries[summaryId];
    if (fromLayout) {
      for (const childId of childIds) {
        const toLayout = subtree2.nodes[childId];
        if (!toLayout) continue;
        subtree2.edges.push({
          id: `summary:${summaryId}->${childId}`,
          from: summaryId,
          to: childId,
          path: layoutType === "tree-down" || layoutType === "tree-up" ? createCubicPathVertical2(fromLayout, toLayout) : createCubicPathHorizontal2(fromLayout, toLayout)
        });
      }
    }
    subtree2.bounds = computeBounds2(subtree2.nodes, Object.values(subtree2.summaries));
    writeCached(cache, cache?.summarySubtrees, cacheKey, signature, subtree2);
    return subtree2;
  };
  const layoutNodeSubtree = (nodeId, inheritedLayout) => {
    const node = doc3.nodes[nodeId];
    if (!node) return emptySubtree();
    const signature = buildNodeSubtreeSignature(nodeId, inheritedLayout);
    const cacheKey = `${layoutOptionsKey}|node|${nodeId}|${inheritedLayout}`;
    const cached = readCached(cache?.nodeSubtrees, cacheKey, signature);
    if (cached) return cached;
    const size = nodeSizes[nodeId] ?? defaultNodeSize2;
    const layoutType = resolveNodeLayoutType(nodeId, inheritedLayout);
    const childIds = isNodeCollapsed(nodeId) ? [] : node.children.filter((id) => Boolean(doc3.nodes[id]));
    const attachedSummaries = summariesByParent.get(nodeId) ?? [];
    const subtree2 = {
      nodes: {
        [nodeId]: { x: 0, y: 0, width: size.width, height: size.height }
      },
      summaries: {},
      edges: [],
      bounds: computeBounds2({ [nodeId]: { x: 0, y: 0, width: size.width, height: size.height } }, [])
    };
    if (childIds.length === 0) {
      subtree2.bounds = computeBounds2(subtree2.nodes, Object.values(subtree2.summaries));
      writeCached(cache, cache?.nodeSubtrees, cacheKey, signature, subtree2);
      return subtree2;
    }
    const children = layoutChildrenBlocks({
      doc: doc3,
      containerId: nodeId,
      containerKind: "node",
      layoutType,
      containerSize: size,
      childIds,
      attachedSummaries,
      inheritedLayout: layoutType,
      nodeSizes,
      summarySizes,
      summariesByParent,
      resolveLayout,
      layoutNodeSubtree,
      layoutSummarySubtree,
      resolveMindmapBothAutoSide,
      options
    });
    mergeInto(subtree2, children.subtree);
    const fromLayout = subtree2.nodes[nodeId];
    if (fromLayout) {
      for (const childId of childIds) {
        const toLayout = subtree2.nodes[childId];
        if (!toLayout) continue;
        subtree2.edges.push({
          id: `${nodeId}->${childId}`,
          from: nodeId,
          to: childId,
          path: layoutType === "tree-down" || layoutType === "tree-up" ? createCubicPathVertical2(fromLayout, toLayout) : createCubicPathHorizontal2(fromLayout, toLayout)
        });
      }
    }
    subtree2.bounds = computeBounds2(subtree2.nodes, Object.values(subtree2.summaries));
    writeCached(cache, cache?.nodeSubtrees, cacheKey, signature, subtree2);
    return subtree2;
  };
  const rootSignature = buildNodeSubtreeSignature(rootId, "logical-right");
  const rootCacheKey = `${layoutOptionsKey}|root|${rootId}`;
  const cachedRoot = readCached(cache?.rootSubtrees, rootCacheKey, rootSignature);
  if (cachedRoot) return cachedRoot;
  let subtree = layoutNodeSubtree(rootId, "logical-right");
  const dx = subtree.bounds.minX < 0 ? -subtree.bounds.minX : 0;
  const dy = subtree.bounds.minY < 0 ? -subtree.bounds.minY : 0;
  if (dx !== 0 || dy !== 0) {
    subtree = translateSubtree(subtree, dx, dy);
  }
  subtree.bounds = computeBounds2(subtree.nodes, Object.values(subtree.summaries));
  const result = { nodes: subtree.nodes, edges: subtree.edges, summaries: subtree.summaries, bounds: subtree.bounds };
  writeCached(cache, cache?.rootSubtrees, rootCacheKey, rootSignature, result);
  return result;
}
function layoutChildrenBlocks(args) {
  const {
    doc: doc3,
    layoutType,
    containerSize,
    childIds,
    attachedSummaries,
    nodeSizes,
    summarySizes,
    resolveLayout,
    layoutNodeSubtree,
    layoutSummarySubtree,
    options
  } = args;
  const isTree = layoutType === "tree-down" || layoutType === "tree-up";
  const isUp = layoutType === "tree-up";
  const isLeft = layoutType === "logical-left";
  const childSubtrees = childIds.map((childId) => layoutNodeSubtree(childId, layoutType));
  if (layoutType === "mindmap-both" || layoutType === "mindmap-both-auto") {
    const leftChildIds = [];
    const leftChildSubtrees = [];
    const rightChildIds = [];
    const rightChildSubtrees = [];
    const sideByChildId = /* @__PURE__ */ new Map();
    for (let index = 0; index < childIds.length; index += 1) {
      const childId = childIds[index];
      const node = doc3.nodes[childId];
      const side = layoutType === "mindmap-both-auto" && args.containerKind === "node" && args.resolveMindmapBothAutoSide ? args.resolveMindmapBothAutoSide(args.containerId, childId) : node?.branchSide === "left" ? "left" : "right";
      sideByChildId.set(childId, side);
      const childSubtree = childSubtrees[index];
      if (side === "left") {
        leftChildIds.push(childId);
        leftChildSubtrees.push(childSubtree);
      } else {
        rightChildIds.push(childId);
        rightChildSubtrees.push(childSubtree);
      }
    }
    const subtree2 = emptySubtree();
    const leftSummaries = [];
    const rightSummaries = [];
    for (const summary of attachedSummaries) {
      const sides = summary.childIds.map((id) => sideByChildId.get(id)).filter((value) => Boolean(value));
      if (sides.length !== summary.childIds.length) continue;
      const uniqueSides = new Set(sides);
      if (uniqueSides.size !== 1) continue;
      const onlySide = uniqueSides.has("left") ? "left" : "right";
      if (onlySide === "left") leftSummaries.push(summary);
      else rightSummaries.push(summary);
    }
    const layoutSide = (sideLayout, ids, subtrees, summaries) => {
      if (ids.length === 0) return;
      const indexById2 = new Map(ids.map((id, index) => [id, index]));
      const summaryRanges2 = summaries.map((summary) => {
        const indices = summary.childIds.map((id) => indexById2.get(id)).filter((index) => index !== void 0);
        if (indices.length !== summary.childIds.length) return null;
        if (indices.length === 0) return null;
        return {
          summary,
          startIndex: Math.min(...indices),
          endIndex: Math.max(...indices)
        };
      }).filter((range) => Boolean(range)).sort((a2, b2) => a2.startIndex !== b2.startIndex ? a2.startIndex - b2.startIndex : a2.endIndex - b2.endIndex);
      const mergedIntervals2 = [];
      for (const range of summaryRanges2) {
        const last = mergedIntervals2.at(-1);
        if (!last) {
          mergedIntervals2.push({ startIndex: range.startIndex, endIndex: range.endIndex });
          continue;
        }
        if (range.startIndex <= last.endIndex) {
          last.endIndex = Math.max(last.endIndex, range.endIndex);
          continue;
        }
        mergedIntervals2.push({ startIndex: range.startIndex, endIndex: range.endIndex });
      }
      const blocks2 = [];
      let cursor2 = 0;
      for (const interval of mergedIntervals2) {
        while (cursor2 < interval.startIndex) {
          blocks2.push(
            buildBlock({
              childIds: ids,
              childSubtrees: subtrees,
              summaryRanges: summaryRanges2,
              summarySizes,
              resolveLayout,
              layoutType: sideLayout,
              layoutSummarySubtree,
              options,
              startIndex: cursor2,
              endIndex: cursor2
            })
          );
          cursor2 += 1;
        }
        blocks2.push(
          buildBlock({
            childIds: ids,
            childSubtrees: subtrees,
            summaryRanges: summaryRanges2,
            summarySizes,
            resolveLayout,
            layoutType: sideLayout,
            layoutSummarySubtree,
            options,
            startIndex: interval.startIndex,
            endIndex: interval.endIndex
          })
        );
        cursor2 = interval.endIndex + 1;
      }
      while (cursor2 < ids.length) {
        blocks2.push(
          buildBlock({
            childIds: ids,
            childSubtrees: subtrees,
            summaryRanges: summaryRanges2,
            summarySizes,
            resolveLayout,
            layoutType: sideLayout,
            layoutSummarySubtree,
            options,
            startIndex: cursor2,
            endIndex: cursor2
          })
        );
        cursor2 += 1;
      }
      const stacked2 = stackBlocks(blocks2, "y", options.verticalGap, options.tidy.packing);
      const alignBounds2 = (() => {
        if (options.tidy.logicalAlign !== "level") return stacked2.bounds;
        let combined = emptyBounds();
        for (let index = 0; index < blocks2.length; index += 1) {
          const block = blocks2[index];
          const offset = stacked2.offsets[index];
          combined = unionBounds(combined, translateBounds(block.focusBounds, 0, offset));
        }
        return combined;
      })();
      const alignShift2 = containerSize.height / 2 - (alignBounds2.minY + alignBounds2.maxY) / 2;
      const placeLeft = sideLayout === "logical-left";
      for (let index = 0; index < blocks2.length; index += 1) {
        const block = blocks2[index];
        const offset = stacked2.offsets[index];
        const dx = placeLeft ? -options.horizontalGap - block.bounds.maxX : containerSize.width + options.horizontalGap - block.bounds.minX;
        const dy = alignShift2 + offset;
        mergeTranslatedLayout2(subtree2.nodes, subtree2.edges, subtree2.summaries, {
          nodes: block.subtree.nodes,
          edges: block.subtree.edges,
          summaries: block.subtree.summaries,
          bounds: block.subtree.bounds
        }, dx, dy);
      }
    };
    layoutSide("logical-right", rightChildIds, rightChildSubtrees, rightSummaries);
    layoutSide("logical-left", leftChildIds, leftChildSubtrees, leftSummaries);
    subtree2.bounds = computeBounds2(subtree2.nodes, Object.values(subtree2.summaries));
    return { subtree: subtree2 };
  }
  if (layoutType === "timeline-right" || layoutType === "timeline-down") {
    const subtree2 = emptySubtree();
    if (childIds.length === 0) return { subtree: subtree2 };
    if (layoutType === "timeline-right") {
      const centerY = containerSize.height / 2;
      let xCursor = containerSize.width + options.horizontalGap;
      for (let index = 0; index < childIds.length; index += 1) {
        const childId = childIds[index];
        const child = childSubtrees[index];
        const root = child.nodes[childId];
        const rootCenterY = root ? root.y + root.height / 2 : 0;
        const dy = centerY - rootCenterY;
        const dx = xCursor - child.bounds.minX;
        mergeTranslatedLayout2(subtree2.nodes, subtree2.edges, subtree2.summaries, {
          nodes: child.nodes,
          edges: child.edges,
          summaries: child.summaries,
          bounds: child.bounds
        }, dx, dy);
        xCursor += child.bounds.width + options.horizontalGap;
      }
    } else {
      const centerX = containerSize.width / 2;
      let yCursor = containerSize.height + options.verticalGap;
      for (let index = 0; index < childIds.length; index += 1) {
        const childId = childIds[index];
        const child = childSubtrees[index];
        const root = child.nodes[childId];
        const rootCenterX = root ? root.x + root.width / 2 : 0;
        const dx = centerX - rootCenterX;
        const dy = yCursor - child.bounds.minY;
        mergeTranslatedLayout2(subtree2.nodes, subtree2.edges, subtree2.summaries, {
          nodes: child.nodes,
          edges: child.edges,
          summaries: child.summaries,
          bounds: child.bounds
        }, dx, dy);
        yCursor += child.bounds.height + options.verticalGap;
      }
    }
    subtree2.bounds = computeBounds2(subtree2.nodes, Object.values(subtree2.summaries));
    return { subtree: subtree2 };
  }
  if (layoutType === "fishbone-left" || layoutType === "fishbone-right") {
    const subtree2 = emptySubtree();
    if (childIds.length === 0) return { subtree: subtree2 };
    const isLeft2 = layoutType === "fishbone-right";
    const spineY = containerSize.height / 2;
    const spineGap = Math.max(16, options.verticalGap);
    const placements = /* @__PURE__ */ new Map();
    let xCursor = isLeft2 ? -options.horizontalGap : containerSize.width + options.horizontalGap;
    for (let index = 0; index < childIds.length; index += 1) {
      const childId = childIds[index];
      const child = childSubtrees[index];
      const isTop = index % 2 === 0;
      const dx = isLeft2 ? xCursor - child.bounds.maxX : xCursor - child.bounds.minX;
      const dy = isTop ? spineY - spineGap - child.bounds.maxY : spineY + spineGap - child.bounds.minY;
      placements.set(childId, { dx, dy, subtree: child });
      mergeTranslatedLayout2(subtree2.nodes, subtree2.edges, subtree2.summaries, {
        nodes: child.nodes,
        edges: child.edges,
        summaries: child.summaries,
        bounds: child.bounds
      }, dx, dy);
      if (isLeft2) xCursor -= child.bounds.width + options.horizontalGap;
      else xCursor += child.bounds.width + options.horizontalGap;
    }
    const indexById2 = new Map(childIds.map((id, index) => [id, index]));
    const summaryRanges2 = attachedSummaries.map((summary) => {
      const indices = summary.childIds.map((id) => indexById2.get(id)).filter((index) => index !== void 0);
      if (indices.length === 0) return null;
      return {
        summary,
        startIndex: Math.min(...indices),
        endIndex: Math.max(...indices)
      };
    }).filter((range) => Boolean(range)).sort((a2, b2) => a2.startIndex !== b2.startIndex ? a2.startIndex - b2.startIndex : a2.endIndex - b2.endIndex);
    for (const { summary, startIndex: rangeStart, endIndex: rangeEnd } of summaryRanges2) {
      const coveredChildren = childIds.slice(rangeStart, rangeEnd + 1);
      const size = summarySizes[summary.id] ?? defaultNodeSize2;
      const rangeBounds = computeSummaryRangeBounds(coveredChildren, placements);
      if (!rangeBounds) continue;
      const geometry = layoutSummaryRangeGeometry({
        layoutType,
        rangeBounds,
        summarySize: size,
        options
      });
      const summarySubtree = layoutSummarySubtree(summary.id, resolveLayout(layoutType, summary.layout));
      mergeTranslatedLayout2(
        subtree2.nodes,
        subtree2.edges,
        subtree2.summaries,
        { nodes: summarySubtree.nodes, edges: summarySubtree.edges, summaries: summarySubtree.summaries, bounds: summarySubtree.bounds },
        geometry.summaryX,
        geometry.summaryY
      );
      const summaryLayout = subtree2.summaries[summary.id];
      if (summaryLayout) {
        subtree2.summaries[summary.id] = {
          ...summaryLayout,
          x: geometry.summaryX,
          y: geometry.summaryY,
          width: size.width,
          height: size.height,
          bracketPath: geometry.bracketPath,
          parentId: summary.parentId,
          childIds: summary.childIds
        };
      } else {
        subtree2.summaries[summary.id] = {
          id: summary.id,
          x: geometry.summaryX,
          y: geometry.summaryY,
          width: size.width,
          height: size.height,
          bracketPath: geometry.bracketPath,
          parentId: summary.parentId,
          childIds: summary.childIds
        };
      }
    }
    subtree2.bounds = computeBounds2(subtree2.nodes, Object.values(subtree2.summaries));
    return { subtree: subtree2 };
  }
  const indexById = new Map(childIds.map((id, index) => [id, index]));
  const summaryRanges = attachedSummaries.map((summary) => {
    const indices = summary.childIds.map((id) => indexById.get(id)).filter((index) => index !== void 0);
    if (indices.length === 0) return null;
    return {
      summary,
      startIndex: Math.min(...indices),
      endIndex: Math.max(...indices)
    };
  }).filter((range) => Boolean(range)).sort((a2, b2) => a2.startIndex !== b2.startIndex ? a2.startIndex - b2.startIndex : a2.endIndex - b2.endIndex);
  const mergedIntervals = [];
  for (const range of summaryRanges) {
    const last = mergedIntervals.at(-1);
    if (!last) {
      mergedIntervals.push({ startIndex: range.startIndex, endIndex: range.endIndex });
      continue;
    }
    if (range.startIndex <= last.endIndex) {
      last.endIndex = Math.max(last.endIndex, range.endIndex);
      continue;
    }
    mergedIntervals.push({ startIndex: range.startIndex, endIndex: range.endIndex });
  }
  const blocks = [];
  let cursor = 0;
  for (const interval of mergedIntervals) {
    while (cursor < interval.startIndex) {
      blocks.push(
        buildBlock({
          childIds,
          childSubtrees,
          summaryRanges,
          summarySizes,
          resolveLayout,
          layoutType,
          layoutSummarySubtree,
          options,
          startIndex: cursor,
          endIndex: cursor
        })
      );
      cursor += 1;
    }
    blocks.push(
      buildBlock({
        childIds,
        childSubtrees,
        summaryRanges,
        summarySizes,
        resolveLayout,
        layoutType,
        layoutSummarySubtree,
        options,
        startIndex: interval.startIndex,
        endIndex: interval.endIndex
      })
    );
    cursor = interval.endIndex + 1;
  }
  while (cursor < childIds.length) {
    blocks.push(
      buildBlock({
        childIds,
        childSubtrees,
        summaryRanges,
        summarySizes,
        resolveLayout,
        layoutType,
        layoutSummarySubtree,
        options,
        startIndex: cursor,
        endIndex: cursor
      })
    );
    cursor += 1;
  }
  if (blocks.length === 0) return { subtree: emptySubtree() };
  const stacked = stackBlocks(blocks, isTree ? "x" : "y", isTree ? options.horizontalGap : options.verticalGap, options.tidy.packing);
  const alignBounds = (() => {
    if (isTree) return stacked.bounds;
    if (options.tidy.logicalAlign !== "level") return stacked.bounds;
    let combined = emptyBounds();
    for (let index = 0; index < blocks.length; index += 1) {
      const block = blocks[index];
      const offset = stacked.offsets[index];
      combined = unionBounds(combined, translateBounds(block.focusBounds, 0, offset));
    }
    return combined;
  })();
  const alignShift = isTree ? containerSize.width / 2 - (alignBounds.minX + alignBounds.maxX) / 2 : containerSize.height / 2 - (alignBounds.minY + alignBounds.maxY) / 2;
  const subtree = emptySubtree();
  for (let index = 0; index < blocks.length; index += 1) {
    const block = blocks[index];
    const offset = stacked.offsets[index];
    const dx = isTree ? alignShift + offset - block.bounds.minX : isLeft ? -options.horizontalGap - block.bounds.maxX : containerSize.width + options.horizontalGap - block.bounds.minX;
    const dy = isTree ? isUp ? -options.verticalGap - block.bounds.maxY : containerSize.height + options.verticalGap - block.bounds.minY : alignShift + offset;
    mergeTranslatedLayout2(subtree.nodes, subtree.edges, subtree.summaries, {
      nodes: block.subtree.nodes,
      edges: block.subtree.edges,
      summaries: block.subtree.summaries,
      bounds: block.subtree.bounds
    }, dx, dy);
  }
  subtree.bounds = computeBounds2(subtree.nodes, Object.values(subtree.summaries));
  return { subtree };
}
function buildBlock(args) {
  const { childIds, childSubtrees, summaryRanges, summarySizes, resolveLayout, layoutType, layoutSummarySubtree, options, startIndex, endIndex } = args;
  const nodes = {};
  const summaries = {};
  const edges = [];
  const placements = /* @__PURE__ */ new Map();
  const isTree = layoutType === "tree-down" || layoutType === "tree-up";
  const isLeft = layoutType === "logical-left";
  if (isTree) {
    let xCursor = 0;
    for (let index = startIndex; index <= endIndex; index += 1) {
      const childId = childIds[index];
      const child = childSubtrees[index];
      const dx = xCursor - child.bounds.minX;
      const dy = 0 - child.bounds.minY;
      placements.set(childId, { dx, dy, subtree: child });
      mergeTranslatedLayout2(nodes, edges, summaries, { nodes: child.nodes, edges: child.edges, summaries: child.summaries, bounds: child.bounds }, dx, dy);
      xCursor += child.bounds.width;
      if (index < endIndex) xCursor += options.horizontalGap;
    }
  } else {
    let yCursor = 0;
    for (let index = startIndex; index <= endIndex; index += 1) {
      const childId = childIds[index];
      const child = childSubtrees[index];
      const rootLayout = child.nodes[childId];
      const dx = isLeft ? 0 - (rootLayout ? rootLayout.x + rootLayout.width : child.bounds.maxX) : 0 - child.bounds.minX;
      const dy = yCursor - child.bounds.minY;
      placements.set(childId, { dx, dy, subtree: child });
      mergeTranslatedLayout2(nodes, edges, summaries, { nodes: child.nodes, edges: child.edges, summaries: child.summaries, bounds: child.bounds }, dx, dy);
      yCursor += child.bounds.height;
      if (index < endIndex) yCursor += options.verticalGap;
    }
  }
  const summariesInBlock = summaryRanges.filter((range) => range.startIndex >= startIndex && range.endIndex <= endIndex);
  for (const { summary, startIndex: rangeStart, endIndex: rangeEnd } of summariesInBlock) {
    const coveredChildren = childIds.slice(rangeStart, rangeEnd + 1);
    const size = summarySizes[summary.id] ?? defaultNodeSize2;
    const rangeBounds = computeSummaryRangeBounds(coveredChildren, placements);
    if (!rangeBounds) continue;
    const geometry = layoutSummaryRangeGeometry({
      layoutType,
      rangeBounds,
      summarySize: size,
      options
    });
    const summarySubtree = layoutSummarySubtree(summary.id, resolveLayout(layoutType, summary.layout));
    mergeTranslatedLayout2(
      nodes,
      edges,
      summaries,
      { nodes: summarySubtree.nodes, edges: summarySubtree.edges, summaries: summarySubtree.summaries, bounds: summarySubtree.bounds },
      geometry.summaryX,
      geometry.summaryY
    );
    const summaryLayout = summaries[summary.id];
    if (summaryLayout) {
      summaries[summary.id] = {
        ...summaryLayout,
        x: geometry.summaryX,
        y: geometry.summaryY,
        width: size.width,
        height: size.height,
        bracketPath: geometry.bracketPath,
        parentId: summary.parentId,
        childIds: summary.childIds
      };
    } else {
      summaries[summary.id] = {
        id: summary.id,
        x: geometry.summaryX,
        y: geometry.summaryY,
        width: size.width,
        height: size.height,
        bracketPath: geometry.bracketPath,
        parentId: summary.parentId,
        childIds: summary.childIds
      };
    }
  }
  const bounds = computeBounds2(nodes, Object.values(summaries));
  const rects = collectRects(nodes, summaries);
  if (!isTree && (layoutType === "logical-right" || layoutType === "logical-left")) {
    const includeFrom = new Set(Object.keys(nodes));
    const padding = Math.max(0, options.tidy.edgeClearance);
    rects.push(...collectEdgeRects(edges, includeFrom, Math.max(2, padding)));
    rects.push(...collectTidyEdgeCorridorRects(edges, nodes, includeFrom, Math.max(2, padding)));
  }
  const profileAxis = isTree ? "y" : "x";
  const profile = buildProfile(rects, profileAxis);
  const focusNodes = {};
  for (let index = startIndex; index <= endIndex; index += 1) {
    const childId = childIds[index];
    const placement = placements.get(childId);
    if (!placement) continue;
    const rootLayout = placement.subtree.nodes[childId];
    if (!rootLayout) continue;
    focusNodes[childId] = {
      x: rootLayout.x + placement.dx,
      y: rootLayout.y + placement.dy,
      width: rootLayout.width,
      height: rootLayout.height
    };
  }
  const focusBounds = Object.keys(focusNodes).length > 0 ? computeBounds2(focusNodes, []) : bounds;
  return { startIndex, endIndex, subtree: { nodes, edges, summaries, bounds }, profile, bounds, focusBounds };
}
function computeSummaryRangeBounds(childIds, placements) {
  let minX = Number.POSITIVE_INFINITY;
  let minY = Number.POSITIVE_INFINITY;
  let maxX = Number.NEGATIVE_INFINITY;
  let maxY = Number.NEGATIVE_INFINITY;
  for (const childId of childIds) {
    const placement = placements.get(childId);
    if (!placement) continue;
    minX = Math.min(minX, placement.dx + placement.subtree.bounds.minX);
    minY = Math.min(minY, placement.dy + placement.subtree.bounds.minY);
    maxX = Math.max(maxX, placement.dx + placement.subtree.bounds.maxX);
    maxY = Math.max(maxY, placement.dy + placement.subtree.bounds.maxY);
  }
  if (!Number.isFinite(minX) || !Number.isFinite(minY) || !Number.isFinite(maxX) || !Number.isFinite(maxY)) {
    return null;
  }
  return { minX, minY, maxX, maxY };
}
function layoutSummaryRangeGeometry(args) {
  const normalized = normalizeSummaryRangeLayoutType(args.layoutType);
  if (normalized === "tree-down" || normalized === "tree-up") {
    return layoutVerticalSummaryRangeGeometry({
      goDown: normalized === "tree-down",
      rangeBounds: args.rangeBounds,
      summarySize: args.summarySize,
      options: args.options
    });
  }
  return layoutHorizontalSummaryRangeGeometry({
    isLeft: normalized === "logical-left",
    rangeBounds: args.rangeBounds,
    summarySize: args.summarySize,
    options: args.options
  });
}
function normalizeSummaryRangeLayoutType(layoutType) {
  if (layoutType === "logical-left" || layoutType === "tree-down" || layoutType === "tree-up") return layoutType;
  if (layoutType === "fishbone-right") return "logical-left";
  return "logical-right";
}
function layoutHorizontalSummaryRangeGeometry(args) {
  const { isLeft, rangeBounds, summarySize, options } = args;
  const bracketGap = Math.max(16, Math.floor(options.horizontalGap / 2));
  const tickLen = Math.max(6, Math.min(18, bracketGap - 6));
  const bracketTick = isLeft ? tickLen : -tickLen;
  const summaryGap = tickLen + 14;
  const bracketX = isLeft ? rangeBounds.minX - bracketGap : rangeBounds.maxX + bracketGap;
  const summaryX = isLeft ? bracketX - summaryGap - summarySize.width : bracketX + summaryGap;
  const summaryY = (rangeBounds.minY + rangeBounds.maxY) / 2 - summarySize.height / 2;
  const bracketPath = [
    `M ${bracketX} ${rangeBounds.minY}`,
    `L ${bracketX + bracketTick} ${rangeBounds.minY}`,
    `M ${bracketX} ${rangeBounds.minY}`,
    `L ${bracketX} ${rangeBounds.maxY}`,
    `M ${bracketX} ${rangeBounds.maxY}`,
    `L ${bracketX + bracketTick} ${rangeBounds.maxY}`
  ].join(" ");
  return {
    summaryX,
    summaryY,
    bracketPath
  };
}
function layoutVerticalSummaryRangeGeometry(args) {
  const { goDown, rangeBounds, summarySize, options } = args;
  const centerX = (rangeBounds.minX + rangeBounds.maxX) / 2;
  const halfSpan = Math.max(0, (rangeBounds.maxX - rangeBounds.minX) / 2);
  const bracketGap = Math.max(16, Math.floor(options.verticalGap / 2) + 4);
  const curveDepth = Math.max(10, Math.min(24, bracketGap));
  const controlInset = Math.min(Math.max(10, halfSpan / 2), Math.max(halfSpan, 10));
  const bracketY = goDown ? rangeBounds.maxY + bracketGap : rangeBounds.minY - bracketGap;
  const curveY = goDown ? bracketY + curveDepth : bracketY - curveDepth;
  const summaryGap = curveDepth + 14;
  const summaryX = centerX - summarySize.width / 2;
  const summaryY = goDown ? bracketY + summaryGap : bracketY - summaryGap - summarySize.height;
  const bracketPath = [
    `M ${rangeBounds.minX} ${bracketY}`,
    `C ${rangeBounds.minX + controlInset} ${bracketY}, ${centerX - controlInset} ${curveY}, ${centerX} ${curveY}`,
    `C ${centerX + controlInset} ${curveY}, ${rangeBounds.maxX - controlInset} ${bracketY}, ${rangeBounds.maxX} ${bracketY}`
  ].join(" ");
  return {
    summaryX,
    summaryY,
    bracketPath
  };
}
function stackBlocks(blocks, axis, gap, packing) {
  if (packing === "relaxed") {
    return stackBlocksRelaxed(blocks, axis, gap);
  }
  return stackBlocksCompact(blocks, axis, gap);
}
function stackBlocksRelaxed(blocks, axis, gap) {
  if (blocks.length === 0) return { offsets: [], bounds: emptyBounds() };
  const offsets = new Array(blocks.length).fill(0);
  let combinedBounds = blocks[0].bounds;
  for (let index = 1; index < blocks.length; index += 1) {
    const block = blocks[index];
    const required = axis === "x" ? combinedBounds.maxX + gap - block.bounds.minX : combinedBounds.maxY + gap - block.bounds.minY;
    const offset = Math.max(0, required);
    offsets[index] = offset;
    const translatedBounds = axis === "x" ? translateBounds(block.bounds, offset, 0) : translateBounds(block.bounds, 0, offset);
    combinedBounds = unionBounds(combinedBounds, translatedBounds);
  }
  return { offsets, bounds: combinedBounds };
}
function stackBlocksCompact(blocks, axis, gap) {
  if (blocks.length === 0) return { offsets: [], bounds: emptyBounds() };
  const offsets = new Array(blocks.length).fill(0);
  let combinedProfile = blocks[0].profile;
  let combinedBounds = blocks[0].bounds;
  for (let index = 1; index < blocks.length; index += 1) {
    const block = blocks[index];
    const required = computeShift(combinedProfile, block.profile, gap);
    offsets[index] = required;
    const shiftedProfile = shiftProfile(block.profile, required);
    combinedProfile = mergeProfiles(combinedProfile, shiftedProfile);
    const translatedBounds = axis === "x" ? translateBounds(block.bounds, required, 0) : translateBounds(block.bounds, 0, required);
    combinedBounds = unionBounds(combinedBounds, translatedBounds);
  }
  return { offsets, bounds: combinedBounds };
}
function emptySubtree() {
  return { nodes: {}, summaries: {}, edges: [], bounds: emptyBounds() };
}
function emptyBounds() {
  return { minX: 0, minY: 0, maxX: 0, maxY: 0, width: 0, height: 0 };
}
function translateBounds(bounds, dx, dy) {
  return {
    minX: bounds.minX + dx,
    minY: bounds.minY + dy,
    maxX: bounds.maxX + dx,
    maxY: bounds.maxY + dy,
    width: bounds.width,
    height: bounds.height
  };
}
function unionBounds(a2, b2) {
  if (a2.width === 0 && a2.height === 0 && Object.keys(a2).length > 0 && a2.minX === 0 && a2.maxX === 0 && a2.minY === 0 && a2.maxY === 0) {
    return b2;
  }
  if (b2.width === 0 && b2.height === 0 && b2.minX === 0 && b2.maxX === 0 && b2.minY === 0 && b2.maxY === 0) {
    return a2;
  }
  const minX = Math.min(a2.minX, b2.minX);
  const minY = Math.min(a2.minY, b2.minY);
  const maxX = Math.max(a2.maxX, b2.maxX);
  const maxY = Math.max(a2.maxY, b2.maxY);
  return { minX, minY, maxX, maxY, width: maxX - minX, height: maxY - minY };
}
function mergeTranslatedLayout2(nodeLayouts, edges, summaries, rootLayout, dx, dy) {
  for (const [nodeId, layout] of Object.entries(rootLayout.nodes)) {
    nodeLayouts[nodeId] = {
      ...layout,
      x: layout.x + dx,
      y: layout.y + dy
    };
  }
  for (const edge of rootLayout.edges) {
    edges.push({
      ...edge,
      path: translatePath2(edge.path, dx, dy)
    });
  }
  for (const [summaryId, layout] of Object.entries(rootLayout.summaries)) {
    summaries[summaryId] = {
      ...layout,
      x: layout.x + dx,
      y: layout.y + dy,
      bracketPath: translatePath2(layout.bracketPath, dx, dy)
    };
  }
}
function translatePath2(path2, dx, dy) {
  if (!path2) return path2;
  if (dx === 0 && dy === 0) return path2;
  let coordIndex = 0;
  return path2.replace(/-?\d*\.?\d+/g, (match) => {
    const value = Number(match);
    const next = coordIndex % 2 === 0 ? value + dx : value + dy;
    coordIndex += 1;
    return String(next);
  });
}
function layoutRelations2(doc3, nodes, summaries) {
  const result = [];
  for (const rel2 of doc3.relations) {
    const from2 = rel2.from.kind === "summary" ? summaries[rel2.from.summaryId] : nodes[rel2.from.nodeId];
    const to = rel2.to.kind === "summary" ? summaries[rel2.to.summaryId] : nodes[rel2.to.nodeId];
    if (!from2 || !to) continue;
    const start = resolvePortPoint2(from2, relationEndpointPort(rel2.from) ?? "right", relationEndpointPortRatio(rel2.from));
    const end = resolvePortPoint2(to, relationEndpointPort(rel2.to) ?? "left", relationEndpointPortRatio(rel2.to));
    const dx = end.x - start.x;
    const dy = end.y - start.y;
    const curve = Math.max(40, Math.min(220, Math.abs(dx) / 2));
    const defaultControl1 = { x: Math.sign(dx || 1) * curve, y: 0 };
    const defaultControl2 = { x: -Math.sign(dx || 1) * curve, y: 0 };
    const curveV1 = rel2.curve?.schemaVersion === 1 && rel2.curve.kind === "cubic" ? rel2.curve : null;
    const control1 = curveV1?.control1 ?? defaultControl1;
    const control2 = curveV1?.control2 ?? defaultControl2;
    const c1 = { x: start.x + control1.x, y: start.y + control1.y };
    const c2 = { x: end.x + control2.x, y: end.y + control2.y };
    const path2 = `M ${start.x} ${start.y} C ${c1.x} ${c1.y}, ${c2.x} ${c2.y}, ${end.x} ${end.y}`;
    const labelText = rel2.label?.schemaVersion === 1 && rel2.label.kind === "plain-text" ? rel2.label.text : "";
    const label = (() => {
      const text5 = labelText.trim();
      if (text5.length === 0) return void 0;
      const mid = cubicAtHalf2(start, c1, c2, end);
      return { text: text5, x: mid.x, y: mid.y };
    })();
    result.push({
      id: rel2.id,
      from: rel2.from,
      to: rel2.to,
      path: path2,
      label,
      style: rel2.style
    });
  }
  return result;
}
function resolvePortPoint2(layout, port, portRatio) {
  const ratio = (() => {
    const next = Number(portRatio);
    if (!Number.isFinite(next)) return 0.5;
    return Math.max(0, Math.min(1, next));
  })();
  switch (port) {
    case "top":
      return { x: layout.x + layout.width * ratio, y: layout.y };
    case "bottom":
      return { x: layout.x + layout.width * ratio, y: layout.y + layout.height };
    case "left":
      return { x: layout.x, y: layout.y + layout.height * ratio };
    case "right":
    default:
      return { x: layout.x + layout.width, y: layout.y + layout.height * ratio };
  }
}
function cubicAtHalf2(p0, p1, p2, p3) {
  return {
    x: (p0.x + 3 * p1.x + 3 * p2.x + p3.x) / 8,
    y: (p0.y + 3 * p1.y + 3 * p2.y + p3.y) / 8
  };
}
function computeBounds2(nodes, summaries) {
  const layouts = [
    ...Object.values(nodes),
    ...summaries
  ];
  if (layouts.length === 0) {
    return { minX: 0, minY: 0, maxX: 0, maxY: 0, width: 0, height: 0 };
  }
  let minX = Number.POSITIVE_INFINITY;
  let minY = Number.POSITIVE_INFINITY;
  let maxX = Number.NEGATIVE_INFINITY;
  let maxY = Number.NEGATIVE_INFINITY;
  for (const layout of layouts) {
    minX = Math.min(minX, layout.x);
    minY = Math.min(minY, layout.y);
    maxX = Math.max(maxX, layout.x + layout.width);
    maxY = Math.max(maxY, layout.y + layout.height);
  }
  return {
    minX,
    minY,
    maxX,
    maxY,
    width: maxX - minX,
    height: maxY - minY
  };
}
function createCubicPathHorizontal2(from2, to) {
  const fromCx = from2.x + from2.width / 2;
  const toCx = to.x + to.width / 2;
  const goRight = toCx >= fromCx;
  const startX = goRight ? from2.x + from2.width : from2.x;
  const startY = from2.y + from2.height / 2;
  const endX = goRight ? to.x : to.x + to.width;
  const endY = to.y + to.height / 2;
  const c1X = startX + (goRight ? 40 : -40);
  const c1Y = startY;
  const c2X = endX + (goRight ? -40 : 40);
  const c2Y = endY;
  return `M ${startX} ${startY} C ${c1X} ${c1Y}, ${c2X} ${c2Y}, ${endX} ${endY}`;
}
function createCubicPathVertical2(from2, to) {
  const startX = from2.x + from2.width / 2;
  const fromCy = from2.y + from2.height / 2;
  const toCy = to.y + to.height / 2;
  const goDown = toCy >= fromCy;
  const startY = goDown ? from2.y + from2.height : from2.y;
  const endX = to.x + to.width / 2;
  const endY = goDown ? to.y : to.y + to.height;
  const c1X = startX;
  const c1Y = startY + (goDown ? 40 : -40);
  const c2X = endX;
  const c2Y = endY + (goDown ? -40 : 40);
  return `M ${startX} ${startY} C ${c1X} ${c1Y}, ${c2X} ${c2Y}, ${endX} ${endY}`;
}
function collectRects(nodes, summaries) {
  const rects = [];
  for (const layout of Object.values(nodes)) {
    rects.push({
      minX: layout.x,
      minY: layout.y,
      maxX: layout.x + layout.width,
      maxY: layout.y + layout.height
    });
  }
  for (const layout of Object.values(summaries)) {
    rects.push({
      minX: layout.x,
      minY: layout.y,
      maxX: layout.x + layout.width,
      maxY: layout.y + layout.height
    });
  }
  return rects;
}
function collectEdgeRects(edges, includeFrom, padding) {
  const rects = [];
  for (const edge of edges) {
    if (!includeFrom.has(edge.from)) continue;
    if (!edge.path) continue;
    const nums = edge.path.match(/-?\d*\.?\d+/g);
    if (!nums || nums.length < 4) continue;
    let minX = Number.POSITIVE_INFINITY;
    let minY = Number.POSITIVE_INFINITY;
    let maxX = Number.NEGATIVE_INFINITY;
    let maxY = Number.NEGATIVE_INFINITY;
    for (let index = 0; index + 1 < nums.length; index += 2) {
      const x5 = Number(nums[index]);
      const y = Number(nums[index + 1]);
      if (!Number.isFinite(x5) || !Number.isFinite(y)) continue;
      minX = Math.min(minX, x5);
      minY = Math.min(minY, y);
      maxX = Math.max(maxX, x5);
      maxY = Math.max(maxY, y);
    }
    if (!Number.isFinite(minX) || !Number.isFinite(minY) || !Number.isFinite(maxX) || !Number.isFinite(maxY)) continue;
    rects.push({
      minX: minX - padding,
      minY: minY - padding,
      maxX: maxX + padding,
      maxY: maxY + padding
    });
  }
  return rects;
}
function collectTidyEdgeCorridorRects(edges, nodes, includeFrom, padding) {
  const rects = [];
  for (const edge of edges) {
    if (!includeFrom.has(edge.from)) continue;
    const from2 = nodes[edge.from];
    const to = nodes[edge.to];
    if (!from2 || !to) continue;
    const fromCx = from2.x + from2.width / 2;
    const fromCy = from2.y + from2.height / 2;
    const toCx = to.x + to.width / 2;
    const toCy = to.y + to.height / 2;
    const dir = toCx >= fromCx ? 1 : -1;
    const startX = fromCx + dir * (from2.width / 10);
    const endX = dir === 1 ? to.x : to.x + to.width;
    rects.push({
      minX: Math.min(startX, endX) - padding,
      minY: Math.min(fromCy, toCy) - padding,
      maxX: Math.max(startX, endX) + padding,
      maxY: Math.max(fromCy, toCy) + padding
    });
  }
  return rects;
}
function hasTidyEdgeNodeIntersections(layout) {
  const rectFromLayout = (node) => ({
    minX: node.x,
    minY: node.y,
    maxX: node.x + node.width,
    maxY: node.y + node.height
  });
  const rectOverlaps = (a2, b2) => a2.minX < b2.maxX && a2.maxX > b2.minX && a2.minY < b2.maxY && a2.maxY > b2.minY;
  const pointInRect2 = (point, rect, epsilon = 1e-3) => {
    return point.x > rect.minX + epsilon && point.x < rect.maxX - epsilon && point.y > rect.minY + epsilon && point.y < rect.maxY - epsilon;
  };
  const clamp4 = (value, min, max) => Math.max(min, Math.min(max, value));
  const parseCubicPath = (path2) => {
    const nums = path2.match(/-?\d*\.?\d+/g);
    if (!nums || nums.length < 8) return null;
    const sx = Number(nums[0]);
    const sy = Number(nums[1]);
    const c1x = Number(nums[2]);
    const c1y = Number(nums[3]);
    const c2x = Number(nums[4]);
    const c2y = Number(nums[5]);
    const ex = Number(nums[6]);
    const ey = Number(nums[7]);
    if (![sx, sy, c1x, c1y, c2x, c2y, ex, ey].every(Number.isFinite)) return null;
    return { sx, sy, c1x, c1y, c2x, c2y, ex, ey };
  };
  const cubicBounds = (cubic) => {
    const minX = Math.min(cubic.sx, cubic.c1x, cubic.c2x, cubic.ex);
    const maxX = Math.max(cubic.sx, cubic.c1x, cubic.c2x, cubic.ex);
    const minY = Math.min(cubic.sy, cubic.c1y, cubic.c2y, cubic.ey);
    const maxY = Math.max(cubic.sy, cubic.c1y, cubic.c2y, cubic.ey);
    return { minX, minY, maxX, maxY };
  };
  const cubicPoint3 = (cubic, t) => {
    const mt = 1 - t;
    const mt2 = mt * mt;
    const t2 = t * t;
    const a2 = mt2 * mt;
    const b2 = 3 * mt2 * t;
    const c = 3 * mt * t2;
    const d2 = t2 * t;
    return {
      x: a2 * cubic.sx + b2 * cubic.c1x + c * cubic.c2x + d2 * cubic.ex,
      y: a2 * cubic.sy + b2 * cubic.c1y + c * cubic.c2y + d2 * cubic.ey
    };
  };
  const cubicIntersectsRect = (cubic, rect, samples2) => {
    for (let i = 1; i < samples2; i += 1) {
      const t = i / samples2;
      const p2 = cubicPoint3(cubic, t);
      if (pointInRect2(p2, rect)) return true;
    }
    return false;
  };
  const quadraticPoint2 = (p0, p1, p2, t) => {
    const mt = 1 - t;
    const a2 = mt * mt;
    const b2 = 2 * mt * t;
    const c = t * t;
    return {
      x: a2 * p0.x + b2 * p1.x + c * p2.x,
      y: a2 * p0.y + b2 * p1.y + c * p2.y
    };
  };
  const centerQuadraticCurve = (from2, to) => {
    const fromCx = from2.x + from2.width / 2;
    const fromCy = from2.y + from2.height / 2;
    const toCx = to.x + to.width / 2;
    const toCy = to.y + to.height / 2;
    const dx = toCx - fromCx;
    const dy = toCy - fromCy;
    const axis = Math.abs(dx) >= Math.abs(dy) ? "x" : "y";
    if (axis === "x") {
      const direction2 = dx >= 0 ? 1 : -1;
      const pct2 = clamp4(Math.abs(dy) / Math.max(1, layout.bounds.height), 0, 1);
      const offset2 = (1 - pct2) * 0.25 * (from2.width / 2);
      const shift3 = from2.width / 10 + offset2;
      const x1 = fromCx + direction2 * shift3;
      const x22 = direction2 === 1 ? to.x : to.x + to.width;
      const p02 = { x: x1, y: fromCy };
      const p12 = { x: x1, y: toCy };
      const p22 = { x: x22, y: toCy };
      return {
        p0: p02,
        p1: p12,
        p2: p22,
        bounds: { minX: Math.min(p02.x, p12.x, p22.x), minY: Math.min(p02.y, p12.y, p22.y), maxX: Math.max(p02.x, p12.x, p22.x), maxY: Math.max(p02.y, p12.y, p22.y) }
      };
    }
    const direction = dy >= 0 ? 1 : -1;
    const pct = clamp4(Math.abs(dx) / Math.max(1, layout.bounds.width), 0, 1);
    const offset = (1 - pct) * 0.25 * (from2.height / 2);
    const shift2 = from2.height / 10 + offset;
    const y1 = fromCy + direction * shift2;
    const y2 = direction === 1 ? to.y : to.y + to.height;
    const p0 = { x: fromCx, y: y1 };
    const p1 = { x: toCx, y: y1 };
    const p2 = { x: toCx, y: y2 };
    return {
      p0,
      p1,
      p2,
      bounds: { minX: Math.min(p0.x, p1.x, p2.x), minY: Math.min(p0.y, p1.y, p2.y), maxX: Math.max(p0.x, p1.x, p2.x), maxY: Math.max(p0.y, p1.y, p2.y) }
    };
  };
  const centerQuadraticIntersectsRect = (curve, rect, samples2) => {
    for (let i = 1; i < samples2; i += 1) {
      const t = i / samples2;
      const p2 = quadraticPoint2(curve.p0, curve.p1, curve.p2, t);
      if (pointInRect2(p2, rect)) return true;
    }
    return false;
  };
  const obstacles = [];
  for (const [id, node] of Object.entries(layout.nodes)) {
    obstacles.push({ id, rect: rectFromLayout(node) });
  }
  for (const [id, summary] of Object.entries(layout.summaries)) {
    obstacles.push({ id, rect: rectFromLayout(summary) });
  }
  const queryObstacles = (() => {
    if (obstacles.length === 0) return (_rect) => [];
    const area = Math.max(1, layout.bounds.width * layout.bounds.height);
    const cellSize = Math.max(160, Math.min(1200, Math.sqrt(area / Math.max(1, obstacles.length)) * 2));
    const buckets = /* @__PURE__ */ new Map();
    const cellRange = (rect) => ({
      minX: Math.floor(rect.minX / cellSize),
      maxX: Math.floor(rect.maxX / cellSize),
      minY: Math.floor(rect.minY / cellSize),
      maxY: Math.floor(rect.maxY / cellSize)
    });
    for (const obstacle of obstacles) {
      const range = cellRange(obstacle.rect);
      for (let x5 = range.minX; x5 <= range.maxX; x5 += 1) {
        for (let y = range.minY; y <= range.maxY; y += 1) {
          const key = `${x5}:${y}`;
          const bucket = buckets.get(key);
          if (bucket) bucket.push(obstacle);
          else buckets.set(key, [obstacle]);
        }
      }
    }
    return (rect) => {
      const range = cellRange(rect);
      const candidates = /* @__PURE__ */ new Map();
      for (let x5 = range.minX; x5 <= range.maxX; x5 += 1) {
        for (let y = range.minY; y <= range.maxY; y += 1) {
          const bucket = buckets.get(`${x5}:${y}`);
          if (!bucket) continue;
          for (const obstacle of bucket) candidates.set(obstacle.id, obstacle);
        }
      }
      return Array.from(candidates.values());
    };
  })();
  const samples = 120;
  for (const edge of layout.edges) {
    const from2 = layout.nodes[edge.from];
    const to = layout.nodes[edge.to];
    if (!from2 || !to) continue;
    const curve = centerQuadraticCurve(from2, to);
    const cubic = parseCubicPath(edge.path);
    const cubicRect = cubic ? cubicBounds(cubic) : null;
    const candidates = /* @__PURE__ */ new Map();
    for (const obstacle of queryObstacles(curve.bounds)) candidates.set(obstacle.id, obstacle);
    if (cubicRect) {
      for (const obstacle of queryObstacles(cubicRect)) candidates.set(obstacle.id, obstacle);
    }
    for (const obstacle of candidates.values()) {
      if (obstacle.id === edge.from || obstacle.id === edge.to) continue;
      if (cubic && cubicRect && rectOverlaps(obstacle.rect, cubicRect) && cubicIntersectsRect(cubic, obstacle.rect, samples)) {
        return true;
      }
      if (rectOverlaps(obstacle.rect, curve.bounds) && centerQuadraticIntersectsRect(curve, obstacle.rect, samples)) {
        return true;
      }
    }
  }
  return false;
}
function buildProfile(rects, axis) {
  const points = /* @__PURE__ */ new Set();
  for (const rect of rects) {
    if (axis === "x") {
      points.add(rect.minX);
      points.add(rect.maxX);
    } else {
      points.add(rect.minY);
      points.add(rect.maxY);
    }
  }
  const sorted = Array.from(points).sort((a2, b2) => a2 - b2);
  if (sorted.length < 2) return [];
  const profile = [];
  for (let index = 0; index < sorted.length - 1; index += 1) {
    const start = sorted[index];
    const end = sorted[index + 1];
    if (end <= start) continue;
    let min = Number.POSITIVE_INFINITY;
    let max = Number.NEGATIVE_INFINITY;
    for (const rect of rects) {
      const overlaps = axis === "x" ? rect.minX < end && rect.maxX > start : rect.minY < end && rect.maxY > start;
      if (!overlaps) continue;
      if (axis === "x") {
        min = Math.min(min, rect.minY);
        max = Math.max(max, rect.maxY);
      } else {
        min = Math.min(min, rect.minX);
        max = Math.max(max, rect.maxX);
      }
    }
    if (!Number.isFinite(min) || !Number.isFinite(max)) continue;
    const prev = profile.at(-1);
    if (prev && prev.max === max && prev.min === min && prev.axisEnd === start) {
      prev.axisEnd = end;
    } else {
      profile.push({ axisStart: start, axisEnd: end, min, max });
    }
  }
  return profile;
}
function computeShift(existing, next, gap) {
  if (existing.length === 0 || next.length === 0) return 0;
  let i = 0;
  let j = 0;
  let required = 0;
  while (i < existing.length && j < next.length) {
    const a2 = existing[i];
    const b2 = next[j];
    if (a2.axisEnd <= b2.axisStart) {
      i += 1;
      continue;
    }
    if (b2.axisEnd <= a2.axisStart) {
      j += 1;
      continue;
    }
    required = Math.max(required, a2.max + gap - b2.min);
    if (a2.axisEnd < b2.axisEnd) i += 1;
    else j += 1;
  }
  return Math.max(0, required);
}
function shiftProfile(profile, delta) {
  if (delta === 0) return profile;
  return profile.map((segment) => ({
    ...segment,
    min: segment.min + delta,
    max: segment.max + delta
  }));
}
function mergeProfiles(a2, b2) {
  if (a2.length === 0) return b2;
  if (b2.length === 0) return a2;
  const points = /* @__PURE__ */ new Set();
  for (const seg of a2) {
    points.add(seg.axisStart);
    points.add(seg.axisEnd);
  }
  for (const seg of b2) {
    points.add(seg.axisStart);
    points.add(seg.axisEnd);
  }
  const sorted = Array.from(points).sort((x5, y) => x5 - y);
  if (sorted.length < 2) return [];
  let aIndex = 0;
  let bIndex = 0;
  const result = [];
  for (let index = 0; index < sorted.length - 1; index += 1) {
    const start = sorted[index];
    const end = sorted[index + 1];
    if (end <= start) continue;
    while (aIndex < a2.length && a2[aIndex].axisEnd <= start) aIndex += 1;
    while (bIndex < b2.length && b2[bIndex].axisEnd <= start) bIndex += 1;
    const aSeg = aIndex < a2.length && a2[aIndex].axisStart < end && a2[aIndex].axisEnd > start ? a2[aIndex] : null;
    const bSeg = bIndex < b2.length && b2[bIndex].axisStart < end && b2[bIndex].axisEnd > start ? b2[bIndex] : null;
    if (!aSeg && !bSeg) continue;
    const min = Math.min(aSeg?.min ?? Number.POSITIVE_INFINITY, bSeg?.min ?? Number.POSITIVE_INFINITY);
    const max = Math.max(aSeg?.max ?? Number.NEGATIVE_INFINITY, bSeg?.max ?? Number.NEGATIVE_INFINITY);
    if (!Number.isFinite(min) || !Number.isFinite(max)) continue;
    const prev = result.at(-1);
    if (prev && prev.min === min && prev.max === max && prev.axisEnd === start) {
      prev.axisEnd = end;
    } else {
      result.push({ axisStart: start, axisEnd: end, min, max });
    }
  }
  return result;
}
var defaultOptions2, defaultNodeSize2, DEFAULT_TIDY_LAYOUT_CACHE_MAX_ENTRIES, TIDY_LAYOUT_CACHE_PRUNE_TARGET_RATIO, KMIND_TIDY_USE_LEGACY_GLOBAL_EDGE_AVOIDANCE, tidyLayoutCacheClock;
var init_mindmap_tidy = __esm({
  "../core/src/layout/mindmap-tidy.ts"() {
    "use strict";
    init_relations();
    defaultOptions2 = {
      horizontalGap: 80,
      verticalGap: 20,
      rootGap: 60,
      engine: "tidy",
      tidy: {
        logicalAlign: "level",
        packing: "relaxed",
        edgeClearance: 4
      }
    };
    defaultNodeSize2 = { width: 160, height: 56 };
    DEFAULT_TIDY_LAYOUT_CACHE_MAX_ENTRIES = 5e4;
    TIDY_LAYOUT_CACHE_PRUNE_TARGET_RATIO = 0.8;
    KMIND_TIDY_USE_LEGACY_GLOBAL_EDGE_AVOIDANCE = false;
    tidyLayoutCacheClock = 0;
  }
});

// ../core/src/layout/mindmap.ts
function layoutMindMap(doc3, nodeSizes, summarySizes, options = {}) {
  const engine = options.engine ?? "legacy";
  if (engine === "tidy") {
    return layoutMindMapTidy(doc3, nodeSizes, summarySizes, options);
  }
  return layoutMindMapLegacy(doc3, nodeSizes, summarySizes, options);
}
var init_mindmap = __esm({
  "../core/src/layout/mindmap.ts"() {
    "use strict";
    init_mindmap_legacy();
    init_mindmap_tidy();
  }
});

// ../core/src/layout/index.ts
var init_layout = __esm({
  "../core/src/layout/index.ts"() {
    "use strict";
    init_logical_right();
    init_tree_down();
    init_mindmap();
  }
});

// ../core/src/edge-router.ts
function clampNumber(value, min, max) {
  if (value < min) return min;
  if (value > max) return max;
  return value;
}
function round2(value) {
  return Math.round(value * 100) / 100;
}
function simplifyOrthogonalPolyline(points) {
  const deduped = [];
  for (const point of points) {
    const prev = deduped.at(-1);
    if (prev && prev.x === point.x && prev.y === point.y) continue;
    deduped.push(point);
  }
  if (deduped.length <= 2) return deduped;
  const simplified = [];
  for (let i = 0; i < deduped.length; i += 1) {
    const prev = simplified.at(-1);
    const curr = deduped[i];
    const next = i + 1 < deduped.length ? deduped[i + 1] : null;
    if (!prev || !next) {
      simplified.push(curr);
      continue;
    }
    const collinear = prev.x === curr.x && curr.x === next.x || prev.y === curr.y && curr.y === next.y;
    if (collinear) continue;
    simplified.push(curr);
  }
  if (simplified.length > 1) {
    const first2 = simplified[0];
    const last = simplified.at(-1);
    if (first2.x !== deduped[0].x || first2.y !== deduped[0].y) simplified.unshift(deduped[0]);
    if (last.x !== deduped.at(-1).x || last.y !== deduped.at(-1).y) simplified.push(deduped.at(-1));
  }
  return simplified.length >= 2 ? simplified : deduped;
}
function buildRoundedPolylinePath(points, args) {
  const cleaned = simplifyOrthogonalPolyline(points);
  if (cleaned.length < 2) return "";
  if (cleaned.length === 2) {
    return `M ${cleaned[0].x} ${cleaned[0].y} L ${cleaned[1].x} ${cleaned[1].y}`;
  }
  const parts = [];
  parts.push(`M ${cleaned[0].x} ${cleaned[0].y}`);
  const radius = args.radius;
  const policy = args.round ?? "all";
  if (radius <= 0 || policy === "none") {
    for (let i = 1; i < cleaned.length; i += 1) {
      const point = cleaned[i];
      parts.push(`L ${point.x} ${point.y}`);
    }
    return parts.join(" ");
  }
  let current = cleaned[0];
  for (let i = 1; i < cleaned.length - 1; i += 1) {
    const corner = cleaned[i];
    const next = cleaned[i + 1];
    const shouldRoundCorner = policy === "all" || policy === "last" && i === cleaned.length - 2;
    if (!shouldRoundCorner) {
      parts.push(`L ${corner.x} ${corner.y}`);
      current = corner;
      continue;
    }
    const dx1 = corner.x - current.x;
    const dy1 = corner.y - current.y;
    const dx2 = next.x - corner.x;
    const dy2 = next.y - corner.y;
    const len1 = Math.hypot(dx1, dy1);
    const len2 = Math.hypot(dx2, dy2);
    if (!Number.isFinite(len1) || !Number.isFinite(len2) || len1 <= 0 || len2 <= 0) {
      parts.push(`L ${corner.x} ${corner.y}`);
      current = corner;
      continue;
    }
    const maxRadius = Math.max(0, Math.min(len1, len2) / 2);
    const r2 = clampNumber(radius, 0, maxRadius);
    if (r2 <= 1e-3) {
      parts.push(`L ${corner.x} ${corner.y}`);
      current = corner;
      continue;
    }
    const inX = dx1 / len1;
    const inY = dy1 / len1;
    const outX = dx2 / len2;
    const outY = dy2 / len2;
    const p1 = { x: corner.x - inX * r2, y: corner.y - inY * r2 };
    const p2 = { x: corner.x + outX * r2, y: corner.y + outY * r2 };
    parts.push(`L ${p1.x} ${p1.y}`);
    const cross = inX * outY - inY * outX;
    const sweep = cross > 0 ? 1 : 0;
    parts.push(`A ${r2} ${r2} 0 0 ${sweep} ${p2.x} ${p2.y}`);
    current = p2;
  }
  const end = cleaned.at(-1);
  parts.push(`L ${end.x} ${end.y}`);
  return parts.join(" ");
}
function buildTaperedShapePath(args) {
  const count = args.samples.length;
  if (count < 2) return "";
  const left = [];
  const right = [];
  for (let i = 0; i < count; i += 1) {
    const sample = args.samples[i];
    const len = Math.hypot(sample.dx, sample.dy) || 1;
    const nx = -sample.dy / len;
    const ny = sample.dx / len;
    const t = count === 1 ? 0 : i / (count - 1);
    const width = args.startWidth * (1 - t) + args.endWidth * t;
    const half = Math.max(0, width) / 2;
    left.push({ x: sample.x + nx * half, y: sample.y + ny * half });
    right.push({ x: sample.x - nx * half, y: sample.y - ny * half });
  }
  const parts = [];
  const first2 = left[0];
  if (!first2) return "";
  parts.push(`M ${round2(first2.x)} ${round2(first2.y)}`);
  for (let i = 1; i < left.length; i += 1) {
    const p2 = left[i];
    parts.push(`L ${round2(p2.x)} ${round2(p2.y)}`);
  }
  for (let i = right.length - 1; i >= 0; i -= 1) {
    const p2 = right[i];
    parts.push(`L ${round2(p2.x)} ${round2(p2.y)}`);
  }
  parts.push("Z");
  return parts.join(" ");
}
function resolveCubicTailGap(distance, options) {
  const requested = typeof options?.gap === "number" && Number.isFinite(options.gap) ? Math.max(0, options.gap) : 30;
  const maxGap = Math.max(0, distance - 1);
  return clampNumber(requested, 0, maxGap);
}
function resolveCubicTailOffset(perpendicularDistance, gap, options) {
  const scaleRaw = typeof options?.offsetScale === "number" && Number.isFinite(options.offsetScale) ? options.offsetScale : 1;
  const scale = clampNumber(scaleRaw, 0, 3);
  const base2 = Math.max(0, perpendicularDistance) / 300 * gap * scale;
  return clampNumber(base2, 0, gap);
}
function resolveEdgeLeadQuadraticLead(distance, options) {
  const requested = typeof options?.lead === "number" && Number.isFinite(options.lead) ? Math.max(0, options.lead) : 14;
  const maxLead = Math.max(0, distance - 1);
  return clampNumber(requested, 0, maxLead);
}
function resolveOrthogonalRoundedRadius(options) {
  const requested = typeof options?.radius === "number" && Number.isFinite(options.radius) ? options.radius : 10;
  return clampNumber(requested, 0, 120);
}
function resolveBaselineForkLead(options) {
  const requested = typeof options?.lead === "number" && Number.isFinite(options.lead) ? options.lead : 26;
  return clampNumber(requested, 0, 240);
}
function resolveBaselineForkBaselineOffset(options) {
  const requested = typeof options?.baselineOffset === "number" && Number.isFinite(options.baselineOffset) ? options.baselineOffset : 6;
  return clampNumber(requested, 0, 80);
}
function resolveBaselineForkDiagonalAngle(options) {
  const requested = typeof options?.diagonalAngle === "number" && Number.isFinite(options.diagonalAngle) ? options.diagonalAngle : 45;
  return clampNumber(requested, 12, 78);
}
function resolveBaselineForkBaselineY(rect, options) {
  return rect.y + rect.height - resolveBaselineForkBaselineOffset(options);
}
function resolveBaselineForkRootAttachY(rect, targetY) {
  const inset = clampNumber(rect.height * 0.16, 4, 14);
  return clampNumber(targetY, rect.y + inset, rect.y + rect.height - inset);
}
function resolveBaselineForkShoulderX(verticalDelta, options) {
  if (verticalDelta <= 1e-3) return 0;
  const angleRad = resolveBaselineForkDiagonalAngle(options) * Math.PI / 180;
  const requested = verticalDelta / Math.tan(angleRad);
  return clampNumber(requested, 18, 72);
}
function buildPolylinePath(points) {
  const cleaned = [];
  for (const point of points) {
    const prev = cleaned.at(-1);
    if (prev && prev.x === point.x && prev.y === point.y) continue;
    cleaned.push(point);
  }
  if (cleaned.length < 2) return "";
  return cleaned.map((point, index) => `${index === 0 ? "M" : "L"} ${round2(point.x)} ${round2(point.y)}`).join(" ");
}
function routeBaselineForkEdgePath(args) {
  const { from: from2, to, anchors, options } = args;
  const lead = resolveBaselineForkLead(options);
  if (anchors.axis === "x") {
    const endY2 = resolveBaselineForkBaselineY(to, options);
    const startY2 = args.fromIsRoot ? resolveBaselineForkRootAttachY(from2, endY2) : resolveBaselineForkBaselineY(from2, options);
    const startX2 = anchors.start.x;
    const attachX = anchors.end.x;
    const endX2 = anchors.dir === 1 ? to.x + to.width : to.x;
    const availableX = Math.max(0, Math.abs(attachX - startX2));
    const verticalDelta = Math.abs(endY2 - startY2);
    const leadX = args.fromIsRoot ? 0 : clampNumber(lead, 0, availableX);
    const shoulderX = clampNumber(resolveBaselineForkShoulderX(verticalDelta, options), 0, Math.max(0, availableX - leadX));
    const shoulderStart2 = { x: startX2 + anchors.dir * leadX, y: startY2 };
    const shoulderEnd2 = { x: shoulderStart2.x + anchors.dir * shoulderX, y: endY2 };
    return buildPolylinePath([
      { x: startX2, y: startY2 },
      shoulderStart2,
      shoulderEnd2,
      { x: endX2, y: endY2 }
    ]);
  }
  const startX = anchors.start.x;
  const startY = anchors.start.y;
  const endX = anchors.end.x;
  const endY = anchors.end.y;
  const availableY = Math.max(0, Math.abs(endY - startY));
  const horizontalDelta = Math.abs(endX - startX);
  const angleRad = resolveBaselineForkDiagonalAngle(options) * Math.PI / 180;
  const requestedDiagonalY = horizontalDelta <= 1e-3 ? 0 : horizontalDelta * Math.tan(angleRad);
  const diagonalY = clampNumber(requestedDiagonalY, 0, availableY);
  const leadY = clampNumber(lead, 0, Math.max(0, availableY - diagonalY));
  const shoulderStart = { x: startX, y: startY + anchors.dir * leadY };
  const shoulderEnd = { x: endX, y: shoulderStart.y + anchors.dir * diagonalY };
  return buildPolylinePath([
    { x: startX, y: startY },
    shoulderStart,
    shoulderEnd,
    { x: endX, y: endY }
  ]);
}
function routeCenterQuadraticEdgePath(args) {
  const fromCx = args.from.x + args.from.width / 2;
  const fromCy = args.from.y + args.from.height / 2;
  const toCx = args.to.x + args.to.width / 2;
  const toCy = args.to.y + args.to.height / 2;
  if (args.anchors.axis === "x") {
    const direction2 = toCx >= fromCx ? 1 : -1;
    const y12 = fromCy;
    const y22 = toCy;
    const pct2 = clampNumber(Math.abs(y22 - y12) / Math.max(1, args.containerHeight), 0, 1);
    const offset2 = (1 - pct2) * 0.25 * (args.from.width / 2);
    const shift3 = args.from.width / 10 + offset2;
    const x12 = fromCx + direction2 * shift3;
    const x23 = direction2 === 1 ? args.to.x : args.to.x + args.to.width;
    return `M ${x12} ${y12} Q ${x12} ${y22} ${x23} ${y22}`;
  }
  const direction = toCy >= fromCy ? 1 : -1;
  const x1 = fromCx;
  const x22 = toCx;
  const pct = clampNumber(Math.abs(x22 - x1) / Math.max(1, args.containerWidth), 0, 1);
  const offset = (1 - pct) * 0.25 * (args.from.height / 2);
  const shift2 = args.from.height / 10 + offset;
  const y1 = fromCy + direction * shift2;
  const y2 = direction === 1 ? args.to.y : args.to.y + args.to.height;
  return `M ${x1} ${y1} Q ${x22} ${y1} ${x22} ${y2}`;
}
function quadraticPoint(p0, p1, p2, t) {
  const mt = 1 - t;
  const a2 = mt * mt;
  const b2 = 2 * mt * t;
  const c = t * t;
  return {
    x: a2 * p0.x + b2 * p1.x + c * p2.x,
    y: a2 * p0.y + b2 * p1.y + c * p2.y
  };
}
function quadraticDerivative(p0, p1, p2, t) {
  return {
    x: 2 * (1 - t) * (p1.x - p0.x) + 2 * t * (p2.x - p1.x),
    y: 2 * (1 - t) * (p1.y - p0.y) + 2 * t * (p2.y - p1.y)
  };
}
function routeCenterQuadraticTaperedEdgePath(args) {
  const fromCx = args.from.x + args.from.width / 2;
  const fromCy = args.from.y + args.from.height / 2;
  const toCx = args.to.x + args.to.width / 2;
  const toCy = args.to.y + args.to.height / 2;
  const p0 = { x: 0, y: 0 };
  const p1 = { x: 0, y: 0 };
  const p2 = { x: 0, y: 0 };
  if (args.anchors.axis === "x") {
    const direction = toCx >= fromCx ? 1 : -1;
    const y1 = fromCy;
    const y2 = toCy;
    const pct = clampNumber(Math.abs(y2 - y1) / Math.max(1, args.containerHeight), 0, 1);
    const offset = (1 - pct) * 0.25 * (args.from.width / 2);
    const shift2 = args.from.width / 10 + offset;
    const x1 = fromCx + direction * shift2;
    const x22 = direction === 1 ? args.to.x : args.to.x + args.to.width;
    p0.x = x1;
    p0.y = y1;
    p1.x = x1;
    p1.y = y2;
    p2.x = x22;
    p2.y = y2;
  } else {
    const direction = toCy >= fromCy ? 1 : -1;
    const x1 = fromCx;
    const x22 = toCx;
    const pct = clampNumber(Math.abs(x22 - x1) / Math.max(1, args.containerWidth), 0, 1);
    const offset = (1 - pct) * 0.25 * (args.from.height / 2);
    const shift2 = args.from.height / 10 + offset;
    const y1 = fromCy + direction * shift2;
    const y2 = direction === 1 ? args.to.y : args.to.y + args.to.height;
    p0.x = x1;
    p0.y = y1;
    p1.x = x22;
    p1.y = y1;
    p2.x = x22;
    p2.y = y2;
  }
  const steps = 18;
  const samples = [];
  for (let i = 0; i <= steps; i += 1) {
    const t = i / steps;
    const point = quadraticPoint(p0, p1, p2, t);
    const d2 = quadraticDerivative(p0, p1, p2, t);
    samples.push({ x: point.x, y: point.y, dx: d2.x, dy: d2.y });
  }
  return buildTaperedShapePath({ samples, startWidth: args.startWidth, endWidth: args.endWidth });
}
function routeEdgeLeadQuadraticEdgePath(args) {
  const { anchors } = args;
  if (anchors.axis === "x") {
    const dx = anchors.end.x - anchors.start.x;
    const lead2 = resolveEdgeLeadQuadraticLead(Math.abs(dx), args.options);
    const x12 = anchors.start.x;
    const y12 = anchors.start.y;
    const x23 = anchors.end.x;
    const y22 = anchors.end.y;
    if (lead2 <= 0) return `M ${x12} ${y12} Q ${x12} ${y22} ${x23} ${y22}`;
    const leadX = x12 + anchors.dir * lead2;
    return `M ${x12} ${y12} L ${leadX} ${y12} Q ${leadX} ${y22} ${x23} ${y22}`;
  }
  const dy = anchors.end.y - anchors.start.y;
  const lead = resolveEdgeLeadQuadraticLead(Math.abs(dy), args.options);
  const x1 = anchors.start.x;
  const y1 = anchors.start.y;
  const x22 = anchors.end.x;
  const y2 = anchors.end.y;
  if (lead <= 0) return `M ${x1} ${y1} Q ${x22} ${y1} ${x22} ${y2}`;
  const leadY = y1 + anchors.dir * lead;
  return `M ${x1} ${y1} L ${x1} ${leadY} Q ${x22} ${leadY} ${x22} ${y2}`;
}
function routeEdgeLeadQuadraticTaperedEdgePath(args) {
  const { anchors } = args;
  const steps = 18;
  const x1 = anchors.start.x;
  const y1 = anchors.start.y;
  const x22 = anchors.end.x;
  const y2 = anchors.end.y;
  if (anchors.axis === "x") {
    const dx = anchors.end.x - anchors.start.x;
    const lead2 = resolveEdgeLeadQuadraticLead(Math.abs(dx), args.options);
    const leadX = x1 + anchors.dir * lead2;
    if (lead2 <= 0) {
      const p0 = { x: x1, y: y1 };
      const p1 = { x: x1, y: y2 };
      const p2 = { x: x22, y: y2 };
      const samples3 = [];
      for (let i = 0; i <= steps; i += 1) {
        const t = i / steps;
        const point = quadraticPoint(p0, p1, p2, t);
        const d2 = quadraticDerivative(p0, p1, p2, t);
        samples3.push({ x: point.x, y: point.y, dx: d2.x, dy: d2.y });
      }
      return buildTaperedShapePath({ samples: samples3, startWidth: args.startWidth, endWidth: args.endWidth });
    }
    const lineEnd2 = { x: leadX, y: y1 };
    const control2 = { x: leadX, y: y2 };
    const curveEnd2 = { x: x22, y: y2 };
    const lineLen2 = Math.max(0, lead2);
    const curveApproxLen2 = Math.hypot(curveEnd2.x - lineEnd2.x, curveEnd2.y - lineEnd2.y);
    const totalLen2 = lineLen2 + curveApproxLen2;
    const minCurveIntervals2 = 8;
    const maxLineIntervals2 = Math.max(1, steps - minCurveIntervals2);
    const lineIntervals2 = totalLen2 > 0 ? clampNumber(Math.round(lineLen2 / totalLen2 * steps), 1, maxLineIntervals2) : 1;
    const curveIntervals2 = Math.max(1, steps - lineIntervals2);
    const samples2 = [];
    for (let i = 0; i <= lineIntervals2; i += 1) {
      const t = lineIntervals2 === 0 ? 0 : i / lineIntervals2;
      const x5 = x1 + (lineEnd2.x - x1) * t;
      const y = y1;
      samples2.push({ x: x5, y, dx: anchors.dir, dy: 0 });
    }
    for (let i = 1; i <= curveIntervals2; i += 1) {
      const t = i / curveIntervals2;
      const point = quadraticPoint(lineEnd2, control2, curveEnd2, t);
      const d2 = quadraticDerivative(lineEnd2, control2, curveEnd2, t);
      samples2.push({ x: point.x, y: point.y, dx: d2.x, dy: d2.y });
    }
    return buildTaperedShapePath({ samples: samples2, startWidth: args.startWidth, endWidth: args.endWidth });
  }
  const dy = anchors.end.y - anchors.start.y;
  const lead = resolveEdgeLeadQuadraticLead(Math.abs(dy), args.options);
  const leadY = y1 + anchors.dir * lead;
  if (lead <= 0) {
    const p0 = { x: x1, y: y1 };
    const p1 = { x: x22, y: y1 };
    const p2 = { x: x22, y: y2 };
    const samples2 = [];
    for (let i = 0; i <= steps; i += 1) {
      const t = i / steps;
      const point = quadraticPoint(p0, p1, p2, t);
      const d2 = quadraticDerivative(p0, p1, p2, t);
      samples2.push({ x: point.x, y: point.y, dx: d2.x, dy: d2.y });
    }
    return buildTaperedShapePath({ samples: samples2, startWidth: args.startWidth, endWidth: args.endWidth });
  }
  const lineEnd = { x: x1, y: leadY };
  const control = { x: x22, y: leadY };
  const curveEnd = { x: x22, y: y2 };
  const lineLen = Math.max(0, lead);
  const curveApproxLen = Math.hypot(curveEnd.x - lineEnd.x, curveEnd.y - lineEnd.y);
  const totalLen = lineLen + curveApproxLen;
  const minCurveIntervals = 8;
  const maxLineIntervals = Math.max(1, steps - minCurveIntervals);
  const lineIntervals = totalLen > 0 ? clampNumber(Math.round(lineLen / totalLen * steps), 1, maxLineIntervals) : 1;
  const curveIntervals = Math.max(1, steps - lineIntervals);
  const samples = [];
  for (let i = 0; i <= lineIntervals; i += 1) {
    const t = lineIntervals === 0 ? 0 : i / lineIntervals;
    const x5 = x1;
    const y = y1 + (lineEnd.y - y1) * t;
    samples.push({ x: x5, y, dx: 0, dy: anchors.dir });
  }
  for (let i = 1; i <= curveIntervals; i += 1) {
    const t = i / curveIntervals;
    const point = quadraticPoint(lineEnd, control, curveEnd, t);
    const d2 = quadraticDerivative(lineEnd, control, curveEnd, t);
    samples.push({ x: point.x, y: point.y, dx: d2.x, dy: d2.y });
  }
  return buildTaperedShapePath({ samples, startWidth: args.startWidth, endWidth: args.endWidth });
}
function routeCubicTailEdgePath(args) {
  const { from: from2, to, anchors } = args;
  const requestedGap = typeof args.options?.gap === "number" && Number.isFinite(args.options.gap) ? Math.max(0, args.options.gap) : 30;
  if (anchors.axis === "x") {
    const xMid = anchors.start.x;
    const farX = anchors.dir === 1 ? to.x + to.width : to.x;
    const distance2 = Math.max(0, Math.abs(farX - xMid));
    const gap2 = clampNumber(requestedGap, 0, Math.max(0, distance2 - 1));
    if (gap2 <= 0) return `M ${anchors.start.x} ${anchors.start.y} L ${anchors.end.x} ${anchors.end.y}`;
    const y12 = args.startFromCenter ? from2.y + from2.height / 2 : from2.y + from2.height;
    const y22 = to.y + to.height;
    const offset2 = resolveCubicTailOffset(Math.abs(y12 - y22), gap2, args.options);
    const x12 = xMid - anchors.dir * gap2;
    const x23 = xMid + anchors.dir * gap2;
    const ctrl2X = xMid - anchors.dir * offset2;
    const endX = farX;
    return `M ${x12} ${y12} C ${xMid} ${y12}, ${ctrl2X} ${y22}, ${x23} ${y22} H ${endX}`;
  }
  const yMid = anchors.start.y;
  const farY = anchors.dir === 1 ? to.y + to.height : to.y;
  const distance = Math.max(0, Math.abs(farY - yMid));
  const gap = clampNumber(requestedGap, 0, Math.max(0, distance - 1));
  if (gap <= 0) return `M ${anchors.start.x} ${anchors.start.y} L ${anchors.end.x} ${anchors.end.y}`;
  const x1 = anchors.start.x;
  const x22 = anchors.end.x;
  const offset = resolveCubicTailOffset(Math.abs(x22 - x1), gap, args.options);
  const y1 = yMid - anchors.dir * gap;
  const y2 = yMid + anchors.dir * gap;
  const ctrl2Y = yMid - anchors.dir * offset;
  const endY = farY;
  return `M ${x1} ${y1} C ${x1} ${yMid}, ${x22} ${ctrl2Y}, ${x22} ${y2} V ${endY}`;
}
function resolveEdgeAnchorsAuto(from2, to) {
  const fromCx = from2.x + from2.width / 2;
  const fromCy = from2.y + from2.height / 2;
  const toCx = to.x + to.width / 2;
  const toCy = to.y + to.height / 2;
  const dx = toCx - fromCx;
  const dy = toCy - fromCy;
  if (Math.abs(dx) >= Math.abs(dy)) {
    const dir2 = dx >= 0 ? 1 : -1;
    return {
      axis: "x",
      dir: dir2,
      start: { x: dir2 === 1 ? from2.x + from2.width : from2.x, y: fromCy },
      end: { x: dir2 === 1 ? to.x : to.x + to.width, y: toCy }
    };
  }
  const dir = dy >= 0 ? 1 : -1;
  return {
    axis: "y",
    dir,
    start: { x: fromCx, y: dir === 1 ? from2.y + from2.height : from2.y },
    end: { x: toCx, y: dir === 1 ? to.y : to.y + to.height }
  };
}
function resolveEdgeAnchorsForLayout(layoutType, from2, to) {
  const fromCx = from2.x + from2.width / 2;
  const fromCy = from2.y + from2.height / 2;
  const toCx = to.x + to.width / 2;
  const toCy = to.y + to.height / 2;
  if (layoutType === "mindmap-both" || layoutType === "mindmap-both-auto") {
    const effective = toCx < fromCx ? "logical-left" : "logical-right";
    const start2 = effective === "logical-left" ? { x: from2.x, y: fromCy } : { x: from2.x + from2.width, y: fromCy };
    const end2 = effective === "logical-left" ? { x: to.x + to.width, y: toCy } : { x: to.x, y: toCy };
    const dir2 = end2.x >= start2.x ? 1 : -1;
    return { axis: "x", dir: dir2, start: start2, end: end2 };
  }
  if (layoutType === "tree-down" || layoutType === "tree-up" || layoutType === "timeline-down") {
    const isUp = layoutType === "tree-up";
    const start2 = { x: fromCx, y: isUp ? from2.y : from2.y + from2.height };
    const end2 = { x: toCx, y: isUp ? to.y + to.height : to.y };
    const dir2 = end2.y >= start2.y ? 1 : -1;
    return { axis: "y", dir: dir2, start: start2, end: end2 };
  }
  if (layoutType === "logical-left") {
    const start2 = { x: from2.x, y: fromCy };
    const end2 = { x: to.x + to.width, y: toCy };
    const dir2 = end2.x >= start2.x ? 1 : -1;
    return { axis: "x", dir: dir2, start: start2, end: end2 };
  }
  if (layoutType === "fishbone-right") {
    const start2 = { x: from2.x, y: fromCy };
    const end2 = { x: to.x + to.width, y: toCy };
    const dir2 = end2.x >= start2.x ? 1 : -1;
    return { axis: "x", dir: dir2, start: start2, end: end2 };
  }
  if (layoutType === "timeline-right" || layoutType === "fishbone-left") {
    const start2 = { x: from2.x + from2.width, y: fromCy };
    const end2 = { x: to.x, y: toCy };
    const dir2 = end2.x >= start2.x ? 1 : -1;
    return { axis: "x", dir: dir2, start: start2, end: end2 };
  }
  const start = { x: from2.x + from2.width, y: fromCy };
  const end = { x: to.x, y: toCy };
  const dir = end.x >= start.x ? 1 : -1;
  return { axis: "x", dir, start, end };
}
function resolveCubicBezier(from2, to, anchorsOverride) {
  const anchors = anchorsOverride ?? resolveEdgeAnchorsAuto(from2, to);
  const { start, end, axis, dir } = anchors;
  if (axis === "x") {
    const dx = end.x - start.x;
    const curve2 = clampNumber(Math.abs(dx) / 2, 40, 220);
    return {
      p0: start,
      p1: { x: start.x + dir * curve2, y: start.y },
      p2: { x: end.x - dir * curve2, y: end.y },
      p3: end,
      axis
    };
  }
  const dy = end.y - start.y;
  const curve = clampNumber(Math.abs(dy) / 2, 40, 220);
  return {
    p0: start,
    p1: { x: start.x, y: start.y + dir * curve },
    p2: { x: end.x, y: end.y - dir * curve },
    p3: end,
    axis
  };
}
function resolveQuadraticLead(from2, to, anchorsOverride, options) {
  const anchors = anchorsOverride ?? resolveEdgeAnchorsAuto(from2, to);
  const { start, end, axis, dir } = anchors;
  const tensionRaw = typeof options?.tension === "number" && Number.isFinite(options.tension) ? options.tension : 0.5;
  const tension = clampNumber(tensionRaw, -1, 1);
  const magnitude = clampNumber(Math.abs(tension), 0, 1);
  const bendDir = tension < 0 ? -1 : 1;
  const bias = clampNumber(0.25 + 0.5 * magnitude, 0.25, 0.75);
  if (axis === "x") {
    const dx = end.x - start.x;
    const requestedLead2 = typeof options?.lead === "number" && Number.isFinite(options.lead) ? Math.max(0, options.lead) : null;
    const maxLead2 = Math.max(0, Math.abs(dx) - 1);
    const lead2 = requestedLead2 === null ? clampNumber(Math.abs(dx) * 0.12, 10, 28) : clampNumber(requestedLead2, 0, maxLead2);
    const p12 = { x: start.x + dir * lead2, y: start.y };
    const dx2 = end.x - p12.x;
    const baseLift2 = clampNumber(Math.abs(dx2) * 0.18, 10, 160);
    const cx = p12.x + dx2 * bias;
    const control2 = { x: cx, y: p12.y + bendDir * baseLift2 * magnitude };
    return { p0: start, p1: p12, c: control2, p2: end, axis };
  }
  const dy = end.y - start.y;
  const requestedLead = typeof options?.lead === "number" && Number.isFinite(options.lead) ? Math.max(0, options.lead) : null;
  const maxLead = Math.max(0, Math.abs(dy) - 1);
  const lead = requestedLead === null ? clampNumber(Math.abs(dy) * 0.12, 10, 28) : clampNumber(requestedLead, 0, maxLead);
  const p1 = { x: start.x, y: start.y + dir * lead };
  const dy2 = end.y - p1.y;
  const baseLift = clampNumber(Math.abs(dy2) * 0.18, 10, 160);
  const cy = p1.y + dy2 * bias;
  const control = { x: p1.x + bendDir * baseLift * magnitude, y: cy };
  return { p0: start, p1, c: control, p2: end, axis };
}
function routeEdgePath(routeType, from2, to, anchorsOverride, options) {
  const anchors = anchorsOverride ?? resolveEdgeAnchorsAuto(from2, to);
  if (routeType === "straight") {
    return `M ${anchors.start.x} ${anchors.start.y} L ${anchors.end.x} ${anchors.end.y}`;
  }
  if (routeType === "edge-lead-quadratic") {
    return routeEdgeLeadQuadraticEdgePath({
      from: from2,
      to,
      anchors,
      options: options?.["edge-lead-quadratic"]
    });
  }
  if (routeType === "baseline-fork") {
    return routeBaselineForkEdgePath({
      from: from2,
      to,
      anchors,
      options: options?.["baseline-fork"]
    });
  }
  if (routeType === "cubic-tail") {
    const cubicTail = options?.["cubic-tail"];
    if (anchors.axis === "x") {
      const dx = anchors.end.x - anchors.start.x;
      const gap2 = resolveCubicTailGap(Math.abs(dx), cubicTail);
      if (gap2 <= 0) return `M ${anchors.start.x} ${anchors.start.y} L ${anchors.end.x} ${anchors.end.y}`;
      const xMid = anchors.start.x;
      const y1 = anchors.start.y;
      const y2 = anchors.end.y;
      const offset2 = resolveCubicTailOffset(Math.abs(y2 - y1), gap2, cubicTail);
      const startX = xMid - anchors.dir * gap2;
      const curveEndX = xMid + anchors.dir * gap2;
      const ctrl2X = xMid - anchors.dir * offset2;
      return `M ${startX} ${y1} C ${xMid} ${y1}, ${ctrl2X} ${y2}, ${curveEndX} ${y2} H ${anchors.end.x}`;
    }
    const dy = anchors.end.y - anchors.start.y;
    const gap = resolveCubicTailGap(Math.abs(dy), cubicTail);
    if (gap <= 0) return `M ${anchors.start.x} ${anchors.start.y} L ${anchors.end.x} ${anchors.end.y}`;
    const yMid = anchors.start.y;
    const x1 = anchors.start.x;
    const x22 = anchors.end.x;
    const offset = resolveCubicTailOffset(Math.abs(x22 - x1), gap, cubicTail);
    const startY = yMid - anchors.dir * gap;
    const curveEndY = yMid + anchors.dir * gap;
    const ctrl2Y = yMid - anchors.dir * offset;
    return `M ${x1} ${startY} C ${x1} ${yMid}, ${x22} ${ctrl2Y}, ${x22} ${curveEndY} V ${anchors.end.y}`;
  }
  if (routeType === "orthogonal") {
    if (anchors.axis === "x") {
      const midX = (anchors.start.x + anchors.end.x) / 2;
      return `M ${anchors.start.x} ${anchors.start.y} L ${midX} ${anchors.start.y} L ${midX} ${anchors.end.y} L ${anchors.end.x} ${anchors.end.y}`;
    }
    const midY = (anchors.start.y + anchors.end.y) / 2;
    return `M ${anchors.start.x} ${anchors.start.y} L ${anchors.start.x} ${midY} L ${anchors.end.x} ${midY} L ${anchors.end.x} ${anchors.end.y}`;
  }
  if (routeType === "orthogonal-rounded") {
    const radius = resolveOrthogonalRoundedRadius(options?.["orthogonal-rounded"]);
    if (anchors.axis === "x") {
      const midX = (anchors.start.x + anchors.end.x) / 2;
      return buildRoundedPolylinePath(
        [
          anchors.start,
          { x: midX, y: anchors.start.y },
          { x: midX, y: anchors.end.y },
          anchors.end
        ],
        { radius, round: "last" }
      );
    }
    const midY = (anchors.start.y + anchors.end.y) / 2;
    return buildRoundedPolylinePath(
      [
        anchors.start,
        { x: anchors.start.x, y: midY },
        { x: anchors.end.x, y: midY },
        anchors.end
      ],
      { radius, round: "last" }
    );
  }
  if (routeType === "quadratic") {
    const quad = resolveQuadraticLead(from2, to, anchorsOverride, options?.quadratic);
    return `M ${quad.p0.x} ${quad.p0.y} L ${quad.p1.x} ${quad.p1.y} Q ${quad.c.x} ${quad.c.y} ${quad.p2.x} ${quad.p2.y}`;
  }
  const bezier = resolveCubicBezier(from2, to, anchorsOverride);
  return `M ${bezier.p0.x} ${bezier.p0.y} C ${bezier.p1.x} ${bezier.p1.y}, ${bezier.p2.x} ${bezier.p2.y}, ${bezier.p3.x} ${bezier.p3.y}`;
}
function cubicPoint(bezier, t) {
  const mt = 1 - t;
  const mt2 = mt * mt;
  const t2 = t * t;
  const a2 = mt2 * mt;
  const b2 = 3 * mt2 * t;
  const c = 3 * mt * t2;
  const d2 = t * t2;
  return {
    x: a2 * bezier.p0.x + b2 * bezier.p1.x + c * bezier.p2.x + d2 * bezier.p3.x,
    y: a2 * bezier.p0.y + b2 * bezier.p1.y + c * bezier.p2.y + d2 * bezier.p3.y
  };
}
function cubicDerivative(bezier, t) {
  const mt = 1 - t;
  const a2 = 3 * mt * mt;
  const b2 = 6 * mt * t;
  const c = 3 * t * t;
  return {
    x: a2 * (bezier.p1.x - bezier.p0.x) + b2 * (bezier.p2.x - bezier.p1.x) + c * (bezier.p3.x - bezier.p2.x),
    y: a2 * (bezier.p1.y - bezier.p0.y) + b2 * (bezier.p2.y - bezier.p1.y) + c * (bezier.p3.y - bezier.p2.y)
  };
}
function routeTaperedEdgePath(args) {
  const bezier = resolveCubicBezier(args.from, args.to, args.anchorsOverride);
  const steps = 18;
  const left = [];
  const right = [];
  for (let i = 0; i <= steps; i += 1) {
    const t = i / steps;
    const point = cubicPoint(bezier, t);
    const d2 = cubicDerivative(bezier, t);
    const len = Math.hypot(d2.x, d2.y) || 1;
    const nx = -d2.y / len;
    const ny = d2.x / len;
    const width = args.startWidth * (1 - t) + args.endWidth * t;
    const half = Math.max(0, width) / 2;
    left.push({ x: point.x + nx * half, y: point.y + ny * half });
    right.push({ x: point.x - nx * half, y: point.y - ny * half });
  }
  const parts = [];
  const first2 = left[0];
  if (!first2) return "";
  parts.push(`M ${round2(first2.x)} ${round2(first2.y)}`);
  for (let i = 1; i < left.length; i += 1) {
    const p2 = left[i];
    parts.push(`L ${round2(p2.x)} ${round2(p2.y)}`);
  }
  for (let i = right.length - 1; i >= 0; i -= 1) {
    const p2 = right[i];
    parts.push(`L ${round2(p2.x)} ${round2(p2.y)}`);
  }
  parts.push("Z");
  return parts.join(" ");
}
var init_edge_router = __esm({
  "../core/src/edge-router.ts"() {
    "use strict";
  }
});

// ../core/src/drag/drop-intent.ts
function parsePathBounds(path2) {
  if (!path2) return null;
  const nums = path2.match(/-?\d*\.?\d+/g);
  if (!nums || nums.length < 2) return null;
  let minX = Number.POSITIVE_INFINITY;
  let minY = Number.POSITIVE_INFINITY;
  let maxX = Number.NEGATIVE_INFINITY;
  let maxY = Number.NEGATIVE_INFINITY;
  for (let i = 0; i < nums.length - 1; i += 2) {
    const x5 = Number(nums[i]);
    const y = Number(nums[i + 1]);
    if (!Number.isFinite(x5) || !Number.isFinite(y)) continue;
    minX = Math.min(minX, x5);
    minY = Math.min(minY, y);
    maxX = Math.max(maxX, x5);
    maxY = Math.max(maxY, y);
  }
  if (!Number.isFinite(minX) || !Number.isFinite(minY) || !Number.isFinite(maxX) || !Number.isFinite(maxY)) return null;
  return { minX, minY, maxX, maxY };
}
function getSummaryBracketBounds(summaryLayout) {
  return parsePathBounds(summaryLayout.bracketPath);
}
var init_drop_intent = __esm({
  "../core/src/drag/drop-intent.ts"() {
    "use strict";
  }
});

// ../core/src/drag/drop-intent-v2.ts
function resolveDropIntentV2(args) {
  const { doc: doc3, layout, draggedNodeId, draggedRect } = args;
  if (!layout.nodes[draggedNodeId]) return { kind: "none" };
  const tailSize = args.options?.tailSize ?? 80;
  const includeSummaryBracket = args.options?.includeSummaryBracket ?? true;
  const childEnterPadding2 = args.options?.childEnterPadding ?? 8;
  const childLeavePadding2 = args.options?.childLeavePadding ?? 22;
  const siblingLanePadding2 = args.options?.siblingLanePadding ?? 44;
  const siblingLanePaddingActive2 = args.options?.siblingLanePaddingActive ?? 72;
  const siblingEndPadding2 = args.options?.siblingEndPadding ?? 44;
  const siblingEndPaddingActive2 = args.options?.siblingEndPaddingActive ?? 72;
  const summaryById = new Map(doc3.summaries.map((summary) => [summary.id, summary]));
  const layoutMemo = /* @__PURE__ */ new Map();
  const resolveNodeLayout = (nodeId, inherited) => {
    const node = doc3.nodes[nodeId];
    if (!node) return inherited;
    if (node.layout) return node.layout;
    if (inherited === "mindmap-both") return node.branchSide === "left" ? "logical-left" : "logical-right";
    if (inherited === "mindmap-both-auto") {
      if (node.branchSide === "left") return "logical-left";
      if (node.branchSide === "right") return "logical-right";
      const parentId = node.parentId;
      const parentRect = parentId ? layout.nodes[parentId] : null;
      const rect = layout.nodes[nodeId];
      if (parentRect && rect) {
        return rect.x + rect.width / 2 < parentRect.x + parentRect.width / 2 ? "logical-left" : "logical-right";
      }
      return "logical-right";
    }
    if (inherited === "fishbone-left") return "logical-right";
    if (inherited === "fishbone-right") return "logical-left";
    return inherited;
  };
  const resolveSummaryLayout = (summaryId, inherited) => {
    const summary = summaryById.get(summaryId);
    if (!summary) return inherited;
    if (summary.layout) return summary.layout;
    if (inherited === "mindmap-both" || inherited === "mindmap-both-auto") return "logical-right";
    if (inherited === "fishbone-left") return "logical-right";
    if (inherited === "fishbone-right") return "logical-left";
    return inherited;
  };
  const resolveLayoutType = (id, visited) => {
    const cached = layoutMemo.get(id);
    if (cached) return cached;
    if (visited.has(id)) return "logical-right";
    visited.add(id);
    const node = doc3.nodes[id];
    if (node) {
      let inherited = "logical-right";
      if (node.parentId) inherited = resolveLayoutType(node.parentId, visited);
      else if (node.parentSummaryId) inherited = resolveLayoutType(node.parentSummaryId, visited);
      const resolved = resolveNodeLayout(id, inherited);
      layoutMemo.set(id, resolved);
      return resolved;
    }
    const summary = summaryById.get(id);
    if (summary) {
      let inherited = "logical-right";
      const parentId = summary.parentId;
      if (doc3.nodes[parentId]) inherited = resolveLayoutType(parentId, visited);
      else inherited = resolveLayoutType(parentId, visited);
      const resolved = resolveSummaryLayout(id, inherited);
      layoutMemo.set(id, resolved);
      return resolved;
    }
    return "logical-right";
  };
  const resolveContainerLayout2 = (containerId) => {
    return resolveLayoutType(containerId, /* @__PURE__ */ new Set());
  };
  const ghostCenter = { x: draggedRect.x + draggedRect.width / 2, y: draggedRect.y + draggedRect.height / 2 };
  const current = args.currentIntent;
  const bestChild = resolveBestChildTarget({
    doc: doc3,
    layout,
    draggedNodeId,
    draggedRect,
    ghostCenter,
    ignoreNodeIds: args.ignoreNodeIds,
    ignoreSummaryIds: args.ignoreSummaryIds,
    resolveContainerLayout: resolveContainerLayout2,
    includeSummaryBracket,
    tailSize,
    childEnterPadding: childEnterPadding2,
    childLeavePadding: childLeavePadding2,
    current
  });
  const bestSibling = resolveBestSiblingSlot({
    doc: doc3,
    layout,
    draggedNodeId,
    draggedRect,
    ignoreNodeIds: args.ignoreNodeIds,
    ignoreSummaryIds: args.ignoreSummaryIds,
    resolveContainerLayout: resolveContainerLayout2,
    siblingLanePadding: siblingLanePadding2,
    siblingLanePaddingActive: siblingLanePaddingActive2,
    siblingEndPadding: siblingEndPadding2,
    siblingEndPaddingActive: siblingEndPaddingActive2,
    current
  });
  if (bestChild && bestChild.fromTail) {
    return {
      kind: "as-child",
      target: bestChild.target,
      ...bestChild.branchSide ? { branchSide: bestChild.branchSide } : {}
    };
  }
  if (bestSibling) {
    if (!bestChild || !bestChild.centerInsideTarget) {
      return {
        kind: "as-sibling",
        parent: bestSibling.parent,
        index: bestSibling.index,
        ...bestSibling.branchSide ? { branchSide: bestSibling.branchSide } : {}
      };
    }
  }
  if (bestChild) {
    return {
      kind: "as-child",
      target: bestChild.target,
      ...bestChild.branchSide ? { branchSide: bestChild.branchSide } : {}
    };
  }
  if (bestSibling) {
    return {
      kind: "as-sibling",
      parent: bestSibling.parent,
      index: bestSibling.index,
      ...bestSibling.branchSide ? { branchSide: bestSibling.branchSide } : {}
    };
  }
  return { kind: "none" };
}
function resolveBestChildTarget(args) {
  const {
    layout,
    draggedNodeId,
    draggedRect,
    ghostCenter,
    ignoreNodeIds,
    ignoreSummaryIds,
    resolveContainerLayout: resolveContainerLayout2,
    includeSummaryBracket,
    tailSize,
    childEnterPadding: childEnterPadding2,
    childLeavePadding: childLeavePadding2,
    current
  } = args;
  const isCurrentChild = current?.kind === "as-child" ? current.target : null;
  let best = null;
  for (const [nodeId, rect] of Object.entries(layout.nodes)) {
    if (nodeId === draggedNodeId) continue;
    if (ignoreNodeIds?.has(nodeId)) continue;
    const pad2 = isCurrentChild?.type === "node" && isCurrentChild.id === nodeId ? childLeavePadding2 : childEnterPadding2;
    const expanded = expandRect(rect, pad2, pad2);
    const area = rectIntersectionArea(draggedRect, expanded);
    const layoutType = resolveContainerLayout2(nodeId);
    const branchSide = layoutType === "mindmap-both" || layoutType === "mindmap-both-auto" ? ghostCenter.x < rect.x + rect.width / 2 ? "left" : "right" : void 0;
    const tailRect = tailSize > 0 ? (() => {
      if (layoutType === "tree-down" || layoutType === "timeline-down") {
        return { x: rect.x, y: rect.y + rect.height, width: rect.width, height: tailSize };
      }
      if (layoutType === "tree-up") {
        return { x: rect.x, y: rect.y - tailSize, width: rect.width, height: tailSize };
      }
      const useLeft = layoutType === "logical-left" || layoutType === "fishbone-right" || (layoutType === "mindmap-both" || layoutType === "mindmap-both-auto") && branchSide === "left";
      return useLeft ? { x: rect.x - tailSize, y: rect.y, width: tailSize, height: rect.height } : { x: rect.x + rect.width, y: rect.y, width: tailSize, height: rect.height };
    })() : null;
    const tailArea = tailRect ? rectIntersectionArea(draggedRect, expandRect(tailRect, pad2, pad2)) : 0;
    const score = Math.max(area, tailArea);
    if (score <= 0) continue;
    const fromTail = tailArea > 0 && area <= 0;
    const centerInsideTarget = pointInRect(ghostCenter, rect);
    if (!best || score > best.score) {
      best = { target: { type: "node", id: nodeId }, score, fromTail, centerInsideTarget, branchSide };
    }
  }
  for (const [summaryId, summaryLayout] of Object.entries(layout.summaries)) {
    if (ignoreSummaryIds?.has(summaryId)) continue;
    const pad2 = isCurrentChild?.type === "summary" && isCurrentChild.id === summaryId ? childLeavePadding2 : childEnterPadding2;
    const expanded = expandRect(summaryLayout, pad2, pad2);
    let score = rectIntersectionArea(draggedRect, expanded);
    let centerInsideTarget = pointInRect(ghostCenter, summaryLayout);
    if (includeSummaryBracket) {
      const bounds = getSummaryBracketBounds(summaryLayout);
      if (bounds) {
        const bracketRect = expandRect(
          { x: bounds.minX, y: bounds.minY, width: bounds.maxX - bounds.minX, height: bounds.maxY - bounds.minY },
          pad2,
          pad2
        );
        score = Math.max(score, rectIntersectionArea(draggedRect, bracketRect));
        centerInsideTarget = centerInsideTarget || pointInRect(ghostCenter, bracketRect);
      }
    }
    if (score <= 0) continue;
    if (!best || score > best.score) {
      best = { target: { type: "summary", id: summaryId }, score, fromTail: false, centerInsideTarget };
    }
  }
  return best;
}
function resolveBestSiblingSlot(args) {
  const {
    doc: doc3,
    layout,
    draggedNodeId,
    draggedRect,
    ignoreNodeIds,
    ignoreSummaryIds,
    resolveContainerLayout: resolveContainerLayout2,
    siblingLanePadding: siblingLanePadding2,
    siblingLanePaddingActive: siblingLanePaddingActive2,
    siblingEndPadding: siblingEndPadding2,
    siblingEndPaddingActive: siblingEndPaddingActive2,
    current
  } = args;
  const isDraggedRoot = doc3.roots.includes(draggedNodeId);
  const isCurrentSiblingParent = current?.kind === "as-sibling" ? current.parent : null;
  let best = null;
  const considerContainer = (container) => {
    if (container.type === "root") {
      if (!isDraggedRoot) return;
    } else if (container.type === "node") {
      if (ignoreNodeIds?.has(container.id)) return;
    } else {
      if (ignoreSummaryIds?.has(container.id)) return;
    }
    const axis = resolveSiblingAxis(container, resolveContainerLayout2);
    const children = resolveContainerChildren(doc3, container).filter((id) => id !== draggedNodeId).filter((id) => Boolean(layout.nodes[id]));
    if (children.length === 0) return;
    const rects = children.map((id) => layout.nodes[id]).filter(Boolean);
    const bounds = computeBounds3(rects);
    if (!bounds) return;
    const isActive2 = container.type === "root" ? isCurrentSiblingParent?.type === "root" : isCurrentSiblingParent?.type === container.type && isCurrentSiblingParent.id === container.id;
    const padCross = isActive2 ? siblingLanePaddingActive2 : siblingLanePadding2;
    const padEnd = isActive2 ? siblingEndPaddingActive2 : siblingEndPadding2;
    const lane = axis === "y" ? { x: bounds.minX - padCross, y: bounds.minY - padEnd, width: bounds.maxX - bounds.minX + padCross * 2, height: bounds.maxY - bounds.minY + padEnd * 2 } : { x: bounds.minX - padEnd, y: bounds.minY - padCross, width: bounds.maxX - bounds.minX + padEnd * 2, height: bounds.maxY - bounds.minY + padCross * 2 };
    const overlap = rectIntersectionArea(draggedRect, lane);
    if (overlap <= 0) return;
    const laneArea = Math.max(1, lane.width * lane.height);
    const score = overlap / laneArea;
    const slot = resolveInsertSlot(doc3, layout, container, axis, draggedRect, draggedNodeId, resolveContainerLayout2, ignoreNodeIds);
    if (!best || score > best.score) {
      best = { parent: container, index: slot.index, score, branchSide: slot.branchSide };
    }
  };
  for (const nodeId of Object.keys(layout.nodes)) {
    const node = doc3.nodes[nodeId];
    if (!node) continue;
    if (node.children.length === 0) continue;
    considerContainer({ type: "node", id: nodeId });
  }
  for (const summaryId of Object.keys(layout.summaries)) {
    const summary = doc3.summaries.find((item) => item.id === summaryId);
    if (!summary) continue;
    if (summary.children.length === 0) continue;
    considerContainer({ type: "summary", id: summaryId });
  }
  if (doc3.roots.length > 1) {
    considerContainer({ type: "root" });
  }
  return best;
}
function resolveSiblingAxis(container, resolveContainerLayout2) {
  if (container.type === "root") return "y";
  const layoutType = resolveContainerLayout2(container.id);
  if (layoutType === "tree-down" || layoutType === "tree-up") return "x";
  if (layoutType === "timeline-right" || layoutType === "fishbone-left" || layoutType === "fishbone-right") return "x";
  if (layoutType === "timeline-down") return "y";
  return "y";
}
function resolveInsertSlot(doc3, layout, container, axis, draggedRect, draggedNodeId, resolveContainerLayout2, ignoreNodeIds) {
  if (container.type === "node") {
    const containerLayoutType = resolveContainerLayout2(container.id);
    if (containerLayoutType === "mindmap-both" || containerLayoutType === "mindmap-both-auto") {
      const containerRect = layout.nodes[container.id];
      const siblings = resolveContainerChildren(doc3, container).filter((id) => id !== draggedNodeId).filter((id) => !ignoreNodeIds?.has(id)).filter((id) => Boolean(layout.nodes[id]));
      if (siblings.length === 0) return { index: 0, branchSide: "right" };
      const branchSide = containerRect ? draggedRect.x + draggedRect.width / 2 < containerRect.x + containerRect.width / 2 ? "left" : "right" : "right";
      const resolveEffectiveBranchSide = (id) => {
        const node = doc3.nodes[id];
        if (node?.branchSide === "left") return "left";
        if (node?.branchSide === "right") return "right";
        if (containerLayoutType === "mindmap-both-auto" && containerRect) {
          const rect = layout.nodes[id];
          if (rect) {
            return rect.x + rect.width / 2 < containerRect.x + containerRect.width / 2 ? "left" : "right";
          }
        }
        return "right";
      };
      const sideSiblings = siblings.filter((id) => {
        return resolveEffectiveBranchSide(id) === branchSide;
      });
      const coord = draggedRect.y + draggedRect.height / 2;
      let sideIndex = 0;
      for (const id of sideSiblings) {
        const rect = layout.nodes[id];
        if (!rect) continue;
        const centerY = rect.y + rect.height / 2;
        if (coord < centerY) break;
        sideIndex += 1;
      }
      if (sideSiblings.length === 0) {
        if (branchSide === "left") {
          const firstRight = siblings.find((id) => resolveEffectiveBranchSide(id) === "right");
          const index2 = firstRight ? siblings.indexOf(firstRight) : siblings.length;
          return { index: index2 < 0 ? 0 : index2, branchSide };
        }
        return { index: siblings.length, branchSide };
      }
      const anchorId = sideSiblings[sideIndex];
      if (anchorId) {
        const index2 = siblings.indexOf(anchorId);
        return { index: index2 < 0 ? siblings.length : index2, branchSide };
      }
      const lastId = sideSiblings.at(-1);
      const lastIndex = lastId ? siblings.indexOf(lastId) : -1;
      return { index: lastIndex < 0 ? siblings.length : lastIndex + 1, branchSide };
    }
  }
  const reverseX = container.type === "node" && axis === "x" && resolveContainerLayout2(container.id) === "fishbone-right";
  const index = resolveInsertIndexGeneric(doc3, layout, container, axis, draggedRect, draggedNodeId, reverseX, ignoreNodeIds);
  return { index };
}
function resolveInsertIndexGeneric(doc3, layout, container, axis, draggedRect, draggedNodeId, reverseX, ignoreNodeIds) {
  const coord = axis === "x" ? draggedRect.x + draggedRect.width / 2 : draggedRect.y + draggedRect.height / 2;
  const ids = resolveContainerChildren(doc3, container).filter((id) => id !== draggedNodeId).filter((id) => !ignoreNodeIds?.has(id)).filter((id) => Boolean(layout.nodes[id]));
  let index = 0;
  for (const id of ids) {
    const rect = layout.nodes[id];
    if (!rect) continue;
    const center3 = axis === "x" ? rect.x + rect.width / 2 : rect.y + rect.height / 2;
    if (axis === "x" && reverseX ? coord > center3 : coord < center3) break;
    index += 1;
  }
  return index;
}
function resolveContainerChildren(doc3, container) {
  if (container.type === "root") return doc3.roots.filter((id) => Boolean(doc3.nodes[id]));
  if (container.type === "node") {
    const parent = doc3.nodes[container.id];
    return parent ? parent.children.filter((id) => Boolean(doc3.nodes[id])) : [];
  }
  const summary = doc3.summaries.find((item) => item.id === container.id);
  return summary ? summary.children.filter((id) => Boolean(doc3.nodes[id])) : [];
}
function computeBounds3(rects) {
  if (rects.length === 0) return null;
  let minX = Number.POSITIVE_INFINITY;
  let minY = Number.POSITIVE_INFINITY;
  let maxX = Number.NEGATIVE_INFINITY;
  let maxY = Number.NEGATIVE_INFINITY;
  for (const rect of rects) {
    minX = Math.min(minX, rect.x);
    minY = Math.min(minY, rect.y);
    maxX = Math.max(maxX, rect.x + rect.width);
    maxY = Math.max(maxY, rect.y + rect.height);
  }
  if (!Number.isFinite(minX) || !Number.isFinite(minY) || !Number.isFinite(maxX) || !Number.isFinite(maxY)) return null;
  return { minX, minY, maxX, maxY };
}
function pointInRect(point, rect) {
  return point.x >= rect.x && point.x <= rect.x + rect.width && point.y >= rect.y && point.y <= rect.y + rect.height;
}
function expandRect(rect, padX, padY) {
  return {
    x: rect.x - padX,
    y: rect.y - padY,
    width: rect.width + padX * 2,
    height: rect.height + padY * 2
  };
}
function rectIntersectionArea(a2, b2) {
  const x1 = Math.max(a2.x, b2.x);
  const y1 = Math.max(a2.y, b2.y);
  const x22 = Math.min(a2.x + a2.width, b2.x + b2.width);
  const y2 = Math.min(a2.y + a2.height, b2.y + b2.height);
  const w = x22 - x1;
  const h2 = y2 - y1;
  if (w <= 0 || h2 <= 0) return 0;
  return w * h2;
}
var init_drop_intent_v2 = __esm({
  "../core/src/drag/drop-intent-v2.ts"() {
    "use strict";
    init_drop_intent();
  }
});

// ../core/src/drag/index.ts
var init_drag = __esm({
  "../core/src/drag/index.ts"() {
    "use strict";
    init_drop_intent();
    init_drop_intent_v2();
  }
});

// ../core/src/index.ts
var init_src = __esm({
  "../core/src/index.ts"() {
    "use strict";
    init_commands();
    init_core();
    init_blur();
    init_theme();
    init_content();
    init_document();
    init_node_content_width();
    init_compact_document();
    init_relations();
    init_pos();
    init_tree();
    init_id();
    init_id();
    init_layout();
    init_edge_router();
    init_drag();
    init_drag();
  }
});

// ../collab/dist/broadcast-channel-sync.js
var init_broadcast_channel_sync = __esm({
  "../collab/dist/broadcast-channel-sync.js"() {
    "use strict";
  }
});

// ../collab/dist/yjs-helpers.js
var init_yjs_helpers = __esm({
  "../collab/dist/yjs-helpers.js"() {
    "use strict";
  }
});

// ../collab/dist/kmind-crdt-v1.js
var init_kmind_crdt_v1 = __esm({
  "../collab/dist/kmind-crdt-v1.js"() {
    "use strict";
    init_src();
  }
});

// ../collab/dist/crdt-mindmap-core.js
var init_crdt_mindmap_core = __esm({
  "../collab/dist/crdt-mindmap-core.js"() {
    "use strict";
    init_src();
    init_kmind_crdt_v1();
  }
});

// ../collab/dist/index.js
var init_dist = __esm({
  "../collab/dist/index.js"() {
    "use strict";
    init_broadcast_channel_sync();
    init_yjs_helpers();
    init_crdt_mindmap_core();
    init_kmind_crdt_v1();
  }
});

// ../../node_modules/.pnpm/react@19.2.3/node_modules/react/cjs/react-jsx-runtime.development.js
var require_react_jsx_runtime_development = __commonJS({
  "../../node_modules/.pnpm/react@19.2.3/node_modules/react/cjs/react-jsx-runtime.development.js"(exports) {
    "use strict";
    (function() {
      function getComponentNameFromType(type) {
        if (null == type) return null;
        if ("function" === typeof type)
          return type.$$typeof === REACT_CLIENT_REFERENCE ? null : type.displayName || type.name || null;
        if ("string" === typeof type) return type;
        switch (type) {
          case REACT_FRAGMENT_TYPE:
            return "Fragment";
          case REACT_PROFILER_TYPE:
            return "Profiler";
          case REACT_STRICT_MODE_TYPE:
            return "StrictMode";
          case REACT_SUSPENSE_TYPE:
            return "Suspense";
          case REACT_SUSPENSE_LIST_TYPE:
            return "SuspenseList";
          case REACT_ACTIVITY_TYPE:
            return "Activity";
        }
        if ("object" === typeof type)
          switch ("number" === typeof type.tag && console.error(
            "Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."
          ), type.$$typeof) {
            case REACT_PORTAL_TYPE:
              return "Portal";
            case REACT_CONTEXT_TYPE:
              return type.displayName || "Context";
            case REACT_CONSUMER_TYPE:
              return (type._context.displayName || "Context") + ".Consumer";
            case REACT_FORWARD_REF_TYPE:
              var innerType = type.render;
              type = type.displayName;
              type || (type = innerType.displayName || innerType.name || "", type = "" !== type ? "ForwardRef(" + type + ")" : "ForwardRef");
              return type;
            case REACT_MEMO_TYPE:
              return innerType = type.displayName || null, null !== innerType ? innerType : getComponentNameFromType(type.type) || "Memo";
            case REACT_LAZY_TYPE:
              innerType = type._payload;
              type = type._init;
              try {
                return getComponentNameFromType(type(innerType));
              } catch (x5) {
              }
          }
        return null;
      }
      function testStringCoercion(value) {
        return "" + value;
      }
      function checkKeyStringCoercion(value) {
        try {
          testStringCoercion(value);
          var JSCompiler_inline_result = false;
        } catch (e) {
          JSCompiler_inline_result = true;
        }
        if (JSCompiler_inline_result) {
          JSCompiler_inline_result = console;
          var JSCompiler_temp_const = JSCompiler_inline_result.error;
          var JSCompiler_inline_result$jscomp$0 = "function" === typeof Symbol && Symbol.toStringTag && value[Symbol.toStringTag] || value.constructor.name || "Object";
          JSCompiler_temp_const.call(
            JSCompiler_inline_result,
            "The provided key is an unsupported type %s. This value must be coerced to a string before using it here.",
            JSCompiler_inline_result$jscomp$0
          );
          return testStringCoercion(value);
        }
      }
      function getTaskName(type) {
        if (type === REACT_FRAGMENT_TYPE) return "<>";
        if ("object" === typeof type && null !== type && type.$$typeof === REACT_LAZY_TYPE)
          return "<...>";
        try {
          var name = getComponentNameFromType(type);
          return name ? "<" + name + ">" : "<...>";
        } catch (x5) {
          return "<...>";
        }
      }
      function getOwner() {
        var dispatcher = ReactSharedInternals.A;
        return null === dispatcher ? null : dispatcher.getOwner();
      }
      function UnknownOwner() {
        return Error("react-stack-top-frame");
      }
      function hasValidKey(config) {
        if (hasOwnProperty2.call(config, "key")) {
          var getter = Object.getOwnPropertyDescriptor(config, "key").get;
          if (getter && getter.isReactWarning) return false;
        }
        return void 0 !== config.key;
      }
      function defineKeyPropWarningGetter(props, displayName) {
        function warnAboutAccessingKey() {
          specialPropKeyWarningShown || (specialPropKeyWarningShown = true, console.error(
            "%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://react.dev/link/special-props)",
            displayName
          ));
        }
        warnAboutAccessingKey.isReactWarning = true;
        Object.defineProperty(props, "key", {
          get: warnAboutAccessingKey,
          configurable: true
        });
      }
      function elementRefGetterWithDeprecationWarning() {
        var componentName = getComponentNameFromType(this.type);
        didWarnAboutElementRef[componentName] || (didWarnAboutElementRef[componentName] = true, console.error(
          "Accessing element.ref was removed in React 19. ref is now a regular prop. It will be removed from the JSX Element type in a future release."
        ));
        componentName = this.props.ref;
        return void 0 !== componentName ? componentName : null;
      }
      function ReactElement(type, key, props, owner, debugStack, debugTask) {
        var refProp = props.ref;
        type = {
          $$typeof: REACT_ELEMENT_TYPE,
          type,
          key,
          props,
          _owner: owner
        };
        null !== (void 0 !== refProp ? refProp : null) ? Object.defineProperty(type, "ref", {
          enumerable: false,
          get: elementRefGetterWithDeprecationWarning
        }) : Object.defineProperty(type, "ref", { enumerable: false, value: null });
        type._store = {};
        Object.defineProperty(type._store, "validated", {
          configurable: false,
          enumerable: false,
          writable: true,
          value: 0
        });
        Object.defineProperty(type, "_debugInfo", {
          configurable: false,
          enumerable: false,
          writable: true,
          value: null
        });
        Object.defineProperty(type, "_debugStack", {
          configurable: false,
          enumerable: false,
          writable: true,
          value: debugStack
        });
        Object.defineProperty(type, "_debugTask", {
          configurable: false,
          enumerable: false,
          writable: true,
          value: debugTask
        });
        Object.freeze && (Object.freeze(type.props), Object.freeze(type));
        return type;
      }
      function jsxDEVImpl(type, config, maybeKey, isStaticChildren, debugStack, debugTask) {
        var children = config.children;
        if (void 0 !== children)
          if (isStaticChildren)
            if (isArrayImpl(children)) {
              for (isStaticChildren = 0; isStaticChildren < children.length; isStaticChildren++)
                validateChildKeys(children[isStaticChildren]);
              Object.freeze && Object.freeze(children);
            } else
              console.error(
                "React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead."
              );
          else validateChildKeys(children);
        if (hasOwnProperty2.call(config, "key")) {
          children = getComponentNameFromType(type);
          var keys3 = Object.keys(config).filter(function(k) {
            return "key" !== k;
          });
          isStaticChildren = 0 < keys3.length ? "{key: someKey, " + keys3.join(": ..., ") + ": ...}" : "{key: someKey}";
          didWarnAboutKeySpread[children + isStaticChildren] || (keys3 = 0 < keys3.length ? "{" + keys3.join(": ..., ") + ": ...}" : "{}", console.error(
            'A props object containing a "key" prop is being spread into JSX:\n  let props = %s;\n  <%s {...props} />\nReact keys must be passed directly to JSX without using spread:\n  let props = %s;\n  <%s key={someKey} {...props} />',
            isStaticChildren,
            children,
            keys3,
            children
          ), didWarnAboutKeySpread[children + isStaticChildren] = true);
        }
        children = null;
        void 0 !== maybeKey && (checkKeyStringCoercion(maybeKey), children = "" + maybeKey);
        hasValidKey(config) && (checkKeyStringCoercion(config.key), children = "" + config.key);
        if ("key" in config) {
          maybeKey = {};
          for (var propName in config)
            "key" !== propName && (maybeKey[propName] = config[propName]);
        } else maybeKey = config;
        children && defineKeyPropWarningGetter(
          maybeKey,
          "function" === typeof type ? type.displayName || type.name || "Unknown" : type
        );
        return ReactElement(
          type,
          children,
          maybeKey,
          getOwner(),
          debugStack,
          debugTask
        );
      }
      function validateChildKeys(node) {
        isValidElement(node) ? node._store && (node._store.validated = 1) : "object" === typeof node && null !== node && node.$$typeof === REACT_LAZY_TYPE && ("fulfilled" === node._payload.status ? isValidElement(node._payload.value) && node._payload.value._store && (node._payload.value._store.validated = 1) : node._store && (node._store.validated = 1));
      }
      function isValidElement(object) {
        return "object" === typeof object && null !== object && object.$$typeof === REACT_ELEMENT_TYPE;
      }
      var React7 = require_react(), REACT_ELEMENT_TYPE = /* @__PURE__ */ Symbol.for("react.transitional.element"), REACT_PORTAL_TYPE = /* @__PURE__ */ Symbol.for("react.portal"), REACT_FRAGMENT_TYPE = /* @__PURE__ */ Symbol.for("react.fragment"), REACT_STRICT_MODE_TYPE = /* @__PURE__ */ Symbol.for("react.strict_mode"), REACT_PROFILER_TYPE = /* @__PURE__ */ Symbol.for("react.profiler"), REACT_CONSUMER_TYPE = /* @__PURE__ */ Symbol.for("react.consumer"), REACT_CONTEXT_TYPE = /* @__PURE__ */ Symbol.for("react.context"), REACT_FORWARD_REF_TYPE = /* @__PURE__ */ Symbol.for("react.forward_ref"), REACT_SUSPENSE_TYPE = /* @__PURE__ */ Symbol.for("react.suspense"), REACT_SUSPENSE_LIST_TYPE = /* @__PURE__ */ Symbol.for("react.suspense_list"), REACT_MEMO_TYPE = /* @__PURE__ */ Symbol.for("react.memo"), REACT_LAZY_TYPE = /* @__PURE__ */ Symbol.for("react.lazy"), REACT_ACTIVITY_TYPE = /* @__PURE__ */ Symbol.for("react.activity"), REACT_CLIENT_REFERENCE = /* @__PURE__ */ Symbol.for("react.client.reference"), ReactSharedInternals = React7.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE, hasOwnProperty2 = Object.prototype.hasOwnProperty, isArrayImpl = Array.isArray, createTask = console.createTask ? console.createTask : function() {
        return null;
      };
      React7 = {
        react_stack_bottom_frame: function(callStackForError) {
          return callStackForError();
        }
      };
      var specialPropKeyWarningShown;
      var didWarnAboutElementRef = {};
      var unknownOwnerDebugStack = React7.react_stack_bottom_frame.bind(
        React7,
        UnknownOwner
      )();
      var unknownOwnerDebugTask = createTask(getTaskName(UnknownOwner));
      var didWarnAboutKeySpread = {};
      exports.Fragment = REACT_FRAGMENT_TYPE;
      exports.jsx = function(type, config, maybeKey) {
        var trackActualOwner = 1e4 > ReactSharedInternals.recentlyCreatedOwnerStacks++;
        return jsxDEVImpl(
          type,
          config,
          maybeKey,
          false,
          trackActualOwner ? Error("react-stack-top-frame") : unknownOwnerDebugStack,
          trackActualOwner ? createTask(getTaskName(type)) : unknownOwnerDebugTask
        );
      };
      exports.jsxs = function(type, config, maybeKey) {
        var trackActualOwner = 1e4 > ReactSharedInternals.recentlyCreatedOwnerStacks++;
        return jsxDEVImpl(
          type,
          config,
          maybeKey,
          true,
          trackActualOwner ? Error("react-stack-top-frame") : unknownOwnerDebugStack,
          trackActualOwner ? createTask(getTaskName(type)) : unknownOwnerDebugTask
        );
      };
    })();
  }
});

// ../../node_modules/.pnpm/react@19.2.3/node_modules/react/jsx-runtime.js
var require_jsx_runtime = __commonJS({
  "../../node_modules/.pnpm/react@19.2.3/node_modules/react/jsx-runtime.js"(exports, module) {
    "use strict";
    if (false) {
      module.exports = null;
    } else {
      module.exports = require_react_jsx_runtime_development();
    }
  }
});

// ../../node_modules/.pnpm/use-sync-external-store@1.6.0_react@19.2.3/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/.pnpm/use-sync-external-store@1.6.0_react@19.2.3/node_modules/use-sync-external-store/cjs/use-sync-external-store-shim.development.js"(exports) {
    "use strict";
    (function() {
      function is(x5, y) {
        return x5 === y && (0 !== x5 || 1 / x5 === 1 / y) || x5 !== x5 && y !== y;
      }
      function useSyncExternalStore$2(subscribe2, getSnapshot) {
        didWarnOld18Alpha || void 0 === React7.startTransition || (didWarnOld18Alpha = true, console.error(
          "You are using an outdated, pre-release alpha of React 18 that does not support useSyncExternalStore. The use-sync-external-store shim will not work correctly. Upgrade to a newer pre-release."
        ));
        var value = getSnapshot();
        if (!didWarnUncachedGetSnapshot) {
          var cachedValue = getSnapshot();
          objectIs(value, cachedValue) || (console.error(
            "The result of getSnapshot should be cached to avoid an infinite loop"
          ), didWarnUncachedGetSnapshot = true);
        }
        cachedValue = useState28({
          inst: { value, getSnapshot }
        });
        var inst = cachedValue[0].inst, forceUpdate = cachedValue[1];
        useLayoutEffect10(
          function() {
            inst.value = value;
            inst.getSnapshot = getSnapshot;
            checkIfSnapshotChanged(inst) && forceUpdate({ inst });
          },
          [subscribe2, value, getSnapshot]
        );
        useEffect29(
          function() {
            checkIfSnapshotChanged(inst) && forceUpdate({ inst });
            return subscribe2(function() {
              checkIfSnapshotChanged(inst) && forceUpdate({ inst });
            });
          },
          [subscribe2]
        );
        useDebugValue3(value);
        return value;
      }
      function checkIfSnapshotChanged(inst) {
        var latestGetSnapshot = inst.getSnapshot;
        inst = inst.value;
        try {
          var nextValue = latestGetSnapshot();
          return !objectIs(inst, nextValue);
        } catch (error) {
          return true;
        }
      }
      function useSyncExternalStore$1(subscribe2, getSnapshot) {
        return getSnapshot();
      }
      "undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ && "function" === typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart && __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(Error());
      var React7 = require_react(), objectIs = "function" === typeof Object.is ? Object.is : is, useState28 = React7.useState, useEffect29 = React7.useEffect, useLayoutEffect10 = React7.useLayoutEffect, useDebugValue3 = React7.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 !== React7.useSyncExternalStore ? React7.useSyncExternalStore : shim;
      "undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ && "function" === typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop && __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(Error());
    })();
  }
});

// ../../node_modules/.pnpm/use-sync-external-store@1.6.0_react@19.2.3/node_modules/use-sync-external-store/shim/index.js
var require_shim = __commonJS({
  "../../node_modules/.pnpm/use-sync-external-store@1.6.0_react@19.2.3/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/.pnpm/use-sync-external-store@1.6.0_react@19.2.3/node_modules/use-sync-external-store/cjs/use-sync-external-store-shim/with-selector.development.js
var require_with_selector_development = __commonJS({
  "../../node_modules/.pnpm/use-sync-external-store@1.6.0_react@19.2.3/node_modules/use-sync-external-store/cjs/use-sync-external-store-shim/with-selector.development.js"(exports) {
    "use strict";
    (function() {
      function is(x5, y) {
        return x5 === y && (0 !== x5 || 1 / x5 === 1 / y) || x5 !== x5 && y !== y;
      }
      "undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ && "function" === typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart && __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(Error());
      var React7 = require_react(), shim = require_shim(), objectIs = "function" === typeof Object.is ? Object.is : is, useSyncExternalStore6 = shim.useSyncExternalStore, useRef28 = React7.useRef, useEffect29 = React7.useEffect, useMemo28 = React7.useMemo, useDebugValue3 = React7.useDebugValue;
      exports.useSyncExternalStoreWithSelector = function(subscribe2, getSnapshot, getServerSnapshot, selector, isEqual) {
        var instRef = useRef28(null);
        if (null === instRef.current) {
          var inst = { hasValue: false, value: null };
          instRef.current = inst;
        } else inst = instRef.current;
        instRef = useMemo28(
          function() {
            function memoizedSelector(nextSnapshot) {
              if (!hasMemo) {
                hasMemo = true;
                memoizedSnapshot = nextSnapshot;
                nextSnapshot = selector(nextSnapshot);
                if (void 0 !== isEqual && inst.hasValue) {
                  var currentSelection = inst.value;
                  if (isEqual(currentSelection, nextSnapshot))
                    return memoizedSelection = currentSelection;
                }
                return memoizedSelection = nextSnapshot;
              }
              currentSelection = memoizedSelection;
              if (objectIs(memoizedSnapshot, nextSnapshot))
                return currentSelection;
              var nextSelection = selector(nextSnapshot);
              if (void 0 !== isEqual && isEqual(currentSelection, nextSelection))
                return memoizedSnapshot = nextSnapshot, currentSelection;
              memoizedSnapshot = nextSnapshot;
              return memoizedSelection = nextSelection;
            }
            var hasMemo = false, memoizedSnapshot, memoizedSelection, maybeGetServerSnapshot = void 0 === getServerSnapshot ? null : getServerSnapshot;
            return [
              function() {
                return memoizedSelector(getSnapshot());
              },
              null === maybeGetServerSnapshot ? void 0 : function() {
                return memoizedSelector(maybeGetServerSnapshot());
              }
            ];
          },
          [getSnapshot, getServerSnapshot, selector, isEqual]
        );
        var value = useSyncExternalStore6(subscribe2, instRef[0], instRef[1]);
        useEffect29(
          function() {
            inst.hasValue = true;
            inst.value = value;
          },
          [value]
        );
        useDebugValue3(value);
        return value;
      };
      "undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ && "function" === typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop && __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(Error());
    })();
  }
});

// ../../node_modules/.pnpm/use-sync-external-store@1.6.0_react@19.2.3/node_modules/use-sync-external-store/shim/with-selector.js
var require_with_selector = __commonJS({
  "../../node_modules/.pnpm/use-sync-external-store@1.6.0_react@19.2.3/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();
    }
  }
});

// src/render-job-browser.tsx
var import_react49 = __toESM(require_react(), 1);
var import_client = __toESM(require_client(), 1);
init_src();

// ../react/src/dom-measurer.ts
function createDomNodeContentMeasurer(options = {}) {
  if (typeof document === "undefined") {
    return {
      measure: (input) => {
        const resolved = { ...options, ...input.options ?? {} };
        const roughCharWidth = 7;
        const paddingX = resolved.paddingX ?? 12;
        const paddingY = resolved.paddingY ?? 8;
        const minWidth = resolved.minWidth ?? 60;
        const minHeight = resolved.minHeight ?? 34;
        const html = typeof input.html === "string" ? input.html : "";
        const fallbackText = typeof input.text === "string" ? input.text : "";
        const text5 = fallbackText.length > 0 ? fallbackText : stripHtml(html);
        const maxWidth = input.maxWidth;
        const rawWidth = paddingX * 2 + Math.max(1, text5.length) * roughCharWidth;
        return {
          width: Math.max(minWidth, Math.min(maxWidth, rawWidth)),
          height: minHeight + paddingY * 2
        };
      },
      destroy: () => {
      }
    };
  }
  const base2 = {
    fontFamily: options.fontFamily ?? "ui-sans-serif, system-ui, sans-serif",
    fontSize: options.fontSize ?? 14,
    fontWeight: options.fontWeight ?? 400,
    lineHeight: options.lineHeight ?? 1.4,
    textAlign: options.textAlign ?? "left",
    paddingX: options.paddingX ?? 12,
    paddingY: options.paddingY ?? 8,
    minWidth: options.minWidth ?? 60,
    minHeight: options.minHeight ?? 34,
    cssText: options.cssText ?? ""
  };
  const container = document.createElement("div");
  container.style.position = "absolute";
  container.style.left = "-10000px";
  container.style.top = "-10000px";
  container.style.visibility = "hidden";
  container.style.pointerEvents = "none";
  container.style.contain = "layout style";
  const styleEl = document.createElement("style");
  styleEl.textContent = base2.cssText;
  container.appendChild(styleEl);
  const element = document.createElement("div");
  element.style.display = "inline-block";
  element.style.boxSizing = "border-box";
  element.style.padding = `${base2.paddingY}px ${base2.paddingX}px`;
  element.style.fontFamily = base2.fontFamily;
  element.style.fontSize = `${base2.fontSize}px`;
  element.style.fontWeight = String(base2.fontWeight);
  element.style.lineHeight = String(base2.lineHeight);
  element.style.textAlign = base2.textAlign;
  container.appendChild(element);
  document.body.appendChild(container);
  const measure = (input) => {
    const resolved = { ...base2, ...input.options ?? {} };
    const html = typeof input.html === "string" ? input.html : "";
    const text5 = typeof input.text === "string" ? input.text : "";
    const maxWidth = input.maxWidth;
    if (resolved.cssText !== styleEl.textContent) {
      styleEl.textContent = resolved.cssText ?? "";
    }
    element.style.padding = `${resolved.paddingY ?? base2.paddingY}px ${resolved.paddingX ?? base2.paddingX}px`;
    element.style.fontFamily = resolved.fontFamily ?? base2.fontFamily;
    element.style.fontSize = `${resolved.fontSize ?? base2.fontSize}px`;
    element.style.fontWeight = String(resolved.fontWeight ?? base2.fontWeight);
    element.style.lineHeight = String(resolved.lineHeight ?? base2.lineHeight);
    element.style.textAlign = resolved.textAlign ?? base2.textAlign;
    element.style.maxWidth = `${maxWidth}px`;
    if (html.length > 0) {
      element.innerHTML = html;
    } else {
      element.textContent = text5.length === 0 ? " " : text5;
    }
    const target2 = typeof input.querySelector === "string" && input.querySelector.trim().length > 0 ? element.querySelector(input.querySelector) ?? element : element;
    const rect = target2.getBoundingClientRect();
    return {
      width: Math.max(resolved.minWidth ?? base2.minWidth, Math.ceil(rect.width)),
      height: Math.max(resolved.minHeight ?? base2.minHeight, Math.ceil(rect.height))
    };
  };
  return {
    measure,
    destroy: () => {
      container.remove();
    }
  };
}
function stripHtml(input) {
  return input.replace(/<[^>]*>/g, "");
}

// ../react/src/export-beautify-assets.ts
var VAN_GOGH_EXPORT_DECORATION_DATA_URLS = {
  starryCorner: "data:image/png;base64, ",
  starryTopStroke: "data:image/png;base64, ",
  starryLeftStroke: "data:image/png;base64, ",
  sunflowerCorner: "data:image/png;base64, ",
  sunflowerBottomLeft: "data:image/png;base64, ",
  sunflowerBottomStroke: "data:image/png;base64, ",
  nightBloomCorner: "data:image/png;base64, ",
  nightBloomRightStroke: "data:image/png;base64, ",
  nightBloomBottomStroke: "data:image/png;base64, "
};

// ../react/src/export-guards.ts
var HARD_MAX_CANVAS_SIDE = 32767;
var FALLBACK_MAX_CANVAS_SIDE = 16384;
var DEFAULT_MAX_PIXELS = 1e8;
var cachedMaxSide = null;
function formatBytes(bytes) {
  const safe = Number.isFinite(bytes) ? Math.max(0, bytes) : 0;
  const units = ["B", "KB", "MB", "GB"];
  let value = safe;
  let unitIndex = 0;
  while (value >= 1024 && unitIndex < units.length - 1) {
    value /= 1024;
    unitIndex += 1;
  }
  const precision = unitIndex === 0 ? 0 : value >= 100 ? 0 : value >= 10 ? 1 : 2;
  return `${value.toFixed(precision)}${units[unitIndex]}`;
}
function resolveWebglMaxTextureSize() {
  if (typeof document === "undefined") return null;
  try {
    const canvas = document.createElement("canvas");
    const gl = canvas.getContext("webgl") ?? canvas.getContext("experimental-webgl");
    if (!gl) return null;
    const raw = gl.getParameter(gl.MAX_TEXTURE_SIZE);
    const value = typeof raw === "number" ? raw : Number(raw);
    if (!Number.isFinite(value) || value <= 0) return null;
    return value;
  } catch {
    return null;
  }
}
function resolveMaxCanvasSide() {
  if (cachedMaxSide != null) return cachedMaxSide;
  const webglMax = resolveWebglMaxTextureSize();
  cachedMaxSide = Math.max(1, Math.min(HARD_MAX_CANVAS_SIDE, webglMax ?? FALLBACK_MAX_CANVAS_SIDE));
  return cachedMaxSide;
}
function resolvePngExportLimits() {
  const maxSide = resolveMaxCanvasSide();
  const maxPixels = Math.min(DEFAULT_MAX_PIXELS, maxSide * maxSide);
  return { maxSide, maxPixels };
}
function estimatePngExport(bounds, args) {
  const padding = Number.isFinite(args.padding) ? Math.max(0, args.padding) : 0;
  const scale = Number.isFinite(args.scale) ? Math.max(0.01, args.scale) : 1;
  if (!Number.isFinite(bounds.width) || !Number.isFinite(bounds.height)) {
    return {
      width: 1,
      height: 1,
      padding,
      scale,
      widthPx: 1,
      heightPx: 1,
      pixels: 1,
      bytes: 4
    };
  }
  const width = Math.max(1, bounds.width + padding * 2);
  const height = Math.max(1, bounds.height + padding * 2);
  const widthPx = Math.ceil(width * scale);
  const heightPx = Math.ceil(height * scale);
  const pixels = widthPx * heightPx;
  const bytes = pixels * 4;
  return { width, height, padding, scale, widthPx, heightPx, pixels, bytes };
}
function assertPngExportSafe(bounds, args) {
  const estimate = estimatePngExport(bounds, { padding: args.padding, scale: args.scale });
  assertPngExportDimensionsSafe({
    width: estimate.width,
    height: estimate.height,
    scale: estimate.scale,
    mode: args.mode,
    padding: estimate.padding
  });
}
function assertPngExportDimensionsSafe(args) {
  const width = Number.isFinite(args.width) ? Math.max(1, args.width) : 1;
  const height = Number.isFinite(args.height) ? Math.max(1, args.height) : 1;
  const scale = Number.isFinite(args.scale) ? Math.max(0.01, args.scale) : 1;
  const widthPx = Math.ceil(width * scale);
  const heightPx = Math.ceil(height * scale);
  const pixels = widthPx * heightPx;
  const bytes = pixels * 4;
  const estimate = {
    width,
    height,
    padding: args.padding ?? 0,
    scale,
    widthPx,
    heightPx,
    pixels,
    bytes
  };
  const limits = resolvePngExportLimits();
  const exceedsSide = estimate.widthPx > limits.maxSide || estimate.heightPx > limits.maxSide;
  const exceedsPixels = estimate.pixels > limits.maxPixels;
  if (!exceedsSide && !exceedsPixels) return;
  const maxScaleBySide = Math.min(limits.maxSide / estimate.width, limits.maxSide / estimate.height);
  const maxScaleByPixels = Math.sqrt(limits.maxPixels / (estimate.width * estimate.height));
  const suggestedScale = Math.max(0.1, Math.floor(Math.min(maxScaleBySide, maxScaleByPixels) * 10) / 10);
  const modeLabel = args.mode ? ` (${args.mode})` : "";
  const reasons = [];
  if (exceedsSide) reasons.push(`max side\u2248${limits.maxSide}px`);
  if (exceedsPixels) reasons.push(`max pixels\u2248${limits.maxPixels.toLocaleString()}`);
  throw new Error(
    [
      `PNG export${modeLabel} aborted: target bitmap ${estimate.widthPx}\xD7${estimate.heightPx}px (scale=${estimate.scale}, padding=${estimate.padding}) ~${formatBytes(estimate.bytes)} is too large (${reasons.join(", ")}).`,
      `Try reducing scale (<=${suggestedScale}), collapsing nodes, or exporting SVG.`
    ].join(" ")
  );
}

// ../react/src/export.ts
var defaultTextStyle = {
  fontFamily: "ui-sans-serif, system-ui, sans-serif",
  fontSize: 14,
  lineHeight: 1.4,
  paddingX: 12,
  paddingY: 8,
  color: "#0f172a"
};
var defaultExportPadding = 80;
var VAN_GOGH_DECORATION_ASSET_KEYS_BY_VARIANT = {
  "starry-corner": {
    corner: "starryCorner",
    topStroke: "starryTopStroke",
    leftStroke: "starryLeftStroke"
  },
  "sunflower-corner": {
    corner: "sunflowerCorner",
    secondaryCorner: "sunflowerBottomLeft",
    bottomStroke: "sunflowerBottomStroke"
  },
  "night-bloom": {
    corner: "nightBloomCorner",
    rightStroke: "nightBloomRightStroke",
    bottomStroke: "nightBloomBottomStroke"
  }
};
var vanGoghDecorationImageCache = /* @__PURE__ */ new Map();
function downloadBlob(blob, filename) {
  const url = URL.createObjectURL(blob);
  const link = document.createElement("a");
  link.href = url;
  link.download = filename;
  document.body.appendChild(link);
  link.click();
  link.remove();
  URL.revokeObjectURL(url);
}
function svgElementToString(svg, options = {}) {
  const cloned = svg.cloneNode(true);
  if (!cloned.getAttribute("xmlns")) {
    cloned.setAttribute("xmlns", "http://www.w3.org/2000/svg");
  }
  if (!cloned.getAttribute("xmlns:xlink")) {
    cloned.setAttribute("xmlns:xlink", "http://www.w3.org/1999/xlink");
  }
  options.transform?.(cloned);
  const serializer = new XMLSerializer();
  return serializer.serializeToString(cloned);
}
async function exportMindMapSvgBlob(svg, scene, options) {
  ensureDomAvailable();
  const mode = options.mode;
  const inlineAssets = options.inlineAssets ?? mode === "fidelity";
  const padding = options.padding ?? defaultExportPadding;
  const transformSvg = (cloned) => {
    stripExportExcludedNodes(cloned);
    applyExportFraming(cloned, scene.layout.bounds, padding);
    if (options.cssText) {
      injectCssIntoForeignObjects(cloned, options.cssText);
    }
    if (mode === "portable") {
      applyTextFallback(cloned, scene, options.textStyle ? { textStyle: options.textStyle } : {});
    }
  };
  const clonedString = svgElementToString(svg, { transform: transformSvg });
  if (inlineAssets) {
    const inlineCloned = await inlineSvgStringAssets(clonedString);
    return new Blob([inlineCloned], { type: "image/svg+xml;charset=utf-8" });
  }
  return new Blob([clonedString], { type: "image/svg+xml;charset=utf-8" });
}
async function exportMindMapPngBlob(svg, scene, options) {
  ensureDomAvailable();
  const scale = options.scale ?? 2;
  const background = options.background ?? "#ffffff";
  const padding = options.padding ?? defaultExportPadding;
  assertPngExportSafe(scene.layout.bounds, { padding, scale, mode: options.mode });
  if (options.mode === "fast") {
    const svgString = svgElementToString(svg, {
      transform: (cloned) => {
        stripExportExcludedNodes(cloned);
        applyExportFraming(cloned, scene.layout.bounds, padding);
        applyTextFallback(cloned, scene, options.textStyle ? { textStyle: options.textStyle } : {});
      }
    });
    const blob = await renderPngBlobFromSvgString(svgString, { mode: options.mode, scale, background, beautify: options.beautify });
    return { blob, usedFallback: false };
  }
  try {
    const svgString = svgElementToString(svg, {
      transform: (cloned) => {
        stripExportExcludedNodes(cloned);
        applyExportFraming(cloned, scene.layout.bounds, padding);
        if (options.cssText) {
          injectCssIntoForeignObjects(cloned, options.cssText);
        }
      }
    });
    const inlinedSvgString = options.inlineAssets === false ? svgString : await inlineSvgStringAssets(svgString);
    const blob = await renderPngBlobFromSvgString(inlinedSvgString, { mode: options.mode, scale, background, beautify: options.beautify });
    return { blob, usedFallback: false };
  } catch (error) {
    const svgString = svgElementToString(svg, {
      transform: (cloned) => {
        stripExportExcludedNodes(cloned);
        applyExportFraming(cloned, scene.layout.bounds, padding);
        applyTextFallback(cloned, scene, options.textStyle ? { textStyle: options.textStyle } : {});
      }
    });
    const blob = await renderPngBlobFromSvgString(svgString, { mode: options.mode, scale, background, beautify: options.beautify });
    return { blob, usedFallback: true };
  }
}
async function renderPngBlobFromSvgString(svgString, options) {
  const beautify = options.beautify;
  if (!beautify || beautify.kind === "none") {
    return svgStringToPngBlob(svgString, { scale: options.scale, background: options.background });
  }
  return svgStringToBeautifiedPngBlob(svgString, { ...options, beautify });
}
async function svgStringToPngBlob(svgString, options) {
  const src = await svgStringToDataUrl(svgString);
  const image = await loadImage(src);
  const width = Math.ceil(image.width * options.scale);
  const height = Math.ceil(image.height * options.scale);
  const canvas = document.createElement("canvas");
  canvas.width = width;
  canvas.height = height;
  const ctx = canvas.getContext("2d");
  if (!ctx) throw new Error("2D canvas context not available");
  if (options.background) {
    ctx.fillStyle = options.background;
    ctx.fillRect(0, 0, width, height);
  }
  ctx.setTransform(options.scale, 0, 0, options.scale, 0, 0);
  ctx.drawImage(image, 0, 0);
  return canvasToBlob(canvas, "image/png");
}
async function svgStringToBeautifiedPngBlob(svgString, options) {
  const src = await svgStringToDataUrl(svgString);
  const image = await loadImage(src);
  const mapWidth = Math.max(1, image.naturalWidth || image.width || 1);
  const mapHeight = Math.max(1, image.naturalHeight || image.height || 1);
  const appearance = resolveBeautifyAppearance(options.beautify.appearance ?? "auto", options.background);
  const layout = resolveBeautifiedExportLayout({
    mapWidth,
    mapHeight,
    preset: options.beautify
  });
  assertPngExportDimensionsSafe({
    width: layout.outerWidth,
    height: layout.outerHeight,
    scale: options.scale,
    mode: `${options.mode}/${options.beautify.kind}`
  });
  const canvas = document.createElement("canvas");
  canvas.width = Math.ceil(layout.outerWidth * options.scale);
  canvas.height = Math.ceil(layout.outerHeight * options.scale);
  const ctx = canvas.getContext("2d");
  if (!ctx) throw new Error("2D canvas context not available");
  const vanGoghDecorationImages = options.beautify.kind === "vangogh" ? await loadVanGoghDecorationImages(options.beautify.variant) : null;
  ctx.setTransform(options.scale, 0, 0, options.scale, 0, 0);
  drawBeautifiedExport(ctx, image, {
    appearance,
    background: options.background,
    layout,
    preset: options.beautify,
    vanGoghDecorationImages
  });
  return canvasToBlob(canvas, "image/png");
}
function resolveBeautifiedExportLayout(args) {
  const minSide = Math.min(args.mapWidth, args.mapHeight);
  if (args.preset.kind === "window") {
    const outerPad = clamp(minSide * 0.05, 22, 46);
    const titleBarHeight = clamp(minSide * 0.055, 28, 42);
    const cardWidth2 = args.mapWidth;
    const cardHeight2 = args.mapHeight + titleBarHeight;
    return {
      outerWidth: cardWidth2 + outerPad * 2,
      outerHeight: cardHeight2 + outerPad * 2,
      mapX: outerPad,
      mapY: outerPad + titleBarHeight,
      mapWidth: args.mapWidth,
      mapHeight: args.mapHeight,
      cardX: outerPad,
      cardY: outerPad,
      cardWidth: cardWidth2,
      cardHeight: cardHeight2,
      frame: 0,
      frameTop: titleBarHeight,
      frameRight: 0,
      frameBottom: 0,
      frameLeft: 0,
      titleBarHeight
    };
  }
  if (args.preset.kind === "vangogh") {
    return {
      outerWidth: args.mapWidth,
      outerHeight: args.mapHeight,
      mapX: 0,
      mapY: 0,
      mapWidth: args.mapWidth,
      mapHeight: args.mapHeight,
      cardX: 0,
      cardY: 0,
      cardWidth: args.mapWidth,
      cardHeight: args.mapHeight,
      frame: 0,
      frameTop: 0,
      frameRight: 0,
      frameBottom: 0,
      frameLeft: 0,
      titleBarHeight: 0
    };
  }
  const frame = clamp(minSide * 0.07, 30, 68);
  const cardWidth = args.mapWidth + frame * 2;
  const cardHeight = args.mapHeight + frame * 2;
  return {
    outerWidth: cardWidth,
    outerHeight: cardHeight,
    mapX: frame,
    mapY: frame,
    mapWidth: args.mapWidth,
    mapHeight: args.mapHeight,
    cardX: 0,
    cardY: 0,
    cardWidth,
    cardHeight,
    frame,
    frameTop: frame,
    frameRight: frame,
    frameBottom: frame,
    frameLeft: frame,
    titleBarHeight: 0
  };
}
function drawBeautifiedExport(ctx, image, args) {
  const palette = resolveBeautifyPalette(args.appearance);
  ctx.save();
  if (args.preset.kind === "window") {
    ctx.fillStyle = palette.ambient;
    ctx.fillRect(0, 0, args.layout.outerWidth, args.layout.outerHeight);
    drawWindowExport(ctx, image, { ...args, variant: args.preset.variant ?? "soft-shadow" });
  } else if (args.preset.kind === "mondrian") {
    drawMondrianExport(ctx, image, { ...args, variant: args.preset.variant });
  } else {
    if (!args.vanGoghDecorationImages) throw new Error("Van Gogh export decoration assets are not loaded.");
    drawVanGoghExport(ctx, image, { ...args, decorationImages: args.vanGoghDecorationImages, variant: args.preset.variant });
  }
  ctx.restore();
}
function drawWindowExport(ctx, image, args) {
  const palette = resolveBeautifyPalette(args.appearance);
  const { cardX, cardY, cardWidth, cardHeight, titleBarHeight, mapX, mapY, mapWidth, mapHeight } = args.layout;
  const radius = clamp(Math.min(cardWidth, cardHeight) * 0.025, 12, 18);
  drawWindowAmbient(ctx, args.layout, args.appearance, args.variant, palette, radius);
  ctx.save();
  const shadow = resolveWindowShadow(args.appearance, args.variant);
  ctx.shadowColor = shadow.color;
  ctx.shadowBlur = shadow.blur;
  ctx.shadowOffsetY = shadow.offsetY;
  fillRoundedRect(ctx, cardX, cardY, cardWidth, cardHeight, radius, palette.card);
  ctx.restore();
  ctx.save();
  roundedRectPath(ctx, cardX, cardY, cardWidth, cardHeight, radius);
  ctx.clip();
  ctx.fillStyle = palette.card;
  ctx.fillRect(cardX, cardY, cardWidth, cardHeight);
  ctx.fillStyle = palette.windowBar;
  ctx.fillRect(cardX, cardY, cardWidth, titleBarHeight);
  ctx.fillStyle = args.background;
  ctx.fillRect(mapX, mapY, mapWidth, mapHeight);
  ctx.drawImage(image, mapX, mapY, mapWidth, mapHeight);
  ctx.restore();
  strokeRoundedRect(ctx, cardX, cardY, cardWidth, cardHeight, radius, palette.border, 1);
  const dotRadius = clamp(titleBarHeight * 0.16, 4, 6);
  const dotY = cardY + titleBarHeight / 2;
  const firstDotX = cardX + clamp(titleBarHeight * 0.62, 18, 26);
  drawCircle(ctx, firstDotX, dotY, dotRadius, "#ff5f57");
  drawCircle(ctx, firstDotX + dotRadius * 3.2, dotY, dotRadius, "#ffbd2e");
  drawCircle(ctx, firstDotX + dotRadius * 6.4, dotY, dotRadius, "#28c840");
}
function resolveWindowShadow(appearance, variant) {
  if (variant === "aurora-glow") {
    return {
      color: appearance === "dark" ? "rgba(56, 189, 248, 0.34)" : "rgba(37, 99, 235, 0.2)",
      blur: appearance === "dark" ? 46 : 38,
      offsetY: 16
    };
  }
  if (variant === "frosted-blur") {
    return {
      color: appearance === "dark" ? "rgba(15, 23, 42, 0.48)" : "rgba(15, 23, 42, 0.2)",
      blur: appearance === "dark" ? 40 : 34,
      offsetY: 18
    };
  }
  return {
    color: appearance === "dark" ? "rgba(2, 6, 23, 0.5)" : "rgba(15, 23, 42, 0.18)",
    blur: appearance === "dark" ? 34 : 30,
    offsetY: 16
  };
}
function drawWindowAmbient(ctx, layout, appearance, variant, palette, radius) {
  const { cardX, cardY, cardWidth, cardHeight, outerWidth, outerHeight } = layout;
  ctx.save();
  if (variant === "soft-shadow") {
    const glow = appearance === "dark" ? "#020617" : "#94a3b8";
    ctx.globalAlpha = appearance === "dark" ? 0.32 : 0.16;
    ctx.filter = "blur(18px)";
    fillRoundedRect(ctx, cardX + 8, cardY + 14, cardWidth - 16, cardHeight - 8, radius + 8, glow);
    ctx.restore();
    return;
  }
  if (variant === "frosted-blur") {
    ctx.globalAlpha = appearance === "dark" ? 0.3 : 0.42;
    ctx.filter = "blur(22px)";
    fillRoundedRect(
      ctx,
      Math.max(0, cardX - 18),
      Math.max(0, cardY - 16),
      Math.min(outerWidth, cardWidth + 36),
      Math.min(outerHeight, cardHeight + 34),
      radius + 16,
      appearance === "dark" ? "rgba(96, 165, 250, 0.22)" : "rgba(255, 255, 255, 0.78)"
    );
    ctx.globalAlpha = appearance === "dark" ? 0.18 : 0.22;
    fillRoundedRect(
      ctx,
      cardX + cardWidth * 0.08,
      Math.max(0, cardY - 10),
      cardWidth * 0.74,
      cardHeight * 0.26,
      radius,
      appearance === "dark" ? "rgba(148, 163, 184, 0.22)" : "rgba(148, 163, 184, 0.34)"
    );
    ctx.restore();
    return;
  }
  ctx.globalAlpha = appearance === "dark" ? 0.32 : 0.22;
  ctx.filter = "blur(24px)";
  const cyan = ctx.createLinearGradient(cardX, cardY, cardX + cardWidth, cardY + cardHeight);
  cyan.addColorStop(0, appearance === "dark" ? "rgba(34, 211, 238, 0.34)" : "rgba(56, 189, 248, 0.26)");
  cyan.addColorStop(0.5, appearance === "dark" ? "rgba(59, 130, 246, 0.22)" : "rgba(37, 99, 235, 0.14)");
  cyan.addColorStop(1, "rgba(20, 184, 166, 0)");
  ctx.fillStyle = cyan;
  roundedRectPath(ctx, Math.max(0, cardX - 18), Math.max(0, cardY - 16), Math.min(outerWidth, cardWidth + 36), Math.min(outerHeight, cardHeight + 34), radius + 18);
  ctx.fill();
  ctx.globalAlpha = appearance === "dark" ? 0.18 : 0.14;
  ctx.fillStyle = appearance === "dark" ? "#f59e0b" : "#fbbf24";
  ctx.filter = "blur(28px)";
  fillRoundedRect(ctx, cardX + cardWidth * 0.58, cardY + cardHeight * 0.08, cardWidth * 0.28, cardHeight * 0.24, radius, ctx.fillStyle);
  ctx.restore();
  ctx.save();
  ctx.globalAlpha = appearance === "dark" ? 0.16 : 0.12;
  ctx.strokeStyle = palette.border;
  ctx.lineWidth = 1;
  strokeRoundedRect(ctx, Math.max(0.5, cardX - 8), Math.max(0.5, cardY - 8), Math.min(outerWidth - 1, cardWidth + 16), Math.min(outerHeight - 1, cardHeight + 16), radius + 10, palette.border, 1);
  ctx.restore();
}
function drawMondrianExport(ctx, image, args) {
  const palette = resolveBeautifyPalette(args.appearance);
  const { cardX, cardY, cardWidth, cardHeight, mapX, mapY, mapWidth, mapHeight, frame } = args.layout;
  const radius = 8;
  drawCardBase(ctx, args.layout, palette);
  ctx.fillStyle = args.background;
  ctx.fillRect(mapX, mapY, mapWidth, mapHeight);
  ctx.drawImage(image, mapX, mapY, mapWidth, mapHeight);
  ctx.save();
  roundedRectPath(ctx, cardX, cardY, cardWidth, cardHeight, radius);
  ctx.clip();
  const line = args.appearance === "dark" ? "rgba(226, 232, 240, 0.88)" : "#111827";
  const width = Math.max(2.2, Math.round(frame * 0.075));
  ctx.strokeStyle = line;
  ctx.lineWidth = width;
  if (args.variant === "gallery-grid") {
    drawMondrianGrid(ctx, args.layout, [
      { x: cardX, y: cardY, w: frame * 0.72, h: frame * 0.72, color: palette.red },
      { x: cardX + cardWidth - frame * 0.86, y: cardY, w: frame * 0.62, h: frame * 0.5, color: palette.blue },
      { x: cardX, y: mapY + mapHeight * 0.34, w: frame * 0.58, h: frame * 1.25, color: palette.yellow },
      { x: cardX, y: cardY + cardHeight - frame * 0.96, w: frame * 0.72, h: frame * 0.72, color: palette.blue },
      { x: cardX + cardWidth - frame * 1.02, y: cardY + cardHeight - frame * 1.02, w: frame * 0.78, h: frame * 0.78, color: palette.red }
    ], line, width);
  } else if (args.variant === "bold-blocks") {
    drawMondrianGrid(ctx, args.layout, [
      { x: cardX, y: cardY, w: frame * 2.35, h: frame * 1.52, color: palette.red },
      { x: cardX, y: mapY + mapHeight * 0.46, w: frame * 0.82, h: frame * 2.15, color: palette.yellow },
      { x: cardX, y: cardY + cardHeight - frame * 1.24, w: frame * 2.1, h: frame * 1, color: palette.blue },
      { x: cardX + cardWidth - frame * 1.4, y: cardY, w: frame * 1.16, h: frame * 1.55, color: palette.blue },
      { x: cardX + cardWidth - frame * 2.35, y: cardY + cardHeight - frame * 1.24, w: frame * 2.1, h: frame * 1, color: palette.red },
      { x: cardX + cardWidth - frame * 3.34, y: cardY + cardHeight - frame * 1.24, w: frame * 1, h: frame * 1, color: palette.yellow }
    ], line, width);
  } else {
    drawMondrianGrid(ctx, args.layout, [
      { x: cardX, y: cardY, w: frame * 0.56, h: frame * 0.56, color: palette.red },
      { x: cardX + cardWidth - frame * 0.82, y: cardY + cardHeight - frame * 0.82, w: frame * 0.58, h: frame * 0.58, color: palette.blue }
    ], line, width, "minimal");
  }
  ctx.restore();
  strokeRoundedRect(ctx, cardX, cardY, cardWidth, cardHeight, radius, palette.border, 1);
}
function drawVanGoghExport(ctx, image, args) {
  const { cardX, cardY, cardWidth, cardHeight, mapX, mapY, mapWidth, mapHeight } = args.layout;
  ctx.fillStyle = args.background;
  ctx.fillRect(mapX, mapY, mapWidth, mapHeight);
  ctx.drawImage(image, mapX, mapY, mapWidth, mapHeight);
  ctx.save();
  ctx.beginPath();
  ctx.rect(cardX, cardY, cardWidth, cardHeight);
  ctx.clip();
  drawVanGoghDecoration(ctx, args.decorationImages, args.layout, args.appearance, args.variant);
  ctx.restore();
}
function drawCardBase(ctx, layout, palette) {
  const radius = 14;
  ctx.save();
  ctx.shadowColor = palette.shadow;
  ctx.shadowBlur = 24;
  ctx.shadowOffsetY = 12;
  fillRoundedRect(ctx, layout.cardX, layout.cardY, layout.cardWidth, layout.cardHeight, radius, palette.card);
  ctx.restore();
}
function drawMondrianGrid(ctx, layout, blocks, line, lineWidth, style2 = "grid") {
  const { cardX, cardY, cardWidth, cardHeight, mapX, mapY, mapWidth, mapHeight, frame } = layout;
  const inset = Math.max(1, lineWidth * 0.5);
  ctx.save();
  ctx.lineJoin = "miter";
  ctx.lineCap = "butt";
  ctx.strokeStyle = line;
  ctx.lineWidth = lineWidth;
  ctx.strokeRect(cardX + inset, cardY + inset, cardWidth - inset * 2, cardHeight - inset * 2);
  if (style2 === "minimal") {
    ctx.beginPath();
    ctx.moveTo(cardX, mapY);
    ctx.lineTo(cardX + cardWidth, mapY);
    ctx.moveTo(mapX, cardY);
    ctx.lineTo(mapX, cardY + cardHeight);
    ctx.stroke();
  } else {
    ctx.strokeRect(mapX, mapY, mapWidth, mapHeight);
    ctx.beginPath();
    ctx.moveTo(mapX, cardY);
    ctx.lineTo(mapX, cardY + cardHeight);
    ctx.moveTo(mapX + mapWidth, cardY);
    ctx.lineTo(mapX + mapWidth, cardY + cardHeight);
    ctx.moveTo(cardX, mapY);
    ctx.lineTo(cardX + cardWidth, mapY);
    ctx.moveTo(cardX, mapY + mapHeight);
    ctx.lineTo(cardX + cardWidth, mapY + mapHeight);
    ctx.moveTo(cardX + frame * 0.62, cardY);
    ctx.lineTo(cardX + frame * 0.62, mapY);
    ctx.moveTo(cardX, cardY + frame * 0.62);
    ctx.lineTo(mapX, cardY + frame * 0.62);
    ctx.moveTo(cardX + cardWidth - frame * 0.82, cardY);
    ctx.lineTo(cardX + cardWidth - frame * 0.82, mapY);
    ctx.moveTo(mapX + mapWidth, cardY + frame * 0.56);
    ctx.lineTo(cardX + cardWidth, cardY + frame * 0.56);
    ctx.moveTo(cardX, cardY + cardHeight - frame * 0.88);
    ctx.lineTo(mapX, cardY + cardHeight - frame * 0.88);
    ctx.moveTo(cardX + cardWidth - frame * 1.02, mapY + mapHeight);
    ctx.lineTo(cardX + cardWidth - frame * 1.02, cardY + cardHeight);
    ctx.stroke();
  }
  for (const block of blocks) {
    ctx.fillStyle = block.color;
    ctx.fillRect(block.x, block.y, block.w, block.h);
    ctx.strokeStyle = line;
    ctx.lineWidth = lineWidth;
    ctx.strokeRect(block.x, block.y, block.w, block.h);
  }
  ctx.restore();
}
function drawVanGoghDecoration(ctx, images, layout, appearance, variant) {
  const minSide = Math.min(layout.cardWidth, layout.cardHeight);
  const edgeThickness = clamp(minSide * 0.045, 20, 48);
  const cornerSize = clamp(minSide * 0.22, 118, 250);
  const inset = clamp(minSide * 4e-3, 1, 4);
  const alpha2 = appearance === "dark" ? 0.96 : 0.9;
  ctx.save();
  ctx.globalAlpha = alpha2;
  if (variant === "starry-corner") {
    if (!images.corner || !images.topStroke || !images.leftStroke) {
      throw new Error("Van Gogh starry decoration assets are not loaded.");
    }
    drawImageContained(ctx, images.corner, {
      x: layout.cardX + inset,
      y: layout.cardY + inset,
      width: cornerSize,
      height: cornerSize,
      anchorX: "left",
      anchorY: "top"
    });
    drawHorizontalDecorationStroke(ctx, images.topStroke, {
      x: layout.cardX + cornerSize * 0.72,
      y: layout.cardY + inset,
      width: Math.max(0, layout.cardWidth - cornerSize * 0.84),
      height: edgeThickness * 0.86
    });
    drawVerticalDecorationStroke(ctx, images.leftStroke, {
      x: layout.cardX + inset,
      y: layout.cardY + cornerSize * 0.74,
      width: edgeThickness * 0.86,
      height: Math.max(0, layout.cardHeight - cornerSize * 0.88)
    });
  } else if (variant === "sunflower-corner") {
    if (!images.corner || !images.secondaryCorner || !images.bottomStroke) {
      throw new Error("Van Gogh sunflower decoration assets are not loaded.");
    }
    drawImageContained(ctx, images.corner, {
      x: layout.cardX + layout.cardWidth - cornerSize - inset,
      y: layout.cardY + inset,
      width: cornerSize,
      height: cornerSize * 0.92,
      anchorX: "right",
      anchorY: "top"
    });
    drawImageContained(ctx, images.secondaryCorner, {
      x: layout.cardX + inset,
      y: layout.cardY + layout.cardHeight - cornerSize * 0.72 - inset,
      width: cornerSize * 0.82,
      height: cornerSize * 0.72,
      anchorX: "left",
      anchorY: "bottom"
    });
    drawHorizontalDecorationStroke(ctx, images.bottomStroke, {
      x: layout.cardX + cornerSize * 0.62,
      y: layout.cardY + layout.cardHeight - edgeThickness - inset,
      width: Math.max(0, layout.cardWidth - cornerSize * 1.05),
      height: edgeThickness
    });
  } else {
    if (!images.corner || !images.rightStroke || !images.bottomStroke) {
      throw new Error("Van Gogh night bloom decoration assets are not loaded.");
    }
    drawVerticalDecorationStroke(ctx, images.rightStroke, {
      x: layout.cardX + layout.cardWidth - edgeThickness - inset,
      y: layout.cardY + inset,
      width: edgeThickness * 0.75,
      height: Math.max(0, layout.cardHeight - cornerSize * 0.9)
    });
    drawHorizontalDecorationStroke(ctx, images.bottomStroke, {
      x: layout.cardX + cornerSize * 0.86,
      y: layout.cardY + layout.cardHeight - edgeThickness - inset,
      width: Math.max(0, layout.cardWidth - cornerSize * 1.3),
      height: edgeThickness * 0.92
    });
    drawImageContained(ctx, images.corner, {
      x: layout.cardX + layout.cardWidth - cornerSize - inset,
      y: layout.cardY + layout.cardHeight - cornerSize - inset,
      width: cornerSize,
      height: cornerSize,
      anchorX: "right",
      anchorY: "bottom"
    });
  }
  ctx.restore();
}
function drawImageContained(ctx, image, args) {
  if (args.width <= 0 || args.height <= 0) return;
  const imageWidth = image.naturalWidth || image.width;
  const imageHeight = image.naturalHeight || image.height;
  if (imageWidth <= 0 || imageHeight <= 0) return;
  const scale = Math.min(args.width / imageWidth, args.height / imageHeight);
  const width = imageWidth * scale;
  const height = imageHeight * scale;
  const x5 = args.anchorX === "right" ? args.x + args.width - width : args.x;
  const y = args.anchorY === "bottom" ? args.y + args.height - height : args.y;
  ctx.drawImage(image, x5, y, width, height);
}
function drawHorizontalDecorationStroke(ctx, image, args) {
  if (args.width <= 0 || args.height <= 0) return;
  ctx.drawImage(image, args.x, args.y, args.width, args.height);
}
function drawVerticalDecorationStroke(ctx, image, args) {
  if (args.width <= 0 || args.height <= 0) return;
  ctx.drawImage(image, args.x, args.y, args.width, args.height);
}
function resolveBeautifyAppearance(appearance, background) {
  if (appearance === "light" || appearance === "dark") return appearance;
  return resolveColorLuminance(background) < 0.46 ? "dark" : "light";
}
function resolveColorLuminance(color) {
  const rgb = parseCssColor(color);
  if (!rgb) return 1;
  const [r2, g, b2] = rgb.map((value) => {
    const channel = value / 255;
    return channel <= 0.03928 ? channel / 12.92 : ((channel + 0.055) / 1.055) ** 2.4;
  });
  return 0.2126 * (r2 ?? 0) + 0.7152 * (g ?? 0) + 0.0722 * (b2 ?? 0);
}
function parseCssColor(color) {
  const value = color.trim();
  const hex = value.match(/^#([0-9a-f]{3}|[0-9a-f]{6})$/i);
  if (hex) {
    const raw = hex[1] ?? "";
    if (raw.length === 3) {
      return [
        parseInt(raw[0] + raw[0], 16),
        parseInt(raw[1] + raw[1], 16),
        parseInt(raw[2] + raw[2], 16)
      ];
    }
    return [
      parseInt(raw.slice(0, 2), 16),
      parseInt(raw.slice(2, 4), 16),
      parseInt(raw.slice(4, 6), 16)
    ];
  }
  const rgb = value.match(/^rgba?\(([^)]+)\)$/i);
  if (!rgb) return null;
  const parts = (rgb[1] ?? "").split(",").map((part) => Number(part.trim()));
  if (parts.length < 3 || parts.slice(0, 3).some((part) => !Number.isFinite(part))) return null;
  return [
    clamp(parts[0] ?? 0, 0, 255),
    clamp(parts[1] ?? 0, 0, 255),
    clamp(parts[2] ?? 0, 0, 255)
  ];
}
function resolveBeautifyPalette(appearance) {
  if (appearance === "dark") {
    return {
      ambient: "#0b1220",
      card: "#111827",
      border: "rgba(226, 232, 240, 0.16)",
      shadow: "rgba(0, 0, 0, 0.42)",
      windowBar: "rgba(255, 255, 255, 0.07)",
      red: "#dc2626",
      yellow: "#eab308",
      blue: "#2563eb"
    };
  }
  return {
    ambient: "#f6f8fb",
    card: "#ffffff",
    border: "rgba(15, 23, 42, 0.12)",
    shadow: "rgba(15, 23, 42, 0.16)",
    windowBar: "#eef2f7",
    red: "#ef231c",
    yellow: "#facc15",
    blue: "#1d4ed8"
  };
}
function roundedRectPath(ctx, x5, y, width, height, radius) {
  const r2 = Math.min(radius, width / 2, height / 2);
  ctx.beginPath();
  ctx.moveTo(x5 + r2, y);
  ctx.lineTo(x5 + width - r2, y);
  ctx.quadraticCurveTo(x5 + width, y, x5 + width, y + r2);
  ctx.lineTo(x5 + width, y + height - r2);
  ctx.quadraticCurveTo(x5 + width, y + height, x5 + width - r2, y + height);
  ctx.lineTo(x5 + r2, y + height);
  ctx.quadraticCurveTo(x5, y + height, x5, y + height - r2);
  ctx.lineTo(x5, y + r2);
  ctx.quadraticCurveTo(x5, y, x5 + r2, y);
  ctx.closePath();
}
function fillRoundedRect(ctx, x5, y, width, height, radius, color) {
  roundedRectPath(ctx, x5, y, width, height, radius);
  ctx.fillStyle = color;
  ctx.fill();
}
function strokeRoundedRect(ctx, x5, y, width, height, radius, color, lineWidth) {
  roundedRectPath(ctx, x5, y, width, height, radius);
  ctx.strokeStyle = color;
  ctx.lineWidth = lineWidth;
  ctx.stroke();
}
function drawCircle(ctx, x5, y, radius, color) {
  ctx.beginPath();
  ctx.arc(x5, y, radius, 0, Math.PI * 2);
  ctx.fillStyle = color;
  ctx.fill();
}
function clamp(value, min, max) {
  return Math.max(min, Math.min(max, value));
}
function loadVanGoghDecorationImages(variant) {
  const cached = vanGoghDecorationImageCache.get(variant);
  if (cached) return cached;
  const assetKeys = VAN_GOGH_DECORATION_ASSET_KEYS_BY_VARIANT[variant];
  const promise = Promise.all(
    Object.entries(assetKeys).map(async ([role, assetKey]) => {
      const src = VAN_GOGH_EXPORT_DECORATION_DATA_URLS[assetKey];
      const image = await loadImage(src);
      return [role, image];
    })
  ).then((entries) => Object.fromEntries(entries));
  vanGoghDecorationImageCache.set(variant, promise);
  return promise;
}
function loadImage(src) {
  return new Promise((resolve, reject) => {
    const image = new Image();
    image.crossOrigin = "anonymous";
    image.onload = () => resolve(image);
    image.onerror = () => reject(new Error("Failed to load image"));
    image.src = src;
  });
}
function canvasToBlob(canvas, type) {
  return new Promise((resolve, reject) => {
    canvas.toBlob((blob) => {
      if (!blob) {
        reject(new Error("Failed to create blob"));
        return;
      }
      resolve(blob);
    }, type);
  });
}
function ensureDomAvailable() {
  if (typeof document === "undefined") {
    throw new Error("Export requires a browser environment");
  }
}
function stripExportExcludedNodes(svg) {
  svg.querySelectorAll('[data-export-exclude="true"]').forEach((node) => node.remove());
}
function applyExportFraming(svg, bounds, padding) {
  const pad2 = Number.isFinite(padding) ? Math.max(0, padding) : defaultExportPadding;
  const x5 = bounds.minX - pad2;
  const y = bounds.minY - pad2;
  const width = Math.max(1, bounds.width + pad2 * 2);
  const height = Math.max(1, bounds.height + pad2 * 2);
  svg.setAttribute("viewBox", `${x5} ${y} ${width} ${height}`);
  svg.setAttribute("width", String(width));
  svg.setAttribute("height", String(height));
  svg.style.width = "";
  svg.style.height = "";
}
function svgStringToDataUrl(svgString) {
  const blob = new Blob([svgString], { type: "image/svg+xml;charset=utf-8" });
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = () => resolve(String(reader.result));
    reader.onerror = () => reject(new Error("Failed to create SVG data URL"));
    reader.readAsDataURL(blob);
  });
}
function injectCssIntoForeignObjects(svg, cssText) {
  const styleEl = document.createElement("style");
  styleEl.setAttribute("xmlns", "http://www.w3.org/1999/xhtml");
  styleEl.textContent = cssText;
  for (const foreignObject of Array.from(svg.querySelectorAll("foreignObject"))) {
    foreignObject.insertBefore(styleEl.cloneNode(true), foreignObject.firstChild);
  }
}
function applyTextFallback(svg, scene, options = {}) {
  svg.querySelectorAll("foreignObject").forEach((node) => node.remove());
  const textStyle = { ...defaultTextStyle, ...options.textStyle };
  const svgNs = "http://www.w3.org/2000/svg";
  const canvas = document.createElement("canvas");
  const ctx = canvas.getContext("2d");
  if (!ctx) return;
  ctx.font = `${textStyle.fontSize}px ${textStyle.fontFamily}`;
  const wrapText = (text5, maxWidth) => {
    const paragraphs = text5.split("\n");
    const lines = [];
    for (const paragraph of paragraphs) {
      if (paragraph.length === 0) {
        lines.push("");
        continue;
      }
      let current = "";
      for (const char of Array.from(paragraph)) {
        const next = `${current}${char}`;
        if (current.length === 0 || ctx.measureText(next).width <= maxWidth) {
          current = next;
          continue;
        }
        lines.push(current);
        current = char;
      }
      lines.push(current);
    }
    return lines;
  };
  const groupById = /* @__PURE__ */ new Map();
  for (const group of Array.from(svg.querySelectorAll("g[data-node-id]"))) {
    const nodeId = group.getAttribute("data-node-id");
    if (nodeId) groupById.set(nodeId, group);
  }
  const summaryGroupById = /* @__PURE__ */ new Map();
  for (const group of Array.from(svg.querySelectorAll("g[data-summary-id]"))) {
    const summaryId = group.getAttribute("data-summary-id");
    if (summaryId) summaryGroupById.set(summaryId, group);
  }
  const lineHeightPx = textStyle.fontSize * textStyle.lineHeight;
  for (const nodeId of Object.keys(scene.layout.nodes)) {
    const node = scene.doc.nodes[nodeId];
    const nodeLayout = scene.layout.nodes[nodeId];
    if (!node || !nodeLayout) continue;
    const group = groupById.get(nodeId);
    if (!group) continue;
    const maxLineWidth = Math.max(0, nodeLayout.width - textStyle.paddingX * 2);
    const lines = wrapText(node.text, maxLineWidth);
    const textEl = document.createElementNS(svgNs, "text");
    textEl.setAttribute("x", String(nodeLayout.x + textStyle.paddingX));
    textEl.setAttribute("y", String(nodeLayout.y + textStyle.paddingY + textStyle.fontSize));
    textEl.setAttribute("fill", textStyle.color);
    textEl.setAttribute("font-family", textStyle.fontFamily);
    textEl.setAttribute("font-size", String(textStyle.fontSize));
    textEl.setAttribute("xml:space", "preserve");
    for (let index = 0; index < lines.length; index += 1) {
      const line = lines[index] ?? "";
      const tspan = document.createElementNS(svgNs, "tspan");
      tspan.setAttribute("x", String(nodeLayout.x + textStyle.paddingX));
      if (index > 0) {
        tspan.setAttribute("dy", String(lineHeightPx));
      }
      tspan.textContent = line.length === 0 ? " " : line;
      textEl.appendChild(tspan);
    }
    group.appendChild(textEl);
  }
  for (const summary of scene.doc.summaries) {
    const summaryLayout = scene.layout.summaries[summary.id];
    if (!summaryLayout) continue;
    const group = summaryGroupById.get(summary.id);
    if (!group) continue;
    const maxLineWidth = Math.max(0, summaryLayout.width - textStyle.paddingX * 2);
    const lines = wrapText(summary.text, maxLineWidth);
    const textEl = document.createElementNS(svgNs, "text");
    textEl.setAttribute("x", String(summaryLayout.x + textStyle.paddingX));
    textEl.setAttribute("y", String(summaryLayout.y + textStyle.paddingY + textStyle.fontSize));
    textEl.setAttribute("fill", textStyle.color);
    textEl.setAttribute("font-family", textStyle.fontFamily);
    textEl.setAttribute("font-size", String(textStyle.fontSize));
    textEl.setAttribute("xml:space", "preserve");
    for (let index = 0; index < lines.length; index += 1) {
      const line = lines[index] ?? "";
      const tspan = document.createElementNS(svgNs, "tspan");
      tspan.setAttribute("x", String(summaryLayout.x + textStyle.paddingX));
      if (index > 0) {
        tspan.setAttribute("dy", String(lineHeightPx));
      }
      tspan.textContent = line.length === 0 ? " " : line;
      textEl.appendChild(tspan);
    }
    group.appendChild(textEl);
  }
}
async function inlineSvgStringAssets(svgString) {
  ensureDomAvailable();
  const parser = new DOMParser();
  const doc3 = parser.parseFromString(svgString, "image/svg+xml");
  const svg = doc3.documentElement;
  await inlineSvgImages(svg);
  const serializer = new XMLSerializer();
  return serializer.serializeToString(svg);
}
async function inlineSvgImages(svg) {
  const tasks = [];
  for (const imageEl of Array.from(svg.querySelectorAll("image"))) {
    const href = imageEl.getAttribute("href") ?? imageEl.getAttribute("xlink:href");
    if (!href) continue;
    tasks.push(
      inlineUrlToDataUrl(href).then((dataUrl) => {
        imageEl.setAttribute("href", dataUrl);
        imageEl.removeAttribute("xlink:href");
      })
    );
  }
  for (const imgEl of Array.from(svg.querySelectorAll("foreignObject img"))) {
    const src = imgEl.getAttribute("src");
    if (!src) continue;
    tasks.push(
      inlineUrlToDataUrl(src).then((dataUrl) => {
        imgEl.setAttribute("src", dataUrl);
      })
    );
  }
  await Promise.all(tasks);
}
async function inlineUrlToDataUrl(url) {
  if (url.startsWith("data:")) return url;
  if (url.startsWith("blob:")) {
    const response2 = await fetch(url);
    if (!response2.ok) {
      throw new Error(`Failed to fetch asset for export: ${url}`);
    }
    const blob2 = await response2.blob();
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.onload = () => resolve(String(reader.result));
      reader.onerror = () => reject(new Error(`Failed to inline asset: ${url}`));
      reader.readAsDataURL(blob2);
    });
  }
  const resolved = new URL(url, window.location.href);
  if (resolved.origin !== window.location.origin) {
    throw new Error(`External assets are not allowed in exports: ${resolved.toString()}`);
  }
  const response = await fetch(resolved.toString(), { credentials: "same-origin" });
  if (!response.ok) {
    throw new Error(`Failed to fetch asset for export: ${resolved.toString()}`);
  }
  const blob = await response.blob();
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = () => resolve(String(reader.result));
    reader.onerror = () => reject(new Error(`Failed to inline asset: ${resolved.toString()}`));
    reader.readAsDataURL(blob);
  });
}

// ../react/src/mindmap-editor/editor.tsx
var import_react46 = __toESM(require_react(), 1);

// ../react/src/mindmap-editor/editor-view.tsx
var import_react30 = __toESM(require_react(), 1);
init_src();

// ../icons/src/builtin-icons-generated.ts
var BUILTIN_ICONS = [
  {
    id: "kmind-icon://builtin/basic/bolt",
    group: "basic",
    name: "bolt",
    label: "Bolt",
    catalog: { "groupId": "basic", "groupLabel": "Basic", "order": 100, "surfaces": ["node-content", "external-link"] },
    viewBox: "0 0 24 24",
    aliases: ["kmind-icon://basic/bolt"],
    svg: `<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false" width="100%" height="100%"><path d="M13 2L4 14h7l-1 8 10-14h-7l0-6z" fill="none" stroke="currentColor" stroke-width="2" stroke-linejoin="round"/></svg>`
  },
  {
    id: "kmind-icon://builtin/basic/flag",
    group: "basic",
    name: "flag",
    label: "Flag",
    catalog: { "groupId": "basic", "groupLabel": "Basic", "order": 100, "surfaces": ["node-content", "external-link"] },
    viewBox: "0 0 24 24",
    aliases: ["kmind-icon://basic/flag"],
    svg: `<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false" width="100%" height="100%"><path d="M5 3v18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"/><path d="M5 4h12l-2 4 2 4H5" fill="none" stroke="currentColor" stroke-width="2" stroke-linejoin="round"/></svg>`
  },
  {
    id: "kmind-icon://builtin/basic/folder",
    group: "basic",
    name: "folder",
    label: "Folder",
    catalog: { "groupId": "basic", "groupLabel": "Basic", "order": 100, "surfaces": ["node-content", "external-link"] },
    viewBox: "0 0 24 24",
    aliases: ["kmind-icon://basic/folder"],
    svg: `<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false" width="100%" height="100%"><path d="M3 6.5h6l2 2H21v9A2.5 2.5 0 0 1 18.5 20h-13A2.5 2.5 0 0 1 3 17.5v-11z" fill="none" stroke="currentColor" stroke-width="2" stroke-linejoin="round"/></svg>`
  },
  {
    id: "kmind-icon://builtin/basic/star",
    group: "basic",
    name: "star",
    label: "Star",
    catalog: { "groupId": "basic", "groupLabel": "Basic", "order": 100, "surfaces": ["node-content", "external-link"] },
    viewBox: "0 0 24 24",
    aliases: ["kmind-icon://basic/star"],
    svg: `<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false" width="100%" height="100%"><path d="M12 2l3.1 6.8L22 9.9l-5 4.9L18.2 22 12 18.6 5.8 22 7 14.8 2 9.9l6.9-1.1L12 2z" fill="none" stroke="currentColor" stroke-width="2" stroke-linejoin="round"/></svg>`
  },
  {
    id: "kmind-icon://builtin/brand/baidu",
    group: "brand",
    name: "baidu",
    label: "Baidu",
    catalog: { "groupId": "brand", "groupLabel": "Brand", "order": 200, "surfaces": ["node-content", "external-link"] },
    viewBox: "0 0 24 24",
    svg: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="100%" height="100%" aria-hidden="true" focusable="false"><path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M20.839 10.38h-8.656v3.33h5.065c-.092.81-.645 2.07-1.842 2.88c-.737.54-1.842.9-3.223.9c-3.079 0-5.525-2.572-5.525-5.58c0-2.923 2.585-5.49 5.525-5.49c1.75 0 2.855.72 3.591 1.35l2.579-2.52C16.787 3.9 14.669 3 12.183 3C8.592 3 5.461 4.98 3.987 7.95a8.8 8.8 0 0 0 0 8.1C5.461 19.02 8.592 21 12.183 21c2.486 0 4.604-.81 6.078-2.16c2.4-2.1 3.095-5.427 2.578-8.46"/></svg>`
  },
  {
    id: "kmind-icon://builtin/brand/siyuan",
    group: "brand",
    name: "siyuan",
    label: "SiYuan",
    catalog: { "groupId": "brand", "groupLabel": "Brand", "order": 200, "surfaces": ["node-content", "external-link"] },
    viewBox: "0 0 24 24",
    svg: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="100%" height="100%" aria-hidden="true" focusable="false"><g transform="scale(0.0234375)"><path fill="#d23f31" d="M37.052 371.676l269.857-269.857v550.507l-269.857 269.857z"/><path fill="#3b3e43" d="M306.909 101.818l205.091 205.091v550.507l-205.091-205.091z"/><path fill="#d23f31" d="M512 306.909l205.091-205.091v550.507l-205.091 205.091z"/><path fill="#3b3e43" d="M717.091 101.818l269.857 269.857v550.507l-269.857-269.857z"/></g></svg>`
  },
  {
    id: "kmind-icon://builtin/business/bar-chart",
    group: "business",
    name: "bar-chart",
    label: "Metrics",
    catalog: { "groupId": "business", "groupLabel": "Business", "order": 150, "surfaces": ["node-content"] },
    viewBox: "0 0 32 32",
    svg: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" width="100%" height="100%" aria-hidden="true" focusable="false"><g fill="none"><path fill="#E1D8EC" d="M2 6a4 4 0 0 1 4-4h20a4 4 0 0 1 4 4v20c0 1.48-.804 2.773-2 3.465L26.554 29a4 4 0 0 0-3.014.23L22 30h-3l-3-1.5l-3 1.5h-3l-1.54-.77A4 4 0 0 0 5.446 29L4 29.465A4 4 0 0 1 2 26z"/><path fill="#B4ACBC" d="M10 11v10H2v1h8v8h1v-8h10v8h1v-8h8v-1h-8V11h8v-1h-8V2h-1v8H11V2h-1v8H2v1zm1 0h10v10H11z"/><path fill="#00D26A" d="M6 30h4V10.214C10 9.542 9.453 9 8.774 9H5.226C4.547 9 4 9.542 4 10.213v19.252c.588.34 1.271.535 2 .535"/><path fill="#F70A8D" d="M17.774 17h-3.548c-.679 0-1.226.542-1.226 1.214V30h6V18.214c0-.672-.547-1.214-1.226-1.214"/><path fill="#00A6ED" d="M22 30h4c.729 0 1.412-.195 2-.535V7.209C28 6.539 27.453 6 26.774 6h-3.548C22.547 6 22 6.54 22 7.209z"/></g></svg>`
  },
  {
    id: "kmind-icon://builtin/business/briefcase",
    group: "business",
    name: "briefcase",
    label: "Work",
    catalog: { "groupId": "business", "groupLabel": "Business", "order": 150, "surfaces": ["node-content"] },
    viewBox: "0 0 32 32",
    svg: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" width="100%" height="100%" aria-hidden="true" focusable="false"><g fill="none"><path fill="#8C5543" d="M2 15h28v13a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2z"/><path fill="#6D4534" d="M11.1 9H4a2 2 0 0 0-2 2v4a4 4 0 0 0 4 4h20a4 4 0 0 0 4-4v-4a2 2 0 0 0-2-2h-7.1a5.002 5.002 0 0 0-9.8 0m2.07 0a3.001 3.001 0 0 1 5.66 0z"/><path fill="#D3883E" d="m13 19l3-1l3 1v2a1 1 0 0 1-1 1h-4a1 1 0 0 1-1-1z"/><path fill="#E19747" d="M13 18a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v1h-6z"/></g></svg>`
  },
  {
    id: "kmind-icon://builtin/business/chart-increasing",
    group: "business",
    name: "chart-increasing",
    label: "Growth",
    catalog: { "groupId": "business", "groupLabel": "Business", "order": 150, "surfaces": ["node-content"] },
    viewBox: "0 0 32 32",
    svg: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" width="100%" height="100%" aria-hidden="true" focusable="false"><g fill="none"><path fill="#E1D8EC" d="M2 6a4 4 0 0 1 4-4h20a4 4 0 0 1 3.731 2.556l-.585 1.776l.854.846V26a4 4 0 0 1-4 4H6a4 4 0 0 1-3.888-3.056l.67-1.893l-.782-.71z"/><path fill="#B4ACBC" d="M10 11v10H2v1h8v8h1v-8h10v8h1v-8h8v-1h-8V11h8v-1h-8V2h-1v8H11V2h-1v8H2v1zm1 0h10v10H11z"/><path fill="#319FE7" d="M2.12 26.976A4 4 0 0 1 2 26v-1.701l7.062-6.973a2.2 2.2 0 0 1 3.06-.03l2.15 2.04a.5.5 0 0 0 .698-.009L29.722 4.531c.18.455.278.95.278 1.469v1.187L16.132 20.902a2.2 2.2 0 0 1-3.052.04l-2.15-2.017a.5.5 0 0 0-.694.01z"/></g></svg>`
  },
  {
    id: "kmind-icon://builtin/business/dollar-banknote",
    group: "business",
    name: "dollar-banknote",
    label: "Budget",
    catalog: { "groupId": "business", "groupLabel": "Business", "order": 150, "surfaces": ["node-content"] },
    viewBox: "0 0 32 32",
    svg: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" width="100%" height="100%" aria-hidden="true" focusable="false"><g fill="none"><path fill="#00F397" d="M2 10a2 2 0 0 1 2-2h11l2 1l2-1h9a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2z"/><path fill="#008463" d="M3 11a2 2 0 0 1 2-2h22a2 2 0 0 1 2 2v12a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2zm2-1a1 1 0 0 0-1 1v12a1 1 0 0 0 1 1h22a1 1 0 0 0 1-1V11a1 1 0 0 0-1-1zM2 28a2 2 0 0 0 2 2h11l2-1l2 1h9a2 2 0 0 0 2-2v-4a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2zm24-11a4.5 4.5 0 1 1-9 0a4.5 4.5 0 0 1 9 0"/><path fill="#FFF478" d="M19 8h-4v19h4z"/><path fill="#F3AD61" d="M19 26h-4v4h4z"/><path fill="#fff" d="M9.5 12a.5.5 0 0 1 .5.5v.545c.834.152 1.517.678 1.824 1.375c.13.294-.122.58-.443.58c-.244 0-.448-.173-.587-.373C10.55 14.273 10.1 14 9.5 14c-.93 0-1.5.656-1.5 1.25s.57 1.25 1.5 1.25c1.38 0 2.5 1.007 2.5 2.25c0 1.088-.859 1.997-2 2.205v.545a.5.5 0 0 1-1 0v-.545c-.834-.152-1.517-.678-1.824-1.375c-.13-.294.122-.58.443-.58c.244 0 .448.173.587.373c.243.354.694.627 1.294.627c.93 0 1.5-.656 1.5-1.25s-.57-1.25-1.5-1.25c-1.38 0-2.5-1.007-2.5-2.25c0-1.088.859-1.996 2-2.205V12.5a.5.5 0 0 1 .5-.5"/></g></svg>`
  },
  {
    id: "kmind-icon://builtin/business/globe-with-meridians",
    group: "business",
    name: "globe-with-meridians",
    label: "Global",
    catalog: { "groupId": "business", "groupLabel": "Business", "order": 150, "surfaces": ["node-content"] },
    viewBox: "0 0 32 32",
    svg: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" width="100%" height="100%" aria-hidden="true" focusable="false"><path fill="#83CBFF" d="M2 16C2 8.28 8.28 2 16 2s14 6.28 14 14s-6.28 14-14 14S2 23.72 2 16m2.041-1h3.99a16 16 0 0 1 1.129-5H5.609a11.9 11.9 0 0 0-1.568 5m5.994 0H15v-5h-3.654a14 14 0 0 0-1.31 5M15 17h-4.965a14 14 0 0 0 1.31 5H15zm0 7h-2.494A14 14 0 0 0 15 26.73zm4.005 3.62A12 12 0 0 0 24.94 24h-3.074a16 16 0 0 1-2.86 3.62M22.84 22h3.55v.002A11.9 11.9 0 0 0 27.959 17h-3.99a16 16 0 0 1-1.13 5m-.875-5H17v5h3.654a14 14 0 0 0 1.31-5m2.004-2h3.99a11.9 11.9 0 0 0-1.569-5.002V10h-3.55a16 16 0 0 1 1.13 5m-3.315-5H17v5h4.965a14 14 0 0 0-1.31-5m1.212-2h3.073a12 12 0 0 0-5.926-3.618A16 16 0 0 1 21.865 8M17 5.27V8h2.494A14 14 0 0 0 17 5.27m-2 0A14 14 0 0 0 12.506 8H15zM17 24v2.73A14 14 0 0 0 19.494 24zM5.609 22h3.554a16 16 0 0 1-1.132-5H4.04c.15 1.81.703 3.506 1.568 5M13 27.621A16 16 0 0 1 10.14 24H7.06a12 12 0 0 0 5.941 3.621M10.134 8a16 16 0 0 1 2.853-3.617A12 12 0 0 0 7.061 8z"/></svg>`
  },
  {
    id: "kmind-icon://builtin/business/laptop",
    group: "business",
    name: "laptop",
    label: "Computer",
    catalog: { "groupId": "business", "groupLabel": "Business", "order": 150, "surfaces": ["node-content"] },
    viewBox: "0 0 32 32",
    svg: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" width="100%" height="100%" aria-hidden="true" focusable="false"><g fill="none"><path fill="#D3D3D3" d="m28 20l-12-1l-12 1l-1.98 8.891c-.11.766.975.609 1.48.609h25c.505 0 1.59.157 1.48-.609z"/><path fill="#7167A4" d="M27 2H5c-.55 0-1 .45-1 1v16.99h24V3c0-.55-.45-1-1-1"/><path fill="#26C9FC" d="M5 18.74V3.25c0-.14.11-.25.25-.25h21.5c.14 0 .25.11.25.25v15.49c0 .14-.11.25-.25.25H5.25c-.14 0-.25-.11-.25-.25"/><path fill="#9B9B9B" fill-rule="evenodd" d="m27.27 21.28l.72 3.25a.38.38 0 0 1-.37.46H4.38c-.24 0-.42-.23-.37-.46l.72-3.25c.04-.17.19-.29.37-.29h21.8c.18 0 .33.12.37.29M8.186 24.5H6.753l.125-.75H8.28zm1.938 0H8.69l.094-.75h1.404zm1.838 0h-1.336l.062-.75h1.306zm1.85 0h-1.35l.032-.75h1.35zm1.938 0h-1.437l.031-.75h1.406zm1.937 0H16.25v-.75h1.406zm1.85 0h-1.35l-.03-.75h1.349zm1.837 0h-1.336l-.032-.75h1.306zm1.937 0h-1.435l-.063-.75h1.404zm1.936 0h-1.433l-.093-.75h1.4zm1.753 0h-1.247l-.125-.75h1.247zm-.333-2l.125.75h-1.247l-.125-.75zm-.167-1l.083.5h-1.246l-.084-.5zm-3.06 0h1.307l.083.5h-1.328zm-1.814 0h1.31l.062.5h-1.33zm-1.713 0h1.211l.042.5h-1.233zm-1.85 0h1.35l.02.5h-1.35zm-1.813 0h1.312l.021.5H16.25zm-1.812 0h1.312v.5h-1.333zm-1.85 0h1.35l-.022.5h-1.35zm-1.712 0h1.211l-.02.5h-1.233zm-1.812 0h1.31l-.042.5h-1.33zm-1.81 0H8.56l-.063.5H7.17zm-1.754 0h1.247l-.084.5H5.417zm-.292 1.75l.125-.75H6.58l-.125.75zM5 24.5l.125-.75h1.247l-.125.75zm20.038-1.25l-.125-.75h-1.349l.094.75zm-1.884 0l-.093-.75h-1.352l.063.75zm-1.884 0l-.062-.75h-1.254l.032.75zm-1.785 0l-.031-.75h-1.35l.032.75zm-1.85 0l-.031-.75H16.25v.75zM7.087 22.5l-.125.75h1.38l.094-.75zm1.852 0l-.093.75h1.382l.063-.75zm1.854 0l-.063.75h1.284l.032-.75zm1.753 0l-.031.75h1.35l.03-.75zm1.85 0l-.031.75h1.385v-.75z" clip-rule="evenodd"/><path fill="#9B9B9B" d="M29.09 29a.9.9 0 0 0 .8-.49l.09.38l.003.023A.913.913 0 0 1 29.09 30H2.91c-.5 0-.91-.41-.91-.91c0-.07.01-.13.03-.19l.08-.38c.15.28.45.48.8.48zm-18.27-1.01h10.36c.16 0 .28-.15.24-.31l-.38-1.5a.255.255 0 0 0-.24-.19h-9.6c-.11 0-.21.08-.24.19l-.38 1.5c-.04.16.08.31.24.31"/></g></svg>`
  },
  {
    id: "kmind-icon://builtin/collaboration/bell",
    group: "collaboration",
    name: "bell",
    label: "Reminder",
    catalog: { "groupId": "collaboration", "groupLabel": "People & Comms", "order": 140, "surfaces": ["node-content"] },
    viewBox: "0 0 32 32",
    svg: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" width="100%" height="100%" aria-hidden="true" focusable="false"><g fill="none"><path fill="#FF822D" d="M12.5 27.5c.448 1.442 1.838 2.5 3.5 2.5c1.663 0 3.052-1.058 3.5-2.5z"/><path fill="#FFB02E" d="M16 6.55c-.69 0-1.25-.56-1.25-1.25V3.25a1.25 1.25 0 0 1 2.5 0V5.3c0 .69-.56 1.25-1.25 1.25"/><path fill="#F9C23C" d="M27.6 22.843c-.96-.773-1.54-1.927-1.78-3.15l-1.73-8.9C23.32 6.85 19.94 4.01 16 4c-3.94.01-7.32 2.85-8.09 6.793l-1.73 8.9c-.24 1.223-.82 2.377-1.78 3.15a3.78 3.78 0 0 0-1.4 2.95v1.234c0 .542.43.973.95.973h24.1c.53 0 .95-.431.95-.973v-1.234c0-1.204-.55-2.258-1.4-2.95"/></g></svg>`
  },
  {
    id: "kmind-icon://builtin/collaboration/busts-in-silhouette",
    group: "collaboration",
    name: "busts-in-silhouette",
    label: "Team",
    catalog: { "groupId": "collaboration", "groupLabel": "People & Comms", "order": 140, "surfaces": ["node-content"] },
    viewBox: "0 0 32 32",
    svg: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" width="100%" height="100%" aria-hidden="true" focusable="false"><g fill="none"><path fill="#321B41" d="M15.84 23.93q.09.068.174.141q.084-.073.176-.141a11.07 11.07 0 0 1 12.65 0A2.91 2.91 0 0 1 30 26.29V30H2v-3.68a2.93 2.93 0 0 1 1.19-2.39a11.07 11.07 0 0 1 12.65 0"/><path fill="#533566" d="M10.67 7.93h-2.3a4.24 4.24 0 0 0-4.23 4.83l.067 1.022a1.71 1.71 0 0 0 .224 3.397l.099 1.501a4.05 4.05 0 0 0 3.15 3.427v.933a1.81 1.81 0 1 0 3.62 0v-.923a4.05 4.05 0 0 0 3.2-3.437l.094-1.503a1.71 1.71 0 0 0 1.396-.867a1.71 1.71 0 0 0 1.441.87l.099 1.5a4.05 4.05 0 0 0 3.15 3.427v.933a1.81 1.81 0 1 0 3.62 0v-.923a4.05 4.05 0 0 0 3.2-3.437l.094-1.503a1.71 1.71 0 0 0 .212-3.39l.064-1.027a4.26 4.26 0 0 0-4.2-4.83h-2.3a4.24 4.24 0 0 0-4.23 4.83l.067 1.022a1.71 1.71 0 0 0-1.217.848a1.71 1.71 0 0 0-1.184-.843l.064-1.027a4.26 4.26 0 0 0-4.2-4.83"/></g></svg>`
  },
  {
    id: "kmind-icon://builtin/collaboration/e-mail",
    group: "collaboration",
    name: "e-mail",
    label: "Email",
    catalog: { "groupId": "collaboration", "groupLabel": "People & Comms", "order": 140, "surfaces": ["node-content"] },
    viewBox: "0 0 32 32",
    svg: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" width="100%" height="100%" aria-hidden="true" focusable="false"><g fill="none"><rect width="30" height="22" x="1" y="5" fill="#B4ACBC" rx="1.5"/><rect width="28" height="18" x="2" y="7" fill="#CDC4D6" rx="1"/><path fill="#E1D8EC" d="m30 23.4l-12.971-7.782a2 2 0 0 0-2.058 0L2 23.4V25a1 1 0 0 0 1 1h26a1 1 0 0 0 1-1z"/><path fill="#998EA4" d="M2 9.766V8h28v1.766L17.544 17.24a3 3 0 0 1-3.088 0z"/><path fill="#F3EEF8" d="M2 8.6V7a1 1 0 0 1 1-1h26a1 1 0 0 1 1 1v1.6l-12.971 7.783a2 2 0 0 1-2.058 0z"/><path fill="#00A6ED" d="M16 23a7 7 0 1 0 0-14a7 7 0 0 0 0 14"/><path fill="#F4F4F4" d="M16 11.5c-1.21-.02-2.36.44-3.22 1.3c-.87.85-1.34 1.99-1.34 3.2c0 2.48 2.02 4.5 4.5 4.5a.47.47 0 1 0 0-.94c-1.96 0-3.56-1.6-3.56-3.56c0-.96.38-1.86 1.06-2.53s1.59-1.03 2.55-1.03c1.93.03 3.51 1.65 3.51 3.62v.81a.67.67 0 0 1-1.34 0v-3.08a.47.47 0 0 0-.47-.47c-.26 0-.49.21-.49.47v.09c-.44-.35-.99-.57-1.6-.57c-1.4 0-2.54 1.14-2.54 2.54s1.14 2.54 2.54 2.54c.7 0 1.34-.29 1.8-.75c.28.5.81.84 1.42.84c.89 0 1.62-.73 1.62-1.62v-.81c0-2.47-1.99-4.52-4.44-4.55m-.39 5.96c-.88 0-1.6-.72-1.6-1.6s.72-1.6 1.6-1.6s1.6.72 1.6 1.6s-.72 1.6-1.6 1.6"/></g></svg>`
  },
  {
    id: "kmind-icon://builtin/collaboration/handshake",
    group: "collaboration",
    name: "handshake",
    label: "Agreement",
    catalog: { "groupId": "collaboration", "groupLabel": "People & Comms", "order": 140, "surfaces": ["node-content"] },
    viewBox: "0 0 32 32",
    svg: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" width="100%" height="100%" aria-hidden="true" focusable="false"><g fill="none"><path fill="#FFC83D" d="M11.406 6.156c-5.275-.65-7.156 2-8.062 3.219c-2.469 3.64-.985 7.64.812 9.563c0 0 10.094 9.828 10.375 10.093s.946 1.172 2.547.914c1.398-.225 1.797-1.914 1.797-1.914s1.032.842 2.516 0c1.156-.656 1.109-1.968 1.109-1.968s1.238.62 2.563-.5c1.192-1.01.453-2.782.453-2.782s1.07.176 1.828-.656c1.025-1.125.672-2.547 0-3.187L19.625 10.5l-.594-3.125z"/><path fill="#D67D00" d="m26.707 22.593l-2.226-2.257a.5.5 0 1 0-.712.703l1.764 1.788l-.017-.046s.582.096 1.191-.188m-2.729 3.557l-2.31-2.563a.5.5 0 0 0-.743.67l1.66 1.841c.199.076.73.232 1.393.053m-3.402 2.2l-1.806-1.913a.5.5 0 1 0-.727.687l.904.957c.199.13.795.45 1.629.269m-2.173.703c-.759.202-2.167.265-3.137-.773l-.776.71l.041.04q.044.042.1.1c.328.34 1.01 1.046 2.447.814c.622-.1 1.046-.49 1.325-.892"/><path fill="#F59F00" d="M6.375 6.813c-1.687 2.166-4.287 7.775.313 11.625L5.24 19.993l-1.084-1.055C2.36 17.016.875 13.016 3.344 9.375l.04-.055c.525-.706 1.366-1.839 2.95-2.567z"/><path fill="#D67D00" d="M17.25 23.688c1.203 1.39-.3 3.162-1 3.906L5.669 16.584c1.974-2.002 3.278-2.203 4.16-1.334c.88.869.468 1.484.468 1.484s1.194-.678 2.453.563c1.26 1.241.39 2.187.39 2.187s1.3-.234 2.22.797c1.03 1.157.374 2.5.374 2.5s.79.068 1.516.907"/><path fill="#FFC83D" d="M12.438 8c3.234-1.297 8.14-1.953 10.39-1.984c1.531 0 3.481.37 5.547 2.797c3.3 3.874.828 8.296-1.125 10.093V17.5s-7.506-6.536-7.75-6.766c-.45-.425-2.302-.296-2.5-.234c-.604.188-1.65.5-3 1c-1.098.407-1.969.078-2.328-.766c-.36-.843-.842-2.09.765-2.734"/><path fill="#D67D00" d="M28.31 17.71a8.4 8.4 0 0 1-1.06 1.196c-2.76-2.406-8.378-7.325-8.828-7.75s-.974-.406-1.172-.344A79 79 79 0 0 0 13.75 12c-1.098.407-2.203-.422-2.562-1.266c-.33-.771-.356-1.879.87-2.556l.632-.277l.05-.019c-1.953 1.468-.228 3.262 1.385 3.056c.567-.073 1.5-.266 2.406-.5c.36-.094.713-.259 1.046-.414c.625-.293 1.18-.552 1.58-.243c1.5 1.165 5.976 4.968 9.154 7.929"/><path fill="#FFC83D" d="M8.82 16.879a2.203 2.203 0 0 0-3.09-.398L3.812 18.1c-.883.735-1.112 2.11-.467 3.002c.584.808 1.48 1.142 2.303.908c-.365.835-.334 1.903.367 2.49c.655.547 1.464.922 2.275.669c-.078.535.08 1.121.63 1.705c.52.551 1.276.826 2.087.643c-.107.572.074 1.208.743 1.853c.819.79 2.08.858 3.265-.23l.772-.9c.62-.78 1.478-2.136.196-3.288c-.443-.398-.952-.619-1.481-.62c.287-.7.282-1.558-.55-2.38c-.52-.513-1.157-.736-1.86-.568c.38-.808.371-1.633-.39-2.385c-.691-.683-1.543-1.007-2.643-.39c.194-.596.148-1.228-.24-1.731"/><path fill="#D67D00" d="M9.034 17.242L4.31 21.907c.418.186.873.229 1.31.112l3.469-3.426l-.029.016c.15-.459.156-.94-.026-1.367m3.212 2.584L6.96 25.085c.425.171.878.226 1.332.085l3.807-3.786l-.005.001c.245-.52.328-1.048.153-1.559m2.326 3.071l-4.918 4.498c.404.177.865.231 1.345.125l3.513-3.213c.17-.427.23-.912.06-1.41"/></g></svg>`
  },
  {
    id: "kmind-icon://builtin/collaboration/megaphone",
    group: "collaboration",
    name: "megaphone",
    label: "Announcement",
    catalog: { "groupId": "collaboration", "groupLabel": "People & Comms", "order": 140, "surfaces": ["node-content"] },
    viewBox: "0 0 32 32",
    svg: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" width="100%" height="100%" aria-hidden="true" focusable="false"><g fill="none"><path fill="#FFB02E" d="m25.064 23.405l-1.148-2.807l-1.715.702l1.15 2.81l.002.003a.755.755 0 0 1-.41.997l-4.906 2.012l-.003.001a.755.755 0 0 1-.996-.41l-1.152-2.815l-1.715.702l1.15 2.807a2.607 2.607 0 0 0 3.42 1.428h.002l4.894-2.008a2.607 2.607 0 0 0 1.428-3.42zM8 23.5l1.708 3.279c.62.65.59 1.68-.07 2.29c-.65.61-1.68.58-2.29-.07l-4.91-5.21c-.61-.65-.58-1.68.07-2.29s1.68-.58 2.29.07z"/><path fill="#F9C23C" d="m29.228 15.079l-11.55-12.25c-1.27-1.35-3.5-1-4.29.68l-8.59 18.06l4.97 5.27l18.54-7.51c1.71-.69 2.19-2.9.92-4.25"/></g></svg>`
  },
  {
    id: "kmind-icon://builtin/collaboration/speaking-head",
    group: "collaboration",
    name: "speaking-head",
    label: "Discussion",
    catalog: { "groupId": "collaboration", "groupLabel": "People & Comms", "order": 140, "surfaces": ["node-content"] },
    viewBox: "0 0 32 32",
    svg: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" width="100%" height="100%" aria-hidden="true" focusable="false"><path fill="#533566" d="M24.726 14.62c.445.467.66.692.724 1.23a1.79 1.79 0 0 1-1.83 1.98l.043.44c.05.491.097.967.097 1.43a.58.58 0 0 1-.55.59l-1.68.06a.38.38 0 0 0 0 .65l1.67 1.07a.77.77 0 0 1 .34.83c-.55 2.04-2.01 3.44-5.3 3.85q-.952.11-1.91.08a1.19 1.19 0 0 0-1.16.8l-.72 2h-10l2.18-6.89a2.76 2.76 0 0 0-.18-2.09C5.26 18.37 3.36 14.43 3.06 12a7.46 7.46 0 0 1 6.46-8.34l4.81-.6a7.47 7.47 0 0 1 8.31 6.47l.38 3a16 16 0 0 0 1.706 2.09m5.744 7.48v-1.94a.4.4 0 0 0-.51-.44l-3.24 1a.4.4 0 0 0 0 .76l3.24 1a.4.4 0 0 0 .51-.38M27.72 16l1.37 1.37A.4.4 0 0 1 29 18l-3 1.6a.4.4 0 0 1-.54-.53l1.6-3a.4.4 0 0 1 .66-.07m1.37 8.91l-1.37 1.37a.4.4 0 0 1-.66-.07l-1.6-3a.4.4 0 0 1 .54-.53l3 1.6a.4.4 0 0 1 .09.63"/></svg>`
  },
  {
    id: "kmind-icon://builtin/faces/angry-face",
    group: "faces",
    name: "angry-face",
    label: "Angry",
    catalog: { "groupId": "faces", "groupLabel": "Faces", "order": 170, "surfaces": ["node-content"] },
    viewBox: "0 0 32 32",
    svg: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" width="100%" height="100%" aria-hidden="true" focusable="false"><g fill="none"><path fill="#FFB02E" d="M15.999 29.998c9.334 0 13.999-6.268 13.999-14c0-7.73-4.665-13.998-14-13.998C6.665 2 2 8.268 2 15.999s4.664 13.999 13.999 13.999"/><path fill="#fff" d="M10.5 21a4.5 4.5 0 1 0 0-9a4.5 4.5 0 0 0 0 9m11 0a4.5 4.5 0 1 0 0-9a4.5 4.5 0 0 0 0 9"/><path fill="#402A32" d="M14.29 12.501a.75.75 0 0 1-.08 1.498c-1.017-.054-1.989-.304-2.817-.88c-.835-.582-1.46-1.452-1.854-2.631a.75.75 0 1 1 1.422-.476c.31.928.762 1.509 1.29 1.876c.534.372 1.21.569 2.039.613m3.42 0a.75.75 0 0 0 .08 1.498c1.017-.054 1.989-.304 2.817-.88c.835-.582 1.46-1.452 1.854-2.631a.75.75 0 1 0-1.422-.476c-.31.928-.763 1.509-1.29 1.876c-.534.372-1.21.569-2.039.613M16 24c-2.005 0-2.934 1.104-3.106 1.447a1 1 0 1 1-1.789-.894C11.602 23.563 13.205 22 16 22s4.4 1.562 4.894 2.553a1 1 0 1 1-1.788.894C18.934 25.104 18.005 24 16 24m-2-7a2 2 0 1 1-4 0a2 2 0 0 1 4 0m8 0a2 2 0 1 1-4 0a2 2 0 0 1 4 0"/></g></svg>`
  },
  {
    id: "kmind-icon://builtin/faces/beaming-face-with-smiling-eyes",
    group: "faces",
    name: "beaming-face-with-smiling-eyes",
    label: "Beaming",
    catalog: { "groupId": "faces", "groupLabel": "Faces", "order": 170, "surfaces": ["node-content"] },
    viewBox: "0 0 32 32",
    svg: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" width="100%" height="100%" aria-hidden="true" focusable="false"><g fill="none"><path fill="#FFB02E" d="M15.999 29.998c9.334 0 13.999-6.268 13.999-14c0-7.73-4.665-13.998-14-13.998C6.665 2 2 8.268 2 15.999s4.664 13.999 13.999 13.999"/><path fill="#402A32" d="M8.982 11.19c.048-.246.158-.55.367-.777c.18-.196.498-.413 1.15-.413c.643 0 .97.222 1.158.429c.218.24.323.545.358.742a1 1 0 0 0 1.97-.342a3.54 3.54 0 0 0-.85-1.747C12.563 8.452 11.696 8 10.5 8c-1.184 0-2.047.431-2.624 1.06c-.548.596-.769 1.293-.858 1.75a1 1 0 1 0 1.964.38m11 0c.048-.246.158-.55.367-.777c.18-.196.498-.413 1.151-.413c.642 0 .969.222 1.157.429c.219.24.324.545.358.742a1 1 0 0 0 1.97-.342a3.54 3.54 0 0 0-.85-1.747C23.563 8.452 22.696 8 21.5 8c-1.184 0-2.047.431-2.624 1.06c-.548.596-.769 1.293-.857 1.75a1 1 0 1 0 1.963.38"/><path fill="#BB1D80" d="M6 16h20s0 3.774-2.318 6.685H8.318C6 19.774 6 16 6 16"/><path fill="#fff" d="M7.759 19.794L7 16h18l-.759 3.794A1.5 1.5 0 0 1 22.771 21H9.23a1.5 1.5 0 0 1-1.471-1.206m.526 2.849C9.738 24.49 12.114 26 16 26s6.262-1.51 7.715-3.357A1 1 0 0 0 22.78 22H9.22a1 1 0 0 0-.935.643"/></g></svg>`
  },
  {
    id: "kmind-icon://builtin/faces/exploding-head",
    group: "faces",
    name: "exploding-head",
    label: "Mind Blown",
    catalog: { "groupId": "faces", "groupLabel": "Faces", "order": 170, "surfaces": ["node-content"] },
    viewBox: "0 0 32 32",
    svg: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" width="100%" height="100%" aria-hidden="true" focusable="false"><g fill="none"><path fill="#FFB02E" d="M16 30c9.33 0 14-6.26 14-13.979C30 11.947 25.34 10 16 10c-9.33 0-14 1.088-14 6.021C2 23.749 6.66 30 16 30"/><path fill="#fff" d="M14.93 20.46a4.48 4.48 0 1 1-8.96 0a4.48 4.48 0 0 1 8.96 0m11 0a4.48 4.48 0 1 1-8.96 0a4.48 4.48 0 0 1 8.96 0"/><path fill="#402A32" d="M13.97 20.94a2 2 0 1 1-4 0a2 2 0 0 1 4 0m8 0a2 2 0 1 1-4 0a2 2 0 0 1 4 0"/><path fill="#BB1D80" d="M15.97 28.91c-1.36 0-2.47-1.11-2.47-2.47s1.11-2.47 2.47-2.47s2.47 1.11 2.47 2.47s-1.11 2.47-2.47 2.47"/><path fill="#FF6723" d="M25.98 12.97c0 .987-3.073 1.8-8.02 1.968l-1.917-.829l-2.074.825c-4.89-.179-7.949-.993-7.949-1.964c0-1.1 3.92-2 10-2s9.96.9 9.96 2"/><path fill="#fff" d="M13.97 14.94c0-.718-.08-1.415-.23-2.072L16 9l2.193 3.874a9.5 9.5 0 0 0-.223 2.066z"/><path fill="#D3D3D3" d="M20.143 8.8A5 5 0 0 1 16 11a5 5 0 0 1-4.143-2.2A4 4 0 0 1 5 6c0-2.21 1.79-3.478 4-3.478c.68 0 1.32.17 1.882.47c.557.297 1.306.233 1.777-.19A4.98 4.98 0 0 1 16 1.522a4.98 4.98 0 0 1 3.341 1.28c.47.423 1.22.487 1.777.19A4 4 0 0 1 23 2.522c2.21 0 4 1.269 4 3.478a4 4 0 0 1-6.857 2.8"/><path fill="#E6E6E6" d="M27 6c0 .074-.106.079-.124.008a4.002 4.002 0 0 0-5.758-2.539c-.557.298-1.306.234-1.777-.189A4.98 4.98 0 0 0 16 2a4.98 4.98 0 0 0-3.341 1.28c-.47.423-1.22.487-1.777.19a4.002 4.002 0 0 0-5.758 2.538C5.106 6.078 5 6.074 5 6a4 4 0 0 1 5.882-3.53c.557.297 1.306.233 1.777-.19A4.98 4.98 0 0 1 16 1a4.98 4.98 0 0 1 3.341 1.28c.47.423 1.22.487 1.777.19A4 4 0 0 1 27 6"/><path fill="#C9C9C9" d="M16.859 12.38a1.65 1.65 0 0 0-1.718 0A4 4 0 0 1 9 9c0-2.21 1.79-3.458 4-3.458a4 4 0 0 1 2.141.621c.508.323 1.21.323 1.718 0A4 4 0 0 1 19 5.543c2.21 0 4 1.248 4 3.457a4 4 0 0 1-6.141 3.38"/><path fill="#fff" d="M23 9c0 .074-.106.079-.124.008a4.002 4.002 0 0 0-6.017-2.387a1.65 1.65 0 0 1-1.718 0a4.002 4.002 0 0 0-6.017 2.387C9.106 9.078 9 9.074 9 9a4 4 0 0 1 6.141-3.38c.508.323 1.21.323 1.718 0A4 4 0 0 1 23 9"/><path fill="#FFB02E" d="M7 4.5a1.5 1.5 0 1 1-3 0a1.5 1.5 0 0 1 3 0m17.38 2.26a1.38 1.38 0 1 0 0-2.76a1.38 1.38 0 0 0 0 2.76M5 9a1 1 0 1 1-2 0a1 1 0 0 1 2 0m23 1a1 1 0 1 1-2 0a1 1 0 0 1 2 0"/></g></svg>`
  },
  {
    id: "kmind-icon://builtin/faces/expressionless-face",
    group: "faces",
    name: "expressionless-face",
    label: "Blank",
    catalog: { "groupId": "faces", "groupLabel": "Faces", "order": 170, "surfaces": ["node-content"] },
    viewBox: "0 0 32 32",
    svg: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" width="100%" height="100%" aria-hidden="true" focusable="false"><g fill="none"><path fill="#FFB02E" d="M15.999 29.998c9.334 0 13.999-6.268 13.999-14c0-7.73-4.665-13.998-14-13.998C6.665 2 2 8.268 2 15.999s4.664 13.999 13.999 13.999"/><path fill="#402A32" d="M8 13a1 1 0 0 1 1-1h4a1 1 0 1 1 0 2H9a1 1 0 0 1-1-1m10 0a1 1 0 0 1 1-1h4a1 1 0 1 1 0 2h-4a1 1 0 0 1-1-1m-7 6a1 1 0 1 0 0 2h10a1 1 0 1 0 0-2z"/></g></svg>`
  },
  {
    id: "kmind-icon://builtin/faces/face-with-hand-over-mouth",
    group: "faces",
    name: "face-with-hand-over-mouth",
    label: "Surprised",
    catalog: { "groupId": "faces", "groupLabel": "Faces", "order": 170, "surfaces": ["node-content"] },
    viewBox: "0 0 32 32",
    svg: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" width="100%" height="100%" aria-hidden="true" focusable="false"><g fill="none"><path fill="#FFB02E" d="M15.999 29.998c9.334 0 13.999-6.268 13.999-14c0-7.73-4.665-13.998-14-13.998C6.665 2 2 8.268 2 15.999s4.664 13.999 13.999 13.999"/><path fill="#FF6723" d="M10 15c0 1.105-1.343 2-3 2s-3-.895-3-2s1.343-2 3-2s3 .895 3 2m18 0c0 1.105-1.343 2-3 2s-3-.895-3-2s1.343-2 3-2s3 .895 3 2"/><path fill="#402A32" d="M8.982 11.19c.048-.246.158-.55.367-.777c.18-.196.498-.413 1.15-.413c.643 0 .97.222 1.158.429c.218.24.323.545.358.742a1 1 0 0 0 1.97-.342a3.54 3.54 0 0 0-.85-1.747C12.563 8.452 11.696 8 10.5 8c-1.184 0-2.047.431-2.624 1.06c-.548.596-.769 1.293-.858 1.75a1 1 0 1 0 1.964.38m11 0c.048-.246.158-.55.367-.777c.18-.196.498-.413 1.151-.413c.642 0 .969.222 1.157.429c.219.24.324.545.358.742a1 1 0 0 0 1.97-.342a3.54 3.54 0 0 0-.85-1.747C23.563 8.452 22.696 8 21.5 8c-1.184 0-2.047.431-2.624 1.06c-.548.596-.769 1.293-.857 1.75a1 1 0 1 0 1.963.38"/><path fill="#FF822D" d="M16.043 17.689a1.25 1.25 0 0 0-1.927-1.573L11 19.232v-.982c0-.69-.56-1.25-1.25-1.25s-1.25.56-1.285 1.249C8.379 19.885 8.119 22.07 7.5 23c-1 1.5-1 4.5 1 6c3.816 2.862 8.334-2.018 8.741-2.473l2.643-2.643a1.25 1.25 0 0 0-.915-2.134l.354-.31a1.25 1.25 0 0 0-1.512-1.983l1.073-1.073a1.25 1.25 0 0 0-1.768-1.768z"/></g></svg>`
  },
  {
    id: "kmind-icon://builtin/faces/face-with-monocle",
    group: "faces",
    name: "face-with-monocle",
    label: "Inspect",
    catalog: { "groupId": "faces", "groupLabel": "Faces", "order": 170, "surfaces": ["node-content"] },
    viewBox: "0 0 32 32",
    svg: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" width="100%" height="100%" aria-hidden="true" focusable="false"><g fill="none"><path fill="#FFB02E" d="M15.999 29.998c9.334 0 13.999-6.268 13.999-14c0-7.73-4.665-13.998-14-13.998C6.665 2 2 8.268 2 15.999s4.664 13.999 13.999 13.999"/><path fill="#fff" d="M22 17.5a5.5 5.5 0 1 0 0-11a5.5 5.5 0 0 0 0 11M10.5 17a4.5 4.5 0 1 0 0-9a4.5 4.5 0 0 0 0 9"/><path fill="#9B9B9B" d="M28 12a6 6 0 1 0-1 3.318V25.5a.5.5 0 0 0 1 0zm-1 0v.004a5 5 0 1 1-10 0A5 5 0 0 1 27 12"/><path fill="#402A32" d="M18.777 4.916c.22-.146.637-.38 1.141-.575C20.425 4.145 20.985 4 21.5 4s1.075.145 1.582.341c.504.196.921.429 1.14.575a.5.5 0 0 0 .555-.832a7.3 7.3 0 0 0-1.334-.675C22.875 3.189 22.185 3 21.5 3s-1.375.188-1.943.409a7.3 7.3 0 0 0-1.334.675a.5.5 0 0 0 .554.832M7.916 6.777C8.183 6.377 9.11 5.5 10.5 5.5s2.317.877 2.584 1.277a.5.5 0 0 0 .832-.554c-.4-.6-1.606-1.723-3.416-1.723S7.484 5.623 7.084 6.223a.5.5 0 1 0 .832.554M15 19.75c-.835 0-1.23.393-1.293.457a1 1 0 0 1-1.414-1.414c.27-.27 1.142-1.043 2.707-1.043c2.4 0 4.234 1.483 4.894 2.803a1 1 0 1 1-1.788.894c-.34-.68-1.505-1.697-3.106-1.697M18 11a3 3 0 1 1 5.999-.001A3 3 0 0 1 18 11m-11 .5a3 3 0 1 1 5.999-.001A3 3 0 0 1 7 11.5"/></g></svg>`
  },
  {
    id: "kmind-icon://builtin/faces/face-with-open-mouth",
    group: "faces",
    name: "face-with-open-mouth",
    label: "Open Mouth",
    catalog: { "groupId": "faces", "groupLabel": "Faces", "order": 170, "surfaces": ["node-content"] },
    viewBox: "0 0 32 32",
    svg: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" width="100%" height="100%" aria-hidden="true" focusable="false"><g fill="none"><path fill="#FFB02E" d="M15.999 29.998c9.334 0 13.999-6.268 13.999-14c0-7.73-4.665-13.998-14-13.998C6.665 2 2 8.268 2 15.999s4.664 13.999 13.999 13.999"/><path fill="#fff" d="M10.5 16a4.5 4.5 0 1 0 0-9a4.5 4.5 0 0 0 0 9m11 0a4.5 4.5 0 1 0 0-9a4.5 4.5 0 0 0 0 9"/><path fill="#402A32" d="M12 14a2 2 0 1 0 0-4a2 2 0 0 0 0 4m8 0a2 2 0 1 0 0-4a2 2 0 0 0 0 4"/><path fill="#BB1D80" d="M12 22a4 4 0 0 1 8 0v2a4 4 0 0 1-8 0z"/></g></svg>`
  },
  {
    id: "kmind-icon://builtin/faces/face-with-rolling-eyes",
    group: "faces",
    name: "face-with-rolling-eyes",
    label: "Eye Roll",
    catalog: { "groupId": "faces", "groupLabel": "Faces", "order": 170, "surfaces": ["node-content"] },
    viewBox: "0 0 32 32",
    svg: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" width="100%" height="100%" aria-hidden="true" focusable="false"><g fill="none"><path fill="#FFB02E" d="M15.999 29.998c9.334 0 13.999-6.268 13.999-14c0-7.73-4.665-13.998-14-13.998C6.665 2 2 8.268 2 15.999s4.664 13.999 13.999 13.999"/><path fill="#fff" d="M10.5 19a4.5 4.5 0 0 0 2.463-8.266l-1.953.624l-1.803-1.17A4.502 4.502 0 0 0 10.5 19m11 0a4.5 4.5 0 0 0 1.293-8.811l-1.733 1.35l-2.012-.813A4.5 4.5 0 0 0 21.5 19"/><path fill="#402A32" d="M13 11a2 2 0 1 1-3.834-.799A4.5 4.5 0 0 1 10.5 10a4.5 4.5 0 0 1 2.484.747Q13 10.871 13 11m10 0a2 2 0 1 1-3.984-.253A4.5 4.5 0 0 1 21.5 10a4.5 4.5 0 0 1 1.334.201c.107.245.166.515.166.799M12 25a1 1 0 0 1 1-1h6a1 1 0 1 1 0 2h-6a1 1 0 0 1-1-1"/></g></svg>`
  },
  {
    id: "kmind-icon://builtin/faces/face-with-spiral-eyes",
    group: "faces",
    name: "face-with-spiral-eyes",
    label: "Dizzy",
    catalog: { "groupId": "faces", "groupLabel": "Faces", "order": 170, "surfaces": ["node-content"] },
    viewBox: "0 0 32 32",
    svg: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" width="100%" height="100%" aria-hidden="true" focusable="false"><g fill="none"><path fill="#FFB02E" d="M15.999 29.998c9.334 0 13.999-6.268 13.999-14c0-7.73-4.665-13.998-14-13.998C6.665 2 2 8.268 2 15.999s4.664 13.999 13.999 13.999"/><path fill="#402A32" d="M10.487 10.057c-2.193-.478-4.186 1.241-4.53 3.419a1 1 0 1 1-1.975-.312c.477-3.022 3.344-5.843 6.931-5.061a5.283 5.283 0 0 1 4.044 6.278A4.42 4.42 0 0 1 9.7 17.767a3.74 3.74 0 0 1-2.866-4.448v-.004c.18-.811.62-1.506 1.286-1.946c.669-.441 1.484-.572 2.308-.397c1.003.211 1.53 1.112 1.67 1.82c.074.382.068.83-.107 1.25a1.71 1.71 0 0 1-1.102.995a1 1 0 0 1-.751-1.843l-.003-.017a.5.5 0 0 0-.098-.217a.2.2 0 0 0-.034-.034c-.35-.072-.607-.003-.781.112c-.179.118-.353.338-.434.705a1.74 1.74 0 0 0 1.334 2.07a2.42 2.42 0 0 0 2.882-1.854a3.284 3.284 0 0 0-2.515-3.902zm-.49 2.866l.003.001zm1.943 8.724a1.5 1.5 0 0 1 2.12 0L16 23.586l1.94-1.94a1.5 1.5 0 0 1 2.12 0l1.94 1.94l1.793-1.793a1 1 0 0 1 1.414 1.414l-2.146 2.147a1.5 1.5 0 0 1-2.122 0L19 23.414l-1.94 1.94a1.5 1.5 0 0 1-2.12 0L13 23.414l-1.94 1.94a1.5 1.5 0 0 1-2.12 0l-2.147-2.147a1 1 0 1 1 1.414-1.414L10 23.586zm14.072-8.171c-.343-2.178-2.336-3.897-4.53-3.419a3.283 3.283 0 0 0-2.515 3.901a2.42 2.42 0 0 0 2.882 1.855a1.74 1.74 0 0 0 1.334-2.07c-.082-.367-.255-.587-.434-.705c-.175-.115-.43-.184-.782-.112a.2.2 0 0 0-.033.034a.5.5 0 0 0-.098.217l-.003.017a1 1 0 0 1-.751 1.843a1.71 1.71 0 0 1-1.102-.995a2.17 2.17 0 0 1-.107-1.25c.14-.708.667-1.609 1.67-1.82c.824-.175 1.64-.044 2.308.397c.666.44 1.107 1.135 1.285 1.946l.001.004a3.74 3.74 0 0 1-2.866 4.448a4.42 4.42 0 0 1-5.259-3.386a5.283 5.283 0 0 1 4.045-6.278c3.586-.782 6.454 2.039 6.93 5.061a1 1 0 1 1-1.975.312m-4.04-.553"/></g></svg>`
  },
  {
    id: "kmind-icon://builtin/faces/face-with-tears-of-joy",
    group: "faces",
    name: "face-with-tears-of-joy",
    label: "Joy",
    catalog: { "groupId": "faces", "groupLabel": "Faces", "order": 170, "surfaces": ["node-content"] },
    viewBox: "0 0 32 32",
    svg: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" width="100%" height="100%" aria-hidden="true" focusable="false"><g fill="none"><path fill="#FFB02E" d="M15.999 29.998c9.334 0 13.999-6.268 13.999-14c0-7.73-4.665-13.998-14-13.998C6.665 2 2 8.268 2 15.999s4.664 13.999 13.999 13.999"/><path fill="#402A32" d="M8.982 11.19c.048-.246.158-.55.367-.777c.18-.196.498-.413 1.15-.413c.643 0 .97.222 1.158.429c.218.24.323.545.358.742a1 1 0 0 0 1.97-.342a3.54 3.54 0 0 0-.85-1.747C12.563 8.452 11.696 8 10.5 8c-1.184 0-2.047.431-2.624 1.06c-.548.596-.769 1.293-.858 1.75a1 1 0 1 0 1.964.38m11 0c.048-.246.158-.55.367-.777c.18-.196.498-.413 1.151-.413c.642 0 .969.222 1.157.429c.219.24.324.545.358.742a1 1 0 0 0 1.97-.342a3.54 3.54 0 0 0-.85-1.747C23.563 8.452 22.696 8 21.5 8c-1.184 0-2.047.431-2.624 1.06c-.548.596-.769 1.293-.857 1.75a1 1 0 1 0 1.963.38"/><path fill="#BB1D80" d="M16 25c-9 0-9-9-9-9h18s0 9-9 9"/><path fill="#fff" d="M8 16.5V16h16v.5a1 1 0 0 1-1 1H9a1 1 0 0 1-1-1"/><path fill="#3F5FFF" d="M4.63 20.37L8 17a2.121 2.121 0 1 0-3-3l-3.37 3.37a2.121 2.121 0 1 0 3 3m22.99 0L24.25 17a2.121 2.121 0 0 1 3-3l3.37 3.37a2.121 2.121 0 0 1-3 3"/></g></svg>`
  },
  {
    id: "kmind-icon://builtin/faces/grinning-face",
    group: "faces",
    name: "grinning-face",
    label: "Grinning",
    catalog: { "groupId": "faces", "groupLabel": "Faces", "order": 170, "surfaces": ["node-content"] },
    viewBox: "0 0 32 32",
    svg: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" width="100%" height="100%" aria-hidden="true" focusable="false"><g fill="none"><path fill="#FFB02E" d="M15.999 29.998c9.334 0 13.999-6.268 13.999-14c0-7.73-4.665-13.998-14-13.998C6.665 2 2 8.268 2 15.999s4.664 13.999 13.999 13.999"/><path fill="#fff" d="M15 10.5a4.5 4.5 0 0 1-1.694 3.518c-.803-.27-1.83-.518-2.806-.518c-.977 0-2.003.248-2.806.518A4.5 4.5 0 1 1 15 10.5m11 0a4.5 4.5 0 0 1-1.694 3.518c-.803-.27-1.83-.518-2.806-.518c-.977 0-2.003.248-2.806.518A4.5 4.5 0 1 1 26 10.5"/><path fill="#402A32" d="M11 13a3 3 0 1 0 0-6a3 3 0 0 0 0 6m10 0a3 3 0 1 0 0-6a3 3 0 0 0 0 6"/><path fill="#BB1D80" d="M16 25c-9 0-9-9-9-9h18s0 9-9 9"/><path fill="#fff" d="M8 16.5V16h16v.5a1 1 0 0 1-1 1H9a1 1 0 0 1-1-1"/></g></svg>`
  },
  {
    id: "kmind-icon://builtin/faces/loudly-crying-face",
    group: "faces",
    name: "loudly-crying-face",
    label: "Crying",
    catalog: { "groupId": "faces", "groupLabel": "Faces", "order": 170, "surfaces": ["node-content"] },
    viewBox: "0 0 32 32",
    svg: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" width="100%" height="100%" aria-hidden="true" focusable="false"><g fill="none"><path fill="#FFB02E" d="M15.999 29.998c9.334 0 13.999-6.268 13.999-14c0-7.73-4.665-13.998-14-13.998C6.665 2 2 8.268 2 15.999s4.664 13.999 13.999 13.999"/><path fill="#5092FF" d="M11 29.297V8H7.5A1.5 1.5 0 0 0 6 9.5v16.91c1.333 1.28 3 2.273 5 2.887m15-2.89c-1.333 1.282-3 2.275-5 2.89V8h3.5A1.5 1.5 0 0 1 26 9.5z"/><path fill="#402A32" d="M6.949 9.316c.048-.145.435-.816 1.551-.816s1.503.67 1.551.816a1 1 0 0 0 1.898-.632C11.664 7.829 10.585 6.5 8.5 6.5S5.336 7.83 5.051 8.684a1 1 0 0 0 1.898.632m15 0c.048-.145.435-.816 1.551-.816s1.503.67 1.551.816a1 1 0 0 0 1.898-.632C26.664 7.829 25.584 6.5 23.5 6.5s-3.164 1.33-3.449 2.184a1 1 0 0 0 1.898.632"/><path fill="#BB1D80" d="M12 15a4 4 0 0 1 8 0v2a4 4 0 0 1-8 0z"/></g></svg>`
  },
  {
    id: "kmind-icon://builtin/faces/neutral-face",
    group: "faces",
    name: "neutral-face",
    label: "Neutral",
    catalog: { "groupId": "faces", "groupLabel": "Faces", "order": 170, "surfaces": ["node-content"] },
    viewBox: "0 0 32 32",
    svg: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" width="100%" height="100%" aria-hidden="true" focusable="false"><g fill="none"><path fill="#FFB02E" d="M15.999 29.998c9.334 0 13.999-6.268 13.999-14c0-7.73-4.665-13.998-14-13.998C6.665 2 2 8.268 2 15.999s4.664 13.999 13.999 13.999"/><path fill="#fff" d="M10.42 16.224a4.206 4.206 0 1 0 0-8.411a4.206 4.206 0 0 0 0 8.411m11.148.077a4.244 4.244 0 1 0 0-8.489a4.244 4.244 0 0 0 0 8.49"/><path fill="#402A32" d="M11 15a3 3 0 1 0 0-6a3 3 0 0 0 0 6m10 0a3 3 0 1 0 0-6a3 3 0 0 0 0 6m-11 5a1 1 0 0 1 1-1h10a1 1 0 1 1 0 2H11a1 1 0 0 1-1-1"/></g></svg>`
  },
  {
    id: "kmind-icon://builtin/faces/pleading-face",
    group: "faces",
    name: "pleading-face",
    label: "Pleading",
    catalog: { "groupId": "faces", "groupLabel": "Faces", "order": 170, "surfaces": ["node-content"] },
    viewBox: "0 0 32 32",
    svg: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" width="100%" height="100%" aria-hidden="true" focusable="false"><g fill="none"><path fill="#FFB02E" d="M15.999 29.998c9.334 0 13.999-6.268 13.999-14c0-7.73-4.665-13.998-14-13.998C6.665 2 2 8.268 2 15.999s4.664 13.999 13.999 13.999"/><path fill="#fff" d="M15 16.5a4.5 4.5 0 1 1-9 0a4.5 4.5 0 0 1 9 0m10.96-.02a4.48 4.48 0 1 1-8.96 0a4.48 4.48 0 0 1 8.96 0"/><path fill="#402A32" d="M10.88 12C8.74 12 7 13.74 7 15.88s1.74 3.88 3.88 3.88s3.88-1.74 3.88-3.88S13.02 12 10.88 12m10 0C18.74 12 17 13.74 17 15.88s1.74 3.88 3.88 3.88s3.88-1.74 3.88-3.88S23.02 12 20.88 12"/><path fill="#fff" d="M13.163 15.937c.745-.237 1.049-1.07.68-1.865c-.367-.788-1.26-1.246-2.006-1.01c-.745.238-1.049 1.07-.68 1.866c.367.795 1.26 1.246 2.006 1.009m10 0c.745-.237 1.049-1.07.68-1.865c-.367-.788-1.27-1.246-2.006-1.01c-.745.238-1.049 1.07-.68 1.866c.367.795 1.26 1.246 2.006 1.009"/><path fill="#402A32" d="M8.952 9.2c.54-.475.875-1.127 1.065-1.83a.5.5 0 0 1 .966.26c-.225.831-.64 1.68-1.371 2.321C8.873 10.6 7.855 11 6.5 11a.5.5 0 0 1 0-1c1.145 0 1.92-.333 2.452-.8m5.944 16.245q-.003.005-.002.002a1 1 0 1 1-1.788-.894C13.434 23.896 14.405 23 16 23s2.566.896 2.894 1.553a1 1 0 1 1-1.788.894l-.002-.002c-.013-.018-.086-.12-.251-.225c-.173-.11-.447-.22-.853-.22s-.68.11-.853.22a.9.9 0 0 0-.25.225M21.983 7.37c.19.703.525 1.355 1.065 1.83c.533.467 1.307.8 2.452.8a.5.5 0 0 1 0 1c-1.355 0-2.373-.4-3.112-1.049c-.73-.642-1.146-1.49-1.37-2.32a.5.5 0 1 1 .965-.262"/></g></svg>`
  },
  {
    id: "kmind-icon://builtin/faces/saluting-face",
    group: "faces",
    name: "saluting-face",
    label: "Salute",
    catalog: { "groupId": "faces", "groupLabel": "Faces", "order": 170, "surfaces": ["node-content"] },
    viewBox: "0 0 32 32",
    svg: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" width="100%" height="100%" aria-hidden="true" focusable="false"><g fill="none"><path fill="#FFB02E" d="M18.297 30c8.002 0 12-5.373 12-12s-3.998-12-12-12s-12 5.373-12 12s3.999 12 12 12"/><path fill="#fff" d="M13.514 18.194a3.605 3.605 0 1 0 0-7.211a3.605 3.605 0 0 0 0 7.21m9.557.067a3.638 3.638 0 1 0 0-7.277a3.638 3.638 0 0 0 0 7.276"/><path fill="#402A32" d="M16.584 14.573a2.572 2.572 0 1 1-5.144 0a2.572 2.572 0 0 1 5.144 0m8.572 0a2.572 2.572 0 1 1-5.143 0a2.572 2.572 0 0 1 5.143 0M14.9 20.178a.75.75 0 0 0-1.213.883c.548.751 2.147 2.152 4.45 2.152c2.282 0 4.093-1.38 4.741-2.087a.75.75 0 0 0-1.107-1.013c-.477.522-1.916 1.6-3.634 1.6c-1.697 0-2.889-1.057-3.237-1.535"/><path fill="#FF822D" d="M14.785 2.637c.115-.07.232-.14.359-.183l.555.242l.222.959a1.048 1.048 0 0 1 .6 1.953l-3.9 2.252a1.062 1.062 0 0 1 .912 1.9l-2.415 1.344a6.34 6.34 0 0 1-3.415.999H4.795l2.978-4.839c-.435-.773-.82-1.483-.82-1.483l4.55-2.67l.455-.263l2.728-.152z"/><path fill="#FFB02E" d="M10.235 2.943a1.05 1.05 0 0 1 1.267.168l1.674-.966a1.048 1.048 0 0 1 1.51.55l.27-.156a1.048 1.048 0 0 1 1.05 1.815L9.367 8.186q.132-.451.173-.928l4.94-2.852c.688-.397.96-1.238.663-1.952q-.097.033-.187.085l-.271.156a1.05 1.05 0 0 1-.462 1.265L9.558 6.654V6.35l1.983-1.145a1.563 1.563 0 0 0 .417-2.357l-.456.263q.095.095.165.216c.29.501.118 1.142-.383 1.432L8.989 6.084v.079q0 .266-.024.529l-.003.039a6 6 0 0 1-.485 1.857a6 6 0 0 1-2.323 2.672l-1.359.843A2.795 2.795 0 0 1 2 9.308v-.072c0-1.058.583-2.03 1.517-2.529l2.36-1.26l-.003.014z"/></g></svg>`
  },
  {
    id: "kmind-icon://builtin/faces/shushing-face",
    group: "faces",
    name: "shushing-face",
    label: "Shh",
    catalog: { "groupId": "faces", "groupLabel": "Faces", "order": 170, "surfaces": ["node-content"] },
    viewBox: "0 0 32 32",
    svg: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" width="100%" height="100%" aria-hidden="true" focusable="false"><g fill="none"><path fill="#FFB02E" d="M15.999 29.998c9.334 0 13.999-6.268 13.999-14c0-7.73-4.665-13.998-14-13.998C6.665 2 2 8.268 2 15.999s4.664 13.999 13.999 13.999"/><path fill="#fff" d="M10.42 16.224a4.206 4.206 0 1 0 0-8.411a4.206 4.206 0 0 0 0 8.411m11.148.077a4.244 4.244 0 1 0 0-8.489a4.244 4.244 0 0 0 0 8.49"/><path fill="#402A32" d="M14 12a3 3 0 1 1-6 0a3 3 0 0 1 6 0m10 0a3 3 0 1 1-6 0a3 3 0 0 1 6 0m-11 8a1 1 0 1 0 0 2h6a1 1 0 1 0 0-2z"/><path fill="#FF822D" d="M18.79 22.02c-.77 0-.77-.77-.77-.77v-3.23c0-1.1-.9-2-2-2s-2 .9-2 2v9.7c0 2.34 1.9 4.23 4.23 4.23h.53c2.34 0 4.23-1.9 4.23-4.23v-1.47c.01-2.33-1.71-4.23-4.22-4.23"/></g></svg>`
  },
  {
    id: "kmind-icon://builtin/faces/slightly-smiling-face",
    group: "faces",
    name: "slightly-smiling-face",
    label: "Smiling",
    catalog: { "groupId": "faces", "groupLabel": "Faces", "order": 170, "surfaces": ["node-content"] },
    viewBox: "0 0 32 32",
    svg: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" width="100%" height="100%" aria-hidden="true" focusable="false"><g fill="none"><path fill="#FFB02E" d="M15.999 29.998c9.334 0 13.999-6.268 13.999-14c0-7.73-4.665-13.998-14-13.998C6.665 2 2 8.268 2 15.999s4.664 13.999 13.999 13.999"/><path fill="#fff" d="M10.42 16.224a4.206 4.206 0 1 0 0-8.411a4.206 4.206 0 0 0 0 8.411m11.148.077a4.244 4.244 0 1 0 0-8.489a4.244 4.244 0 0 0 0 8.49"/><path fill="#402A32" d="M11 15a3 3 0 1 0 0-6a3 3 0 0 0 0 6m10 0a3 3 0 1 0 0-6a3 3 0 0 0 0 6"/><path fill="#402A32" fill-rule="evenodd" d="M10.4 18.2a1 1 0 0 1 1.4.2c.31.413 1.712 1.6 4.2 1.6s3.89-1.187 4.2-1.6a1 1 0 1 1 1.6 1.2c-.69.92-2.688 2.4-5.8 2.4s-5.11-1.48-5.8-2.4a1 1 0 0 1 .2-1.4" clip-rule="evenodd"/></g></svg>`
  },
  {
    id: "kmind-icon://builtin/faces/smiling-face-with-sunglasses",
    group: "faces",
    name: "smiling-face-with-sunglasses",
    label: "Cool",
    catalog: { "groupId": "faces", "groupLabel": "Faces", "order": 170, "surfaces": ["node-content"] },
    viewBox: "0 0 32 32",
    svg: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" width="100%" height="100%" aria-hidden="true" focusable="false"><g fill="none"><path fill="#FFB02E" d="M15.999 29.998c9.334 0 13.999-6.268 13.999-14c0-7.73-4.665-13.998-14-13.998C6.665 2 2 8.268 2 15.999s4.664 13.999 13.999 13.999"/><path fill="#402A32" d="M11.84 18.457a1 1 0 0 0-1.688 1.073l.001.002l.002.003l.004.006l.009.013a2 2 0 0 0 .097.137c.06.08.147.185.26.306c.226.241.563.546 1.03.845C12.5 21.446 13.937 22 16 22s3.5-.554 4.445-1.158a5.4 5.4 0 0 0 1.03-.845a4 4 0 0 0 .357-.443l.01-.013l.003-.006l.001-.002l.001-.001v-.002a1 1 0 0 0-1.686-1.073l-.018.024a2 2 0 0 1-.126.147a3.4 3.4 0 0 1-.65.53c-.62.396-1.682.842-3.367.842s-2.748-.446-3.367-.842a3.4 3.4 0 0 1-.65-.53a2 2 0 0 1-.144-.171"/><path fill="#321B41" d="M11 5H5a4 4 0 0 0-4 4v.674a7 7 0 0 0 3.87 6.26l.935.469a5.8 5.8 0 0 0 4.52.267C13.111 15.675 15 13.025 15 10.067V9a4 4 0 0 0-4-4m9.5 0h7A3.5 3.5 0 0 1 31 8.5v1.174a7 7 0 0 1-3.87 6.26l-.935.469a5.8 5.8 0 0 1-4.52.267C18.889 15.675 17 13.025 17 10.067V8.5A3.5 3.5 0 0 1 20.5 5"/><path fill="#8D65C5" d="M14 6.354A4 4 0 0 0 11 5H5a4 4 0 0 0-4 4v.674a7 7 0 0 0 3.87 6.26l.935.469a5.8 5.8 0 0 0 4.52.267C13.111 15.675 15 13.025 15 10.067V10a1 1 0 1 1 2 0v.067c0 2.958 1.889 5.608 4.675 6.603a5.8 5.8 0 0 0 4.52-.267l.936-.468A7 7 0 0 0 31 9.674V8.5A3.5 3.5 0 0 0 27.5 5h-7c-1.124 0-2.124.53-2.765 1.354V6.35l-.05.05c-.191.197-.582.596-.945.599h-1.744c-.364-.003-.754-.402-.946-.599L14 6.35zM11 6a3 3 0 0 1 3 3v1.067c0 2.53-1.618 4.806-4.011 5.66a4.8 4.8 0 0 1-3.736-.219l-.936-.468A6 6 0 0 1 2 9.674V9a3 3 0 0 1 3-3zm7 2.5A2.5 2.5 0 0 1 20.5 6h7A2.5 2.5 0 0 1 30 8.5v1.174a6 6 0 0 1-3.317 5.366l-.936.468a4.78 4.78 0 0 1-3.736.22C19.618 14.873 18 12.598 18 10.067z"/><path fill="#fff" d="M12.39 10.268c.585-.586.427-1.694-.354-2.475s-1.89-.94-2.475-.354s-.428 1.694.353 2.475s1.89.94 2.475.354m16.001 0c.585-.586.427-1.694-.354-2.475c-.782-.781-1.89-.94-2.475-.354s-.428 1.694.353 2.475s1.89.94 2.475.354"/></g></svg>`
  },
  {
    id: "kmind-icon://builtin/faces/star-struck",
    group: "faces",
    name: "star-struck",
    label: "Star-struck",
    catalog: { "groupId": "faces", "groupLabel": "Faces", "order": 170, "surfaces": ["node-content"] },
    viewBox: "0 0 32 32",
    svg: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" width="100%" height="100%" aria-hidden="true" focusable="false"><g fill="none"><path fill="#FFB02E" d="M15.999 29.998c9.334 0 13.999-6.268 13.999-14c0-7.73-4.665-13.998-14-13.998C6.665 2 2 8.268 2 15.999s4.664 13.999 13.999 13.999"/><path fill="#BB1D80" d="m5.727 15.434l3.05-2.372a2 2 0 0 1 1.62-.382l3.65.73a.25.25 0 0 0 .282-.338l-1.412-3.528a2 2 0 0 1 .257-1.943L14.96 5.22a.4.4 0 0 0-.356-.639L11.11 4.9a2 2 0 0 1-1.78-.792l-1.365-1.82a.72.72 0 0 0-1.282.291l-.472 2.359a2 2 0 0 1-1.218 1.464l-2.53 1.012a.75.75 0 0 0-.085 1.352l1.983 1.102a2 2 0 0 1 1.02 1.929l-.299 3.285a.4.4 0 0 0 .644.352m20.547 0l-3.05-2.372a2 2 0 0 0-1.62-.382l-3.65.73a.25.25 0 0 1-.282-.338l1.412-3.528a2 2 0 0 0-.257-1.943L17.04 5.22a.4.4 0 0 1 .356-.639l3.492.318a2 2 0 0 0 1.782-.792l1.364-1.819a.72.72 0 0 1 1.282.291l.472 2.359a2 2 0 0 0 1.218 1.464l2.53 1.012a.75.75 0 0 1 .085 1.352l-1.983 1.102a2 2 0 0 0-1.02 1.929l.299 3.285a.4.4 0 0 1-.644.352M16 26c-9 0-9-9-9-9h18s0 9-9 9"/><path fill="#fff" d="M8 17.5V17h16v.5a1 1 0 0 1-1 1H9a1 1 0 0 1-1-1"/></g></svg>`
  },
  {
    id: "kmind-icon://builtin/faces/thinking-face",
    group: "faces",
    name: "thinking-face",
    label: "Thinking",
    catalog: { "groupId": "faces", "groupLabel": "Faces", "order": 170, "surfaces": ["node-content"] },
    viewBox: "0 0 32 32",
    svg: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" width="100%" height="100%" aria-hidden="true" focusable="false"><g fill="none"><path fill="#FFB02E" d="M15.999 29.998c9.334 0 13.999-6.268 13.999-14c0-7.73-4.665-13.998-14-13.998C6.665 2 2 8.268 2 15.999s4.664 13.999 13.999 13.999"/><path fill="#FFB02E" d="M10 21.5v-3.06A1.44 1.44 0 0 0 8.56 17c-.84 0-1.505.718-1.517 1.559C7.023 19.92 6.835 21.722 6 22c-3 1-4 5.5-1.5 7.5c2 1.6 4 1.5 5.5 1.5h2.764a1.236 1.236 0 0 0 .553-2.342L13 28.5h.72a1 1 0 0 0 .97-.758l.067-.272A.78.78 0 0 0 14 26.5l.33-.165a1.214 1.214 0 0 0 0-2.17L14 24h1.75a1.25 1.25 0 1 0 0-2.5z"/><path fill="#fff" d="M10.42 16.224a4.206 4.206 0 1 0 0-8.411a4.206 4.206 0 0 0 0 8.411m11.148.077a4.244 4.244 0 1 0 0-8.489a4.244 4.244 0 0 0 0 8.49"/><path fill="#FF822D" d="M10 21.5v-3.06A1.44 1.44 0 0 0 8.56 17c-.84 0-1.505.718-1.517 1.559C7.023 19.92 6.835 21.722 6 22c-3 1-4 5.5-1.5 7.5c2 1.6 4 1.5 5.5 1.5h2.764a1.236 1.236 0 0 0 .553-2.342L13 28.5h.72a1 1 0 0 0 .97-.758l.067-.272A.78.78 0 0 0 14 26.5l.33-.165a1.214 1.214 0 0 0 0-2.17L14 24h1.75a1.25 1.25 0 1 0 0-2.5z"/><path fill="#402A32" d="M7.146 4.146C7.543 3.75 8.63 3 10 3s2.457.75 2.854 1.146a.5.5 0 0 1-.708.708C11.876 4.584 11.03 4 10 4s-1.877.584-2.146.854a.5.5 0 1 1-.708-.708m11.034 3.97C18.65 7.724 19.92 7 21.5 7s2.85.724 3.32 1.116a.5.5 0 0 1-.64.768C23.85 8.61 22.8 8 21.5 8s-2.35.61-2.68.884a.5.5 0 0 1-.64-.768M13 11.5a3 3 0 1 1-6 0a3 3 0 0 1 6 0"/><path fill="#402A32" d="M24 11.5a3 3 0 1 1-6 0a3 3 0 0 1 6 0m-7.919 7.486a2.73 2.73 0 0 0-2.374.721a1 1 0 0 1-1.414-1.414a4.73 4.73 0 0 1 4.126-1.279c1.962.336 2.973 1.457 3.488 2.565a1 1 0 0 1-1.814.842c-.28-.604-.791-1.227-2.012-1.435"/></g></svg>`
  },
  {
    id: "kmind-icon://builtin/focus/bullseye",
    group: "focus",
    name: "bullseye",
    label: "Goal",
    catalog: { "groupId": "focus", "groupLabel": "Focus & Goals", "order": 160, "surfaces": ["node-content"] },
    viewBox: "0 0 32 32",
    svg: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" width="100%" height="100%" aria-hidden="true" focusable="false"><g fill="none"><path fill="#F4F4F4" d="M14 28.292c5.684 0 10.292-4.608 10.292-10.292S19.684 7.708 14 7.708S3.708 12.316 3.708 18S8.316 28.292 14 28.292"/><path fill="#F8312F" d="M26 18c0-6.627-5.373-12-12-12S2 11.373 2 18s5.373 12 12 12s12-5.373 12-12m-3 0a9 9 0 1 1-18 0a9 9 0 0 1 18 0m-9 6a6 6 0 1 1 0-12a6 6 0 0 1 0 12m3-6a3 3 0 1 0-6 0a3 3 0 0 0 6 0"/><path fill="#9B9B9B" d="M14.25 17.742a.864.864 0 0 0 1.232 0l4.26-4.254a.86.86 0 0 0 0-1.23a.864.864 0 0 0-1.232 0l-4.26 4.254a.88.88 0 0 0 0 1.23"/><path fill="#46A4FB" d="m19.658 10.093l-.45-1.59c-.54-1.9-.01-3.95 1.39-5.34l.89-.89a.906.906 0 0 1 1.52.39L24 6zM22 12.33l1.572.458c1.878.55 3.904.01 5.278-1.416l.88-.906c.494-.5.277-1.356-.385-1.55L26 8z"/><path fill="#50E2FF" d="M15.85 16.152a2.892 2.892 0 0 0 4.307-.24l5.424-6.798a1.92 1.92 0 0 0-2.698-2.696l-6.802 5.42a2.904 2.904 0 0 0-.231 4.314"/><path fill="#46A4FB" d="M21.258 10.742a.86.86 0 0 0 1.23 0l4.254-4.254a.86.86 0 0 0 0-1.23a.86.86 0 0 0-1.23 0l-4.254 4.254a.86.86 0 0 0 0 1.23"/></g></svg>`
  },
  {
    id: "kmind-icon://builtin/focus/gear",
    group: "focus",
    name: "gear",
    label: "System",
    catalog: { "groupId": "focus", "groupLabel": "Focus & Goals", "order": 160, "surfaces": ["node-content"] },
    viewBox: "0 0 32 32",
    svg: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" width="100%" height="100%" aria-hidden="true" focusable="false"><g fill="none"><path fill="#B4ACBC" d="M12.847 3.834A2 2 0 0 1 14.84 2h2.32a2 2 0 0 1 1.993 1.834l.235 2.825a.5.5 0 0 0 .821.34l2.164-1.831a2 2 0 0 1 2.706.112l1.64 1.64a2 2 0 0 1 .113 2.707l-1.83 2.163a.5.5 0 0 0 .34.822l2.824.235A2 2 0 0 1 30 14.84v2.32a2 2 0 0 1-1.834 1.993l-2.825.235a.5.5 0 0 0-.34.821l1.831 2.164a2 2 0 0 1-.112 2.706l-1.64 1.64a2 2 0 0 1-2.707.113l-2.164-1.83a.5.5 0 0 0-.82.34l-.236 2.824A2 2 0 0 1 17.16 30h-2.32a2 2 0 0 1-1.993-1.834l-.235-2.825a.5.5 0 0 0-.822-.34l-2.163 1.831a2 2 0 0 1-2.706-.112l-1.64-1.64a2 2 0 0 1-.113-2.707l1.83-2.164a.5.5 0 0 0-.34-.82l-2.824-.236A2 2 0 0 1 2 17.16v-2.32a2 2 0 0 1 1.834-1.993l2.825-.235a.5.5 0 0 0 .34-.822L5.168 9.628A2 2 0 0 1 5.28 6.92l1.64-1.64a2 2 0 0 1 2.707-.113l2.163 1.83a.5.5 0 0 0 .822-.34zM21 16a5 5 0 1 0-10 0a5 5 0 0 0 10 0"/><path fill="#998EA4" d="M24 16a8 8 0 1 1-16 0a8 8 0 0 1 16 0m-3.5 0a4.5 4.5 0 1 0-9 0a4.5 4.5 0 0 0 9 0"/><path fill="#CDC4D6" d="M10.5 16a5.5 5.5 0 1 1 11 0a5.5 5.5 0 0 1-11 0M21 16a5 5 0 1 0-10 0a5 5 0 0 0 10 0"/></g></svg>`
  },
  {
    id: "kmind-icon://builtin/focus/puzzle-piece",
    group: "focus",
    name: "puzzle-piece",
    label: "Strategy",
    catalog: { "groupId": "focus", "groupLabel": "Focus & Goals", "order": 160, "surfaces": ["node-content"] },
    viewBox: "0 0 32 32",
    svg: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" width="100%" height="100%" aria-hidden="true" focusable="false"><g fill="none"><path fill="#D3D3D3" d="m23.623 21.425l.995.996a1.37 1.37 0 0 0 1.94 0l3.143-3.147a1.01 1.01 0 0 0 0-1.434l-5.83-5.837a.445.445 0 0 1 0-.637c.11-.11.26-.15.399-.12c.945.16 1.95-.12 2.676-.846a3.07 3.07 0 0 0-.03-4.362l-.856-.867l-.388.13a3.05 3.05 0 0 0-3.89 3.406c.02.15-.02.289-.129.398l-.02.02a.444.444 0 0 1-.636 0L15.167 3.3a1.01 1.01 0 0 0-1.433 0l-3.113 3.117c-.08.08-.14.17-.2.259l-.208-.21l-.737.738l1.144 1.145l.02.02c.279.279.657.428 1.045.408a3.06 3.06 0 0 1 2.457 1.056a3.07 3.07 0 0 1 0 4.004a3.06 3.06 0 0 1-4.477.17a3.01 3.01 0 0 1-.885-2.351c.02-.389-.12-.767-.398-1.046a.1.1 0 0 0-.03-.04l-.975-.976l-.427.438l.189.19a1.34 1.34 0 0 0-.697.378l-3.144 3.147a1.01 1.01 0 0 0 0 1.434l5.84 5.847c.18.179.18.458 0 .637a.43.43 0 0 1-.398.12a3.06 3.06 0 0 0-2.815.995a3.07 3.07 0 0 0-.01 4.014a3.05 3.05 0 0 0 4.477.16a3.06 3.06 0 0 0 .855-2.64a.46.46 0 0 1 .13-.398l.02-.02a.444.444 0 0 1 .636 0l5.8 5.806a1.01 1.01 0 0 0 1.433 0l3.114-3.117a1.37 1.37 0 0 0 0-1.942l-.02-.02l-.886-.887l-.388.389l.11.11a3.07 3.07 0 0 1-2.328-1.056a3.07 3.07 0 0 1 0-4.004a3.06 3.06 0 0 1 4.477-.17c.517.519.815 1.186.875 1.863l-.02-.02z"/><path fill="#C3EF3C" d="M21.77 4.91a3.05 3.05 0 0 0-1.014 2.789c.02.15-.02.289-.13.398l-.02.02a.444.444 0 0 1-.636 0L14.153 2.3a1.007 1.007 0 0 0-1.433 0L9.608 5.417a1.373 1.373 0 0 0 0 1.943l.03.02c.268.27.646.419 1.034.399a3.05 3.05 0 0 1 2.456 1.056a3.07 3.07 0 0 1 0 4.005a3.06 3.06 0 0 1-4.475.17a3.12 3.12 0 0 1-.885-2.362c.03-.389-.12-.777-.398-1.046a1.367 1.367 0 0 0-1.94 0L2.299 12.74a1.01 1.01 0 0 0 0 1.435l5.838 5.848a.446.446 0 0 1 0 .638a.43.43 0 0 1-.398.12a3.06 3.06 0 0 0-2.814.996a3.075 3.075 0 0 0-.01 4.015a3.05 3.05 0 0 0 4.475.16a3.06 3.06 0 0 0 .855-2.64a.46.46 0 0 1 .13-.4l.02-.02a.444.444 0 0 1 .636 0l5.798 5.81a1.007 1.007 0 0 0 1.432 0l3.112-3.12a1.373 1.373 0 0 0 0-1.942l-.02-.02a1.37 1.37 0 0 0-1.034-.399a3.05 3.05 0 0 1-2.456-1.056a3.07 3.07 0 0 1 0-4.005a3.06 3.06 0 0 1 4.475-.17c.646.648.945 1.505.885 2.352c-.02.389.12.767.398 1.046a1.367 1.367 0 0 0 1.94 0l3.142-3.148a1.01 1.01 0 0 0 0-1.435l-5.828-5.838a.446.446 0 0 1 0-.638c.11-.11.259-.15.398-.12a3.05 3.05 0 0 0 2.675-.846a3.063 3.063 0 0 0-.17-4.484c-1.153-.956-2.873-.956-4.007.03"/></g></svg>`
  },
  {
    id: "kmind-icon://builtin/focus/rocket",
    group: "focus",
    name: "rocket",
    label: "Launch",
    catalog: { "groupId": "focus", "groupLabel": "Focus & Goals", "order": 160, "surfaces": ["node-content"] },
    viewBox: "0 0 32 32",
    svg: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" width="100%" height="100%" aria-hidden="true" focusable="false"><g fill="none"><path fill="#CA0B4A" d="M29.2 2.95c-.947-.947-2.7-.998-3.818-.425c-.913.314-1.874.667-2.854 1.063l.01.01c-2.575 1.095-6.427 3.04-9.51 5.902c-2.164 2.01-3.404 3.556-4.235 4.965l-5.298 1.95a1 1 0 0 0-.362 1.646l11.138 11.137a1 1 0 0 0 1.645-.362l2.204-5.986c1.608-.958 3.223-2.165 4.908-3.85c2.39-2.39 4.366-6.56 5.513-9.357l.009.008c.4-.99.758-1.961 1.074-2.883c.573-1.118.74-2.654-.424-3.818"/><path fill="#F4F4F4" d="M23.299 4.365c-2.517 1.04-6.478 2.978-9.59 5.868c-2.015 1.87-3.172 3.294-3.94 4.55c-.769 1.255-1.175 2.38-1.663 3.74l-.002.007c-.17.474-.35.977-.559 1.514l4.556 4.556c3.602-1.48 6.74-2.828 10.22-6.307c2.351-2.352 4.339-6.642 5.454-9.421z"/><path fill="#9B9B9B" d="M24.528 11.25a3.25 3.25 0 1 1-6.5 0a3.25 3.25 0 0 1 6.5 0"/><path fill="#83CBFF" d="M23.528 11.25a2.25 2.25 0 1 1-4.5 0a2.25 2.25 0 0 1 4.5 0"/><path fill="#FF8257" d="M2.451 29.61C1.744 28.905 2.028 24 4.528 23c0 0 2.5-1 4.11.6c1.612 1.601.89 3.4.89 3.4c-.707 2.121-3.718 2.965-4.071 2.61c-.195-.194.156-.55 0-.706c-.157-.157-.398.022-1.06.353c-.472.236-1.663.637-1.946.354"/><path fill="#533566" d="M6.088 21.06a1.5 1.5 0 0 1 2.122 0l3.535 3.536a1.5 1.5 0 1 1-2.121 2.122l-3.536-3.536a1.5 1.5 0 0 1 0-2.121"/><path fill="#F92F60" d="M15.535 18.722c.442-1.2-.725-2.368-1.926-1.926l-7.114 2.619a1 1 0 0 0-.362 1.646l5.138 5.137a1 1 0 0 0 1.645-.362z"/></g></svg>`
  },
  {
    id: "kmind-icon://builtin/focus/sparkles",
    group: "focus",
    name: "sparkles",
    label: "Highlight",
    catalog: { "groupId": "focus", "groupLabel": "Focus & Goals", "order": 160, "surfaces": ["node-content"] },
    viewBox: "0 0 32 32",
    svg: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" width="100%" height="100%" aria-hidden="true" focusable="false"><path fill="#F9C23C" d="M10.52 7.052a1.17 1.17 0 0 1-.639-.636L8.93 4.257c-.178-.343-.69-.343-.858 0l-.952 2.16a1.28 1.28 0 0 1-.638.635l-1.214.524a.462.462 0 0 0 0 .838l1.214.524c.293.121.523.353.638.636l.952 2.169c.178.343.69.343.858 0l.952-2.17c.126-.282.356-.504.638-.635l1.214-.524a.462.462 0 0 0 0-.838zm15.054 6.503a3.73 3.73 0 0 1-1.922-1.977L20.79 4.81a1.432 1.432 0 0 0-2.58 0l-2.863 6.768a3.8 3.8 0 0 1-1.921 1.977l-3.622 1.64c-1.072.53-1.072 2.08 0 2.61l3.622 1.64a3.74 3.74 0 0 1 1.922 1.977l2.862 6.768a1.432 1.432 0 0 0 2.58 0l2.863-6.768a3.8 3.8 0 0 1 1.921-1.977l3.622-1.64c1.072-.53 1.072-2.08 0-2.61zM8.281 20.33c.16.392.454.696.822.872l1.55.725a.646.646 0 0 1 0 1.146l-1.55.725c-.368.176-.661.49-.822.872l-1.228 2.977a.61.61 0 0 1-1.106 0L4.72 24.67a1.66 1.66 0 0 0-.822-.872l-1.55-.725a.646.646 0 0 1 0-1.146l1.55-.725c.368-.176.661-.49.822-.872l1.228-2.977a.61.61 0 0 1 1.106 0z"/></svg>`
  },
  {
    id: "kmind-icon://builtin/focus/trophy",
    group: "focus",
    name: "trophy",
    label: "Milestone",
    catalog: { "groupId": "focus", "groupLabel": "Focus & Goals", "order": 160, "surfaces": ["node-content"] },
    viewBox: "0 0 32 32",
    svg: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" width="100%" height="100%" aria-hidden="true" focusable="false"><g fill="none"><path fill="#D3883E" d="M10.52 7.521a3.435 3.435 0 0 0-4.213-2.369a2 2 0 0 0-.163.046c-2.493.831-2.691 4.214-.455 5.45l4.97 2.75a.866.866 0 1 0 .838-1.516l-4.97-2.75c-.982-.543-.823-1.956.16-2.288l.005-.002l.07-.018c.899-.25 1.834.27 2.093 1.175a.866.866 0 1 0 1.666-.478m11.939.478a1.7 1.7 0 0 1 2.118-1.168l.045.011l.007.002c.981.332 1.14 1.745.158 2.288l-4.97 2.75a.866.866 0 1 0 .84 1.516l4.97-2.75c2.235-1.236 2.037-4.619-.456-5.45a2 2 0 0 0-.164-.046a3.435 3.435 0 0 0-4.213 2.37a.866.866 0 1 0 1.666.477m-5.133 9.511v-4.22h-3.34v4.22c0 .74-.33 1.45-.9 1.92l-1.92 1.6h8.98l-1.92-1.6a2.51 2.51 0 0 1-.9-1.92"/><path fill="#FFB02E" d="M15.658 16.54a6.97 6.97 0 0 1-6.97-6.97V2.71c0-.39.32-.71.71-.71h12.53c.39 0 .71.32.71.71v6.86c0 3.85-3.12 6.97-6.98 6.97"/><path fill="#6D4534" d="M22.792 21.03H8.197c-.77 0-1.423.51-1.571 1.22l-1.614 7.09c-.073.33.19.64.549.64h19.878c.359 0 .622-.31.549-.64l-1.614-7.09c-.158-.71-.812-1.22-1.582-1.22"/><path fill="#FFB02E" d="M18.383 23.96h-5.766a.625.625 0 0 0-.613.64v1.81c0 .35.268.64.613.64h5.766c.335 0 .613-.28.613-.64V24.6c0-.35-.268-.64-.613-.64"/></g></svg>`
  },
  {
    id: "kmind-icon://builtin/keycaps/keycap-0",
    group: "keycaps",
    name: "keycap-0",
    label: "Priority 0",
    catalog: { "groupId": "keycaps", "groupLabel": "Priority Numbers", "order": 180, "surfaces": ["node-content"] },
    viewBox: "0 0 32 32",
    svg: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" width="100%" height="100%" aria-hidden="true" focusable="false"><g fill="none"><path fill="#94A3B8" d="M2 6a4 4 0 0 1 4-4h20a4 4 0 0 1 4 4v20a4 4 0 0 1-4 4H6a4 4 0 0 1-4-4z"/><path fill="#fff" d="M10 13.75a6 6 0 0 1 12 0v4.5a6 6 0 0 1-12 0zm6-2.5a2.5 2.5 0 0 0-2.5 2.5v4.5a2.5 2.5 0 0 0 5 0v-4.5a2.5 2.5 0 0 0-2.5-2.5"/></g></svg>`
  },
  {
    id: "kmind-icon://builtin/keycaps/keycap-1",
    group: "keycaps",
    name: "keycap-1",
    label: "Priority 1",
    catalog: { "groupId": "keycaps", "groupLabel": "Priority Numbers", "order": 180, "surfaces": ["node-content"] },
    viewBox: "0 0 32 32",
    svg: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" width="100%" height="100%" aria-hidden="true" focusable="false"><g fill="none"><path fill="#60A5FA" d="M2 6a4 4 0 0 1 4-4h20a4 4 0 0 1 4 4v20a4 4 0 0 1-4 4H6a4 4 0 0 1-4-4z"/><path fill="#fff" d="M17.574 7.875c.665.266 1.1.91 1.1 1.625v13a1.75 1.75 0 1 1-3.5 0v-8.625l-.157.165a1.75 1.75 0 1 1-2.534-2.413l3.174-3.334a1.75 1.75 0 0 1 1.917-.418"/></g></svg>`
  },
  {
    id: "kmind-icon://builtin/keycaps/keycap-2",
    group: "keycaps",
    name: "keycap-2",
    label: "Priority 2",
    catalog: { "groupId": "keycaps", "groupLabel": "Priority Numbers", "order": 180, "surfaces": ["node-content"] },
    viewBox: "0 0 32 32",
    svg: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" width="100%" height="100%" aria-hidden="true" focusable="false"><g fill="none"><path fill="#38BDF8" d="M2 6a4 4 0 0 1 4-4h20a4 4 0 0 1 4 4v20a4 4 0 0 1-4 4H6a4 4 0 0 1-4-4z"/><path fill="#fff" d="M16.3 11.252c-.31.015-.8.168-1.35.823a1.75 1.75 0 0 1-2.678-2.252c1.077-1.282 2.43-1.996 3.853-2.067c1.4-.07 2.68.493 3.593 1.404c1.905 1.9 2.141 5.144-.302 7.768c-.71.763-1.574 1.665-2.445 2.576c-.4.418-.801.837-1.19 1.246h4.099a1.75 1.75 0 1 1 0 3.5h-7.02c-1.88 0-3.005-2.244-1.66-3.728c.852-.939 2.117-2.261 3.322-3.522c.866-.906 1.702-1.78 2.333-2.457c.666-.716.84-1.343.843-1.784c.001-.457-.18-.85-.452-1.121a1.25 1.25 0 0 0-.946-.386"/></g></svg>`
  },
  {
    id: "kmind-icon://builtin/keycaps/keycap-3",
    group: "keycaps",
    name: "keycap-3",
    label: "Priority 3",
    catalog: { "groupId": "keycaps", "groupLabel": "Priority Numbers", "order": 180, "surfaces": ["node-content"] },
    viewBox: "0 0 32 32",
    svg: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" width="100%" height="100%" aria-hidden="true" focusable="false"><g fill="none"><path fill="#22C55E" d="M2 6a4 4 0 0 1 4-4h20a4 4 0 0 1 4 4v20a4 4 0 0 1-4 4H6a4 4 0 0 1-4-4z"/><path fill="#fff" d="M14.291 12.225a1.556 1.556 0 1 1 2.015 2.105a1.75 1.75 0 0 0-.252 3.443l.086.023a1.558 1.558 0 0 1-.446 3.047a1.56 1.56 0 0 1-1.483-1.083a1.75 1.75 0 0 0-3.335 1.061a5.057 5.057 0 1 0 8.737-4.728a5.056 5.056 0 1 0-8.475-5.388a1.75 1.75 0 0 0 3.153 1.52"/></g></svg>`
  },
  {
    id: "kmind-icon://builtin/keycaps/keycap-4",
    group: "keycaps",
    name: "keycap-4",
    label: "Priority 4",
    catalog: { "groupId": "keycaps", "groupLabel": "Priority Numbers", "order": 180, "surfaces": ["node-content"] },
    viewBox: "0 0 32 32",
    svg: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" width="100%" height="100%" aria-hidden="true" focusable="false"><g fill="none"><path fill="#84CC16" d="M2 6a4 4 0 0 1 4-4h20a4 4 0 0 1 4 4v20a4 4 0 0 1-4 4H6a4 4 0 0 1-4-4z"/><path fill="#fff" d="M14.613 7.802a1.75 1.75 0 0 1 1.275 2.121l-1.292 5.182h1.9V14a1.75 1.75 0 1 1 3.5 0v1.14a1.75 1.75 0 0 1 0 3.43v3.81a1.75 1.75 0 1 1-3.5 0v-3.775h-4.14a1.75 1.75 0 0 1-1.698-2.173l1.834-7.355a1.75 1.75 0 0 1 2.121-1.275"/></g></svg>`
  },
  {
    id: "kmind-icon://builtin/keycaps/keycap-5",
    group: "keycaps",
    name: "keycap-5",
    label: "Priority 5",
    catalog: { "groupId": "keycaps", "groupLabel": "Priority Numbers", "order": 180, "surfaces": ["node-content"] },
    viewBox: "0 0 32 33",
    svg: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 33" width="100%" height="100%" aria-hidden="true" focusable="false"><g fill="none"><path fill="#FACC15" d="M2 6.12a4 4 0 0 1 4-4h20a4 4 0 0 1 4 4v20a4 4 0 0 1-4 4H6a4 4 0 0 1-4-4z"/><path fill="#fff" d="M11.078 9.87c0-.966.784-1.75 1.75-1.75h5.438a1.75 1.75 0 0 1 0 3.5h-3.688v1.525h.969a5.61 5.61 0 1 1-4.206 9.321a1.75 1.75 0 0 1 2.624-2.316a2.11 2.11 0 1 0 1.582-3.504h-2.719a1.75 1.75 0 0 1-1.75-1.75z"/></g></svg>`
  },
  {
    id: "kmind-icon://builtin/keycaps/keycap-6",
    group: "keycaps",
    name: "keycap-6",
    label: "Priority 6",
    catalog: { "groupId": "keycaps", "groupLabel": "Priority Numbers", "order": 180, "surfaces": ["node-content"] },
    viewBox: "0 0 32 32",
    svg: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" width="100%" height="100%" aria-hidden="true" focusable="false"><g fill="none"><path fill="#F59E0B" d="M2 6a4 4 0 0 1 4-4h20a4 4 0 0 1 4 4v20a4 4 0 0 1-4 4H6a4 4 0 0 1-4-4z"/><path fill="#fff" d="M19.117 10.618a1.75 1.75 0 1 0-2.984-1.83l-4.531 7.391a1.8 1.8 0 0 0-.177.387a5.25 5.25 0 1 0 5.8-2.863zm-4.71 8.226a1.75 1.75 0 1 1 3.5 0a1.75 1.75 0 0 1-3.5 0"/></g></svg>`
  },
  {
    id: "kmind-icon://builtin/keycaps/keycap-7",
    group: "keycaps",
    name: "keycap-7",
    label: "Priority 7",
    catalog: { "groupId": "keycaps", "groupLabel": "Priority Numbers", "order": 180, "surfaces": ["node-content"] },
    viewBox: "0 0 32 32",
    svg: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" width="100%" height="100%" aria-hidden="true" focusable="false"><g fill="none"><path fill="#FB923C" d="M2 6a4 4 0 0 1 4-4h20a4 4 0 0 1 4 4v20a4 4 0 0 1-4 4H6a4 4 0 0 1-4-4z"/><path fill="#fff" d="M11.038 9.722c0-.966.784-1.75 1.75-1.75h7.474a1.75 1.75 0 0 1 1.52 2.619l-7.253 12.695a1.75 1.75 0 0 1-3.039-1.736l5.757-10.078h-4.459a1.75 1.75 0 0 1-1.75-1.75"/></g></svg>`
  },
  {
    id: "kmind-icon://builtin/keycaps/keycap-8",
    group: "keycaps",
    name: "keycap-8",
    label: "Priority 8",
    catalog: { "groupId": "keycaps", "groupLabel": "Priority Numbers", "order": 180, "surfaces": ["node-content"] },
    viewBox: "0 0 32 32",
    svg: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" width="100%" height="100%" aria-hidden="true" focusable="false"><g fill="none"><path fill="#F97316" d="M2 6a4 4 0 0 1 4-4h20a4 4 0 0 1 4 4v20a4 4 0 0 1-4 4H6a4 4 0 0 1-4-4z"/><path fill="#fff" d="M15.972 7.968a4.516 4.516 0 0 0-3.534 7.329a5.237 5.237 0 1 0 7.091-.03a4.516 4.516 0 0 0-3.557-7.3m-1.266 4.516a1.266 1.266 0 1 1 2.532 0a1.266 1.266 0 0 1-2.532 0m-.443 6.652a1.737 1.737 0 1 1 3.474 0a1.737 1.737 0 0 1-3.474 0"/></g></svg>`
  },
  {
    id: "kmind-icon://builtin/keycaps/keycap-9",
    group: "keycaps",
    name: "keycap-9",
    label: "Priority 9",
    catalog: { "groupId": "keycaps", "groupLabel": "Priority Numbers", "order": 180, "surfaces": ["node-content"] },
    viewBox: "0 0 32 32",
    svg: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" width="100%" height="100%" aria-hidden="true" focusable="false"><g fill="none"><path fill="#EF4444" d="M2 6a4 4 0 0 1 4-4h20a4 4 0 0 1 4 4v20a4 4 0 0 1-4 4H6a4 4 0 0 1-4-4z"/><path fill="#fff" d="M20.888 15.481a5.25 5.25 0 1 0-5.8 2.863l-1.892 3.085a1.75 1.75 0 0 0 2.983 1.83l4.532-7.391q.114-.187.177-.387m-2.982-2.278a1.75 1.75 0 1 1-3.5 0a1.75 1.75 0 0 1 3.5 0"/></g></svg>`
  },
  {
    id: "kmind-icon://builtin/keycaps/keycap-asterisk",
    group: "keycaps",
    name: "keycap-asterisk",
    label: "Priority *",
    catalog: { "groupId": "keycaps", "groupLabel": "Priority Numbers", "order": 180, "surfaces": ["node-content"] },
    viewBox: "0 0 32 32",
    svg: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" width="100%" height="100%" aria-hidden="true" focusable="false"><g fill="none"><path fill="#A855F7" d="M2 6a4 4 0 0 1 4-4h20a4 4 0 0 1 4 4v20a4 4 0 0 1-4 4H6a4 4 0 0 1-4-4z"/><path fill="#fff" d="M16.022 7.75c.967 0 1.75.784 1.75 1.75v3.456l2.982-1.721a1.75 1.75 0 1 1 1.75 3.03L19.5 16l3.004 1.735a1.75 1.75 0 1 1-1.75 3.03l-2.982-1.721V22.5a1.75 1.75 0 1 1-3.5 0v-3.482l-3.026 1.748a1.75 1.75 0 0 1-1.75-3.031L12.5 16l-3.004-1.734a1.75 1.75 0 0 1 1.75-3.031l3.026 1.747V9.5c0-.966.784-1.75 1.75-1.75"/></g></svg>`
  },
  {
    id: "kmind-icon://builtin/keycaps/keycap-hashtag",
    group: "keycaps",
    name: "keycap-hashtag",
    label: "Priority #",
    catalog: { "groupId": "keycaps", "groupLabel": "Priority Numbers", "order": 180, "surfaces": ["node-content"] },
    viewBox: "0 0 32 32",
    svg: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" width="100%" height="100%" aria-hidden="true" focusable="false"><g fill="none"><path fill="#14B8A6" d="M2 6a4 4 0 0 1 4-4h20a4 4 0 0 1 4 4v20a4 4 0 0 1-4 4H6a4 4 0 0 1-4-4z"/><path fill="#fff" d="M12.412 9.404a1.497 1.497 0 1 1 2.989.186l-.134 2.144a.25.25 0 0 0 .25.266h1.498a.25.25 0 0 0 .25-.234l.147-2.362a1.497 1.497 0 1 1 2.989.186l-.134 2.144a.25.25 0 0 0 .25.266h.983a1.5 1.5 0 0 1 0 3h-1.203a.25.25 0 0 0-.25.234l-.093 1.5a.25.25 0 0 0 .25.266H21.5a1.5 1.5 0 0 1 0 3h-1.515a.25.25 0 0 0-.25.234l-.147 2.362a1.497 1.497 0 1 1-2.989-.186l.134-2.144a.25.25 0 0 0-.25-.266h-1.498a.25.25 0 0 0-.25.234l-.147 2.362a1.497 1.497 0 1 1-2.989-.186l.134-2.144a.25.25 0 0 0-.25-.266H10.5a1.5 1.5 0 0 1 0-3h1.203a.25.25 0 0 0 .25-.234l.093-1.5a.25.25 0 0 0-.25-.266H10.5a1.5 1.5 0 0 1 0-3h1.515a.25.25 0 0 0 .25-.234zM16.702 17a.25.25 0 0 0 .25-.234l.094-1.5a.25.25 0 0 0-.25-.266h-1.499a.25.25 0 0 0-.25.234l-.093 1.5a.25.25 0 0 0 .25.266z"/></g></svg>`
  },
  {
    id: "kmind-icon://builtin/knowledge/books",
    group: "knowledge",
    name: "books",
    label: "Reading",
    catalog: { "groupId": "knowledge", "groupLabel": "Knowledge", "order": 130, "surfaces": ["node-content"] },
    viewBox: "0 0 32 32",
    svg: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" width="100%" height="100%" aria-hidden="true" focusable="false"><g fill="none"><path fill="#00A6ED" d="M17.045 27.286H30V13a2 2 0 0 0-2-2H17.045z"/><path fill="#D3D3D3" d="M15.682 27.964H30v1.357H15.682z"/><path fill="#0074BA" d="M16.023 11A1.02 1.02 0 0 0 15 12.018v16.625h.682a.68.68 0 0 1 .682-.679h.681V11z"/><path fill="#0074BA" d="M16.023 27.286A1.02 1.02 0 0 0 15 28.304v.678A1.02 1.02 0 0 0 16.023 30h12.954c.446 0 .824-.283.965-.678H16.364a.68.68 0 0 1-.682-.68a.68.68 0 0 1 .682-.678H30v-.678z"/><path fill="#CA0B4A" d="M10.045 23.286H23V9a2 2 0 0 0-2-2H10.045z"/><path fill="#D3D3D3" d="M8.682 23.964H23v1.357H8.682z"/><path fill="#990838" d="M9.023 7A1.02 1.02 0 0 0 8 8.018v16.625h.682a.68.68 0 0 1 .682-.679h.681V7z"/><path fill="#990838" d="M9.023 23.286A1.02 1.02 0 0 0 8 24.304v.678A1.02 1.02 0 0 0 9.023 26h12.954c.446 0 .824-.283.965-.678H9.364a.68.68 0 0 1-.682-.68a.68.68 0 0 1 .682-.678H23v-.678z"/><path fill="#86D72F" d="M4.045 20.286H17V6a2 2 0 0 0-2-2H4.045z"/><path fill="#D3D3D3" d="M2.682 20.964H17v1.357H2.682z"/><path fill="#44911B" d="M3.023 4A1.02 1.02 0 0 0 2 5.018v16.625h.682a.68.68 0 0 1 .682-.679h.681V4z"/><path fill="#008463" d="M3.023 20.286A1.02 1.02 0 0 0 2 21.304v.678A1.02 1.02 0 0 0 3.023 23h12.954c.446 0 .824-.283.965-.678H3.364a.68.68 0 0 1-.682-.68a.68.68 0 0 1 .682-.678H17v-.678z"/></g></svg>`
  },
  {
    id: "kmind-icon://builtin/knowledge/graduation-cap",
    group: "knowledge",
    name: "graduation-cap",
    label: "Learning",
    catalog: { "groupId": "knowledge", "groupLabel": "Knowledge", "order": 130, "surfaces": ["node-content"] },
    viewBox: "0 0 32 32",
    svg: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" width="100%" height="100%" aria-hidden="true" focusable="false"><g fill="none"><path fill="#533566" d="M19.3 23.138h-6.64c-3.84 0-6.95-3.11-6.95-6.95v-4.36h20.53v4.36c.01 3.84-3.1 6.95-6.94 6.95"/><path fill="#321B41" d="m17.13 5.278l12.28 6.29c.76.39.76 1.48 0 1.87l-12.28 6.29c-.72.37-1.56.37-2.28 0l-12.28-6.29c-.76-.39-.76-1.48 0-1.87l12.28-6.29a2.48 2.48 0 0 1 2.28 0"/><path fill="#FFB02E" d="M15.15 12.048c.19-.41.68-.57 1.08-.37l6.71 3.44c.27.14.43.41.43.71v6.28a1.83 1.83 0 0 1 .97 2.1v.02c-.01.04-.02.09-.04.13c0 .01-.01.02-.01.03c-.01.04-.03.08-.05.12c0 .01-.01.02-.01.02c-.05.11-.12.22-.19.31c-.01.02-.02.03-.04.05l.47 2.2a1.94 1.94 0 0 1-1.9 2.35a1.94 1.94 0 0 1-1.9-2.35l.47-2.2c-.25-.31-.4-.7-.4-1.13c0-.25.05-.49.14-.7c0-.01.01-.02.02-.03c.01-.03.03-.07.05-.1c.02-.04.04-.08.07-.12c.01-.01.01-.02.02-.03c.18-.28.44-.51.74-.66v-5.8l-6.25-3.2c-.39-.2-.57-.68-.38-1.07"/></g></svg>`
  },
  {
    id: "kmind-icon://builtin/knowledge/light-bulb",
    group: "knowledge",
    name: "light-bulb",
    label: "Idea",
    catalog: { "groupId": "knowledge", "groupLabel": "Knowledge", "order": 130, "surfaces": ["node-content"] },
    viewBox: "0 0 32 32",
    svg: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" width="100%" height="100%" aria-hidden="true" focusable="false"><g fill="none"><path fill="#9B9B9B" d="M17.651 22.27h-3.89c-.79 0-1.44.64-1.43 1.43v3.89c0 .79.64 1.43 1.43 1.43h.248a1.94 1.94 0 0 0 3.384 0h.258c.79 0 1.43-.64 1.43-1.43V23.7c0-.79-.64-1.43-1.43-1.43"/><path fill="#FCD53F" d="M18.161 23.13c.24 0 .43-.18.45-.41c.07-.86.44-2.95 2.46-5.19a8.66 8.66 0 0 0 3.29-6.31c.02-.24.03-.4.03-.5v-.1c-.06-4.78-3.93-8.62-8.7-8.62a8.69 8.69 0 0 0-8.69 8.6s-.01.24.03.64c.16 2.54 1.4 4.79 3.29 6.28c2.02 2.25 2.42 4.34 2.49 5.2c.02.23.21.41.45.41z"/><path fill="#FFB02E" d="M15.701 10.7c1.62 0 2.94 1.31 2.96 2.93v.08c0 .03 0 .07-.01.13c-.05.84-.46 1.63-1.12 2.15l-.07.05l-.06.06c-1.1 1.22-1.33 4.32-1.37 6.02h-.65c-.05-1.7-.29-4.8-1.39-6.02l-.06-.06l-.07-.05a2.96 2.96 0 0 1-1.12-2.17c0-.04-.01-.07-.01-.09v-.09c.03-1.62 1.36-2.94 2.97-2.94m0-1a3.96 3.96 0 0 0-2.45 7.07c1.2 1.34 1.14 6.36 1.14 6.36h2.64s-.08-5.02 1.13-6.35c.86-.68 1.43-1.71 1.5-2.88c.01-.11.01-.18.01-.23v-.04a3.97 3.97 0 0 0-3.97-3.93"/><path fill="#D3D3D3" d="M19.167 25.053a.5.5 0 1 0-.172-.986l-6.74 1.18a.5.5 0 1 0 .172.986zm-.05 2.15a.5.5 0 0 0-.172-.985l-6.65 1.17a.5.5 0 1 0 .173.984z"/><path fill="#FFF478" d="M13.791 5.44c-1.11 1.92-.55 4.32 1.25 5.35s4.15.32 5.26-1.6s.55-4.32-1.25-5.35s-4.15-.32-5.26 1.6"/></g></svg>`
  },
  {
    id: "kmind-icon://builtin/knowledge/magnifying-glass-tilted-left",
    group: "knowledge",
    name: "magnifying-glass-tilted-left",
    label: "Explore",
    catalog: { "groupId": "knowledge", "groupLabel": "Knowledge", "order": 130, "surfaces": ["node-content"] },
    viewBox: "0 0 32 32",
    svg: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" width="100%" height="100%" aria-hidden="true" focusable="false"><g fill="none"><path fill="#00A6ED" d="M3 13c0 5.523 4.477 10 10 10s10-4.477 10-10S18.523 3 13 3S3 7.477 3 13"/><path fill="#fff" d="M18.348 7.732c.552.957.419 2.068-.299 2.482c-.717.414-1.747-.025-2.299-.982s-.418-2.068.299-2.482c.718-.414 1.747.025 2.3.982"/><path fill="#533566" d="M2 13c0 6.075 4.925 11 11 11c2.295 0 4.426-.703 6.19-1.905a3.75 3.75 0 0 0 1.005 3.483l3.182 3.182a3.75 3.75 0 0 0 5.303-5.303l-3.182-3.182a3.75 3.75 0 0 0-3.454-1.012A10.95 10.95 0 0 0 24 13c0-6.075-4.925-11-11-11S2 6.925 2 13m20 0a9 9 0 1 1-18 0a9 9 0 0 1 18 0"/></g></svg>`
  },
  {
    id: "kmind-icon://builtin/knowledge/microscope",
    group: "knowledge",
    name: "microscope",
    label: "Research",
    catalog: { "groupId": "knowledge", "groupLabel": "Knowledge", "order": 130, "surfaces": ["node-content"] },
    viewBox: "0 0 32 32",
    svg: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" width="100%" height="100%" aria-hidden="true" focusable="false"><g fill="none"><path fill="#5092FF" d="M4.718 18.023a1.25 1.25 0 0 1 1.742-.305l12.072 8.476l-1.437 2.047l-12.072-8.476a1.25 1.25 0 0 1-.305-1.742"/><path fill="#636363" d="M18.501 2.803c.33-.443.96-.543 1.41-.223l1.673 1.191c.45.32.548.94.22 1.384L13.11 16.88a2.074 2.074 0 0 1-2.858.453a1.98 1.98 0 0 1-.444-2.804z"/><path fill="#BEBEBE" d="M18.047 3.666c-1.209-.352-2.667.195-3.45 1.251l-2.822 3.807L12 10l-1.398.306l-.203.275a3.95 3.95 0 0 0 .903 5.587c1.823 1.298 4.376.902 5.7-.885l.16-.215L17 13.5h1.324l.164-.221c3.504.651 5.38 3.572 5.475 6.576c.052 1.65-.442 3.276-1.482 4.535c-1.027 1.243-2.67 2.229-5.102 2.459c-.834.079-1.449.847-1.373 1.715s.814 1.509 1.648 1.43c3.129-.297 5.53-1.614 7.126-3.545c1.582-1.915 2.289-4.335 2.215-6.698c-.123-3.895-2.39-7.767-6.49-9.192l.696-.94c.783-1.056.863-2.584.148-3.602z"/><path fill="#9B9B9B" d="M2 29.2A3.2 3.2 0 0 1 5.2 26h21.6a3.2 3.2 0 0 1 3.2 3.2a.8.8 0 0 1-.8.8H2.8a.8.8 0 0 1-.8-.8"/><path fill="#D3D3D3" d="m11.776 8.71l6.558 4.765l-1.175 1.618l-6.559-4.765z"/></g></svg>`
  },
  {
    id: "kmind-icon://builtin/knowledge/open-book",
    group: "knowledge",
    name: "open-book",
    label: "Knowledge",
    catalog: { "groupId": "knowledge", "groupLabel": "Knowledge", "order": 130, "surfaces": ["node-content"] },
    viewBox: "0 0 32 32",
    svg: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" width="100%" height="100%" aria-hidden="true" focusable="false"><g fill="none"><path fill="#B4ACBC" fill-rule="evenodd" d="M16 8.05A3.5 3.5 0 0 1 18.5 7h8c.743 0 1.39.404 1.734 1.003c.07.121.096.26.096.4v2.294L29 25.5a2.5 2.5 0 0 1-2.5 2.5h-21A2.5 2.5 0 0 1 3 25.5l.67-14.803V8.403c0-.14.026-.279.096-.4A2 2 0 0 1 5.5 7h8c.98 0 1.865.402 2.5 1.05" clip-rule="evenodd"/><path fill="#0074BA" d="M17.732 30H28.5c.83 0 1.501-.678 1.501-1.505V27.44c0-.827-.67-2.441-1.501-2.441h-25C2.671 25 2 26.614 2 27.441v1.064C2 29.332 2.67 30 3.501 30h10.767a2 2 0 0 0 3.464 0"/><path fill="#00A6ED" fill-rule="evenodd" d="M3.501 10H14v1h4v-1h10.499c.83 0 1.501.668 1.501 1.495v16c0 .827-.67 1.505-1.501 1.505H17.732a2 2 0 0 1-3.464 0H3.5c-.829 0-1.5-.668-1.5-1.495v-16.01C2 10.668 2.67 10 3.501 10M17.5 27.5a1.5 1.5 0 1 1-3 0a1.5 1.5 0 0 1 3 0" clip-rule="evenodd"/><path fill="#B4ACBC" d="M13 8H5.803a1.5 1.5 0 0 0-1.248.668L3 11v14.5A1.5 1.5 0 0 0 4.5 27h23a1.5 1.5 0 0 0 1.5-1.5V11l-1.555-2.332A1.5 1.5 0 0 0 26.197 8H19v3h-6z"/><path fill="#F3EEF8" d="M5.5 8h8a2.5 2.5 0 0 1 2.5 2.5V27l-.447-.894A2 2 0 0 0 13.763 25H5.5a1 1 0 0 1-1-1V9a1 1 0 0 1 1-1m13 0h8a1 1 0 0 1 1 1v15a1 1 0 0 1-1 1h-8.264a2 2 0 0 0-1.736 1.007V9c.456-.607 1.182-1 2-1"/></g></svg>`
  },
  {
    id: "kmind-icon://builtin/pie-progress/pie-0",
    group: "pie-progress",
    name: "pie-0",
    label: "Pie 0%",
    catalog: { "groupId": "pie-progress", "groupLabel": "Pie Progress", "order": 115, "surfaces": ["node-content"] },
    viewBox: "0 0 32 32",
    svg: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" width="100%" height="100%" aria-hidden="true" focusable="false"><g fill="none"><circle cx="16" cy="16" r="12" fill="#E5E7EB"/><g fill="#22C55E"></g><circle cx="16" cy="16" r="12" fill="none" stroke="#475569" stroke-width="1.5"/></g></svg>`
  },
  {
    id: "kmind-icon://builtin/pie-progress/pie-100",
    group: "pie-progress",
    name: "pie-100",
    label: "Pie 100%",
    catalog: { "groupId": "pie-progress", "groupLabel": "Pie Progress", "order": 115, "surfaces": ["node-content"] },
    viewBox: "0 0 32 32",
    svg: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" width="100%" height="100%" aria-hidden="true" focusable="false"><g fill="none"><circle cx="16" cy="16" r="12" fill="#E5E7EB"/><g fill="#22C55E"><circle cx="16" cy="16" r="12" fill="#22C55E"/></g><circle cx="16" cy="16" r="12" fill="none" stroke="#475569" stroke-width="1.5"/></g></svg>`
  },
  {
    id: "kmind-icon://builtin/pie-progress/pie-25",
    group: "pie-progress",
    name: "pie-25",
    label: "Pie 25%",
    catalog: { "groupId": "pie-progress", "groupLabel": "Pie Progress", "order": 115, "surfaces": ["node-content"] },
    viewBox: "0 0 32 32",
    svg: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" width="100%" height="100%" aria-hidden="true" focusable="false"><g fill="none"><circle cx="16" cy="16" r="12" fill="#E5E7EB"/><g fill="#22C55E"><path fill="#22C55E" d="M 16 16 L 16 4 A 12 12 0 0 1 28.000 16.000 Z"/></g><circle cx="16" cy="16" r="12" fill="none" stroke="#475569" stroke-width="1.5"/></g></svg>`
  },
  {
    id: "kmind-icon://builtin/pie-progress/pie-50",
    group: "pie-progress",
    name: "pie-50",
    label: "Pie 50%",
    catalog: { "groupId": "pie-progress", "groupLabel": "Pie Progress", "order": 115, "surfaces": ["node-content"] },
    viewBox: "0 0 32 32",
    svg: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" width="100%" height="100%" aria-hidden="true" focusable="false"><g fill="none"><circle cx="16" cy="16" r="12" fill="#E5E7EB"/><g fill="#22C55E"><path fill="#22C55E" d="M 16 16 L 16 4 A 12 12 0 0 1 16.000 28.000 Z"/></g><circle cx="16" cy="16" r="12" fill="none" stroke="#475569" stroke-width="1.5"/></g></svg>`
  },
  {
    id: "kmind-icon://builtin/pie-progress/pie-75",
    group: "pie-progress",
    name: "pie-75",
    label: "Pie 75%",
    catalog: { "groupId": "pie-progress", "groupLabel": "Pie Progress", "order": 115, "surfaces": ["node-content"] },
    viewBox: "0 0 32 32",
    svg: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" width="100%" height="100%" aria-hidden="true" focusable="false"><g fill="none"><circle cx="16" cy="16" r="12" fill="#E5E7EB"/><g fill="#22C55E"><path fill="#22C55E" d="M 16 16 L 16 4 A 12 12 0 1 1 4.000 16.000 Z"/></g><circle cx="16" cy="16" r="12" fill="none" stroke="#475569" stroke-width="1.5"/></g></svg>`
  },
  {
    id: "kmind-icon://builtin/planning/calendar",
    group: "planning",
    name: "calendar",
    label: "Calendar",
    catalog: { "groupId": "planning", "groupLabel": "Planning", "order": 120, "surfaces": ["node-content"] },
    viewBox: "0 0 32 32",
    svg: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" width="100%" height="100%" aria-hidden="true" focusable="false"><g fill="none"><path fill="#B4ACBC" d="m2 9l13.267-2.843a3.5 3.5 0 0 1 1.466 0L30 9v15.8a5.2 5.2 0 0 1-5.2 5.2H7.2A5.2 5.2 0 0 1 2 24.8z"/><path fill="#F3EEF8" d="m3 8l12.213-2.818a3.5 3.5 0 0 1 1.574 0L29 8v16.5a4.5 4.5 0 0 1-4.5 4.5h-17A4.5 4.5 0 0 1 3 24.5z"/><path fill="#998EA4" d="M8 12a.2.2 0 0 0-.2.2v2.6c0 .11.09.2.2.2h2.8a.2.2 0 0 0 .2-.2v-2.6a.2.2 0 0 0-.2-.2zm0 5.5a.2.2 0 0 0-.2.2v2.6c0 .11.09.2.2.2h2.8a.2.2 0 0 0 .2-.2v-2.6a.2.2 0 0 0-.2-.2zm-.2 5.6c0-.11.09-.2.2-.2h2.8c.11 0 .2.09.2.2v2.6a.2.2 0 0 1-.2.2H8a.2.2 0 0 1-.2-.2zM14.6 12a.2.2 0 0 0-.2.2v2.6c0 .11.09.2.2.2h2.8a.2.2 0 0 0 .2-.2v-2.6a.2.2 0 0 0-.2-.2zm-.2 5.7c0-.11.09-.2.2-.2h2.8c.11 0 .2.09.2.2v2.6a.2.2 0 0 1-.2.2h-2.8a.2.2 0 0 1-.2-.2zm.2 5.2a.2.2 0 0 0-.2.2v2.6c0 .11.09.2.2.2h2.8a.2.2 0 0 0 .2-.2v-2.6a.2.2 0 0 0-.2-.2zM21 12.2c0-.11.09-.2.2-.2H24c.11 0 .2.09.2.2v2.6a.2.2 0 0 1-.2.2h-2.8a.2.2 0 0 1-.2-.2zm.2 10.7a.2.2 0 0 0-.2.2v2.6c0 .11.09.2.2.2H24a.2.2 0 0 0 .2-.2v-2.6a.2.2 0 0 0-.2-.2z"/><path fill="#0084CE" d="M7.2 2A5.2 5.2 0 0 0 2 7.2V9h28V7.2A5.2 5.2 0 0 0 24.8 2zm14 15.5a.2.2 0 0 0-.2.2v2.6c0 .11.09.2.2.2H24a.2.2 0 0 0 .2-.2v-2.6a.2.2 0 0 0-.2-.2z"/></g></svg>`
  },
  {
    id: "kmind-icon://builtin/planning/clipboard",
    group: "planning",
    name: "clipboard",
    label: "Checklist",
    catalog: { "groupId": "planning", "groupLabel": "Planning", "order": 120, "surfaces": ["node-content"] },
    viewBox: "0 0 32 32",
    svg: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" width="100%" height="100%" aria-hidden="true" focusable="false"><g fill="none"><path fill="#E19747" d="M5 4.5A1.5 1.5 0 0 1 6.5 3h19A1.5 1.5 0 0 1 27 4.5v24a1.5 1.5 0 0 1-1.5 1.5h-19A1.5 1.5 0 0 1 5 28.5z"/><path fill="#F3EEF8" d="M25 6a1 1 0 0 0-1-1H8a1 1 0 0 0-1 1v21a1 1 0 0 0 1 1h10.586c.147 0 .29-.032.421-.093l.321-.783l.632-4.086l4.457-.783l.49-.247a1 1 0 0 0 .093-.422z"/><path fill="#CDC4D6" d="M24.91 22H20a1 1 0 0 0-1 1v4.91a1 1 0 0 0 .293-.203l5.414-5.414A1 1 0 0 0 24.91 22"/><path fill="#9B9B9B" d="M18 4a2 2 0 1 0-4 0h-1a2 2 0 0 0-2 2v1.5a.5.5 0 0 0 .5.5h9a.5.5 0 0 0 .5-.5V6a2 2 0 0 0-2-2zm-1 0a1 1 0 1 1-2 0a1 1 0 0 1 2 0m-8 8.5a.5.5 0 0 1 .5-.5h13a.5.5 0 0 1 0 1h-13a.5.5 0 0 1-.5-.5m0 3a.5.5 0 0 1 .5-.5h13a.5.5 0 0 1 0 1h-13a.5.5 0 0 1-.5-.5m.5 2.5a.5.5 0 0 0 0 1h13a.5.5 0 0 0 0-1zM9 21.5a.5.5 0 0 1 .5-.5h8a.5.5 0 0 1 0 1h-8a.5.5 0 0 1-.5-.5"/></g></svg>`
  },
  {
    id: "kmind-icon://builtin/planning/memo",
    group: "planning",
    name: "memo",
    label: "Memo",
    catalog: { "groupId": "planning", "groupLabel": "Planning", "order": 120, "surfaces": ["node-content"] },
    viewBox: "0 0 32 32",
    svg: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" width="100%" height="100%" aria-hidden="true" focusable="false"><g fill="none"><path fill="#B4ACBC" d="M20.343 2.293A1 1 0 0 0 19.636 2H7a2 2 0 0 0-2 2v24a2 2 0 0 0 2 2h18a2 2 0 0 0 2-2V9.364a1 1 0 0 0-.293-.707z"/><path fill="#F3EEF8" d="M19.682 3H7a1 1 0 0 0-1 1v24a1 1 0 0 0 1 1h18a1 1 0 0 0 1-1V9.453z"/><path fill="#998EA4" d="M9.5 12h13a.5.5 0 0 1 0 1h-13a.5.5 0 0 1 0-1m0 3a.5.5 0 0 0 0 1h13a.5.5 0 0 0 0-1zM9 18.5a.5.5 0 0 1 .5-.5h13a.5.5 0 0 1 0 1h-13a.5.5 0 0 1-.5-.5m.5 2.5a.5.5 0 0 0 0 1h8a.5.5 0 0 0 0-1z"/><path fill="#CDC4D6" d="M26 9.453h-4.61a1.707 1.707 0 0 1-1.708-1.707V3z"/><path fill="#FF822D" d="m26.766 20.172l-1.08-3.231l-2.796-2.006l-10.607 7.849l1.148 3.156l2.727 2.082z"/><path fill="#FFCE7C" d="m11.106 26.655l.171.893l.836.468l4.039-.006l-3.86-5.216z"/><path fill="#402A32" d="m10.687 28.018l.418-1.363l1.007 1.36z"/><path fill="#F92F60" d="M26.52 12.249a2 2 0 0 1 2.798.418l1.496 2.022a2 2 0 0 1-.418 2.797l-2.058 1.524l-2.805-2.069l-1.071-3.17z"/><path fill="#D3D3D3" d="m24.462 13.772l3.876 5.238l-1.572 1.162l-3.875-5.237z"/></g></svg>`
  },
  {
    id: "kmind-icon://builtin/planning/pencil",
    group: "planning",
    name: "pencil",
    label: "Draft",
    catalog: { "groupId": "planning", "groupLabel": "Planning", "order": 120, "surfaces": ["node-content"] },
    viewBox: "0 0 32 32",
    svg: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" width="100%" height="100%" aria-hidden="true" focusable="false"><g fill="none"><path fill="#FF822D" d="m16.635 7.585l4.51 2.535l2.561 4.537L9.37 28.993l-4.862-2.57l-2.21-4.5z"/><path fill="#FFCE7C" d="m1.39 28.065l.582 1.312l1.255.525l6.13-.925l-7.042-7.042z"/><path fill="#402A32" d="m1.063 30.229l.326-2.164l1.838 1.837z"/><path fill="#F92F60" d="M22.276 1.944a2 2 0 0 1 2.829 0l4.242 4.243a2 2 0 0 1 0 2.828l-3.535 3.536l-4.527-2.264L18.74 5.48z"/><path fill="#D3D3D3" d="m18.74 5.48l7.072 7.071l-2.122 2.121l-7.07-7.07z"/></g></svg>`
  },
  {
    id: "kmind-icon://builtin/planning/pushpin",
    group: "planning",
    name: "pushpin",
    label: "Pinned",
    catalog: { "groupId": "planning", "groupLabel": "Planning", "order": 120, "surfaces": ["node-content"] },
    viewBox: "0 0 32 32",
    svg: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" width="100%" height="100%" aria-hidden="true" focusable="false"><g fill="none"><path fill="#D3D3D3" d="M2.383 29.495c-.51-.51-.51-1.33 0-1.84l8.96-8.96l1.84 1.84l-8.96 8.96c-.51.51-1.33.51-1.84 0"/><path fill="#CA0B4A" d="m20.033 19.174l4.603-4.603L23 8.5l-5.796-1.36l-4.603 4.602L14 17.5z"/><path fill="#F8312F" d="m17.183 7.125l7.47 7.46a2.607 2.607 0 0 0 3.69 0l1.11-1.11c.42-.42.42-1.1 0-1.52l-9.64-9.64c-.42-.42-1.1-.42-1.52 0l-1.11 1.11a2.62 2.62 0 0 0 0 3.7m-11.1 7.44l11.12 11.12c.52.52 1.37.52 1.89 0l.91-.91a3.983 3.983 0 0 0 0-5.64l-7.37-7.37a3.983 3.983 0 0 0-5.64 0l-.91.91a1.34 1.34 0 0 0 0 1.89"/></g></svg>`
  },
  {
    id: "kmind-icon://builtin/planning/spiral-calendar",
    group: "planning",
    name: "spiral-calendar",
    label: "Plan",
    catalog: { "groupId": "planning", "groupLabel": "Planning", "order": 120, "surfaces": ["node-content"] },
    viewBox: "0 0 32 32",
    svg: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" width="100%" height="100%" aria-hidden="true" focusable="false"><g fill="none"><path fill="#B4ACBC" d="m2 9l13.267-2.843a3.5 3.5 0 0 1 1.466 0L30 9v15.8a5.2 5.2 0 0 1-5.2 5.2H7.2A5.2 5.2 0 0 1 2 24.8z"/><path fill="#F3EEF8" d="M3 10.905V24.5A4.5 4.5 0 0 0 7.5 29h16l5.5-5.667V10.905L16 9z"/><path fill="#998EA4" d="M8.2 13a.2.2 0 0 0-.2.2v2.6c0 .11.09.2.2.2h2.6a.2.2 0 0 0 .2-.2v-2.6a.2.2 0 0 0-.2-.2zm6.5 0a.2.2 0 0 0-.2.2v2.6c0 .11.09.2.2.2h2.6a.2.2 0 0 0 .2-.2v-2.6a.2.2 0 0 0-.2-.2zm6.3.2c0-.11.09-.2.2-.2h2.6c.11 0 .2.09.2.2v2.6a.2.2 0 0 1-.2.2h-2.6a.2.2 0 0 1-.2-.2zM8.2 18a.2.2 0 0 0-.2.2v2.6c0 .11.09.2.2.2h2.6a.2.2 0 0 0 .2-.2v-2.6a.2.2 0 0 0-.2-.2zm6.3.2c0-.11.09-.2.2-.2h2.6c.11 0 .2.09.2.2v2.6a.2.2 0 0 1-.2.2h-2.6a.2.2 0 0 1-.2-.2zM8.2 23a.2.2 0 0 0-.2.2v2.6c0 .11.09.2.2.2h2.6a.2.2 0 0 0 .2-.2v-2.6a.2.2 0 0 0-.2-.2zm6.3.2c0-.11.09-.2.2-.2h2.6c.11 0 .2.09.2.2v2.6a.2.2 0 0 1-.2.2h-2.6a.2.2 0 0 1-.2-.2zm6.7-.2a.2.2 0 0 0-.2.2v2.6c0 .11.09.2.2.2h2.6a.2.2 0 0 0 .2-.2v-2.6a.2.2 0 0 0-.2-.2zm8.81 3.24V23l-4.51 2.5l-2.49 4.5h3.24c2.08 0 3.76-1.69 3.76-3.76"/><path fill="#E1D8EC" d="M23.01 26.76V30l7-7h-3.24c-2.07 0-3.76 1.69-3.76 3.76"/><path fill="#0084CE" d="M30 8.785V11H2V8.785C2 6.691 3.69 4.99 5.759 5h19.277l.728-.57l.772.582C28.468 5.162 30 6.792 30 8.785M21.2 18a.2.2 0 0 0-.2.2v2.6c0 .11.09.2.2.2h2.6a.2.2 0 0 0 .2-.2v-2.6a.2.2 0 0 0-.2-.2z"/><path fill="#CDC4D6" d="M11.52 5a1.77 1.77 0 0 0 1.11 1.92c.328.128.62.403.62.754c0 .477-.395.875-.855.748a3.27 3.27 0 0 1-2.381-3.456A1.77 1.77 0 1 0 7.63 6.92c.328.127.62.402.62.753c0 .477-.395.875-.855.748A3.271 3.271 0 0 1 8.27 2c1.003 0 1.9.451 2.5 1.162A3.26 3.26 0 0 1 13.27 2c1.003 0 1.9.451 2.5 1.162A3.26 3.26 0 0 1 18.27 2c1.003 0 1.9.451 2.5 1.162A3.27 3.27 0 0 1 26.529 5h-1.51a1.77 1.77 0 0 0-3.493-.034l.003.034h-.009a1.77 1.77 0 0 0 1.11 1.92c.328.128.62.403.62.754c0 .477-.395.875-.855.748a3.27 3.27 0 0 1-2.381-3.456a1.77 1.77 0 0 0-3.488 0l.003.034h-.009a1.77 1.77 0 0 0 1.11 1.92c.328.128.62.403.62.754c0 .477-.395.875-.855.748a3.27 3.27 0 0 1-2.381-3.456a1.77 1.77 0 0 0-3.488 0l.003.034z"/></g></svg>`
  },
  {
    id: "kmind-icon://builtin/progress/alarm-clock",
    group: "progress",
    name: "alarm-clock",
    label: "Deadline",
    catalog: { "groupId": "progress", "groupLabel": "Progress", "order": 110, "surfaces": ["node-content"] },
    viewBox: "0 0 32 32",
    svg: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" width="100%" height="100%" aria-hidden="true" focusable="false"><g fill="none"><path fill="#D3D3D3" d="M23.207 24.58C21 25.5 19.05 26 16.5 26c-2.788 0-4.5-.5-7.203-1.86l-2.586 2.237C5.317 27.588 6.11 30 7.905 30H24.09c1.796 0 2.599-2.412 1.194-3.623z"/><path fill="#F8312F" d="M16.5 27C22.299 27 27 22.299 27 16.5S22.299 6 16.5 6S6 10.701 6 16.5S10.701 27 16.5 27"/><path fill="#fff" d="M16.5 24a7.5 7.5 0 1 0 0-15a7.5 7.5 0 0 0 0 15"/><path fill="#F9C23C" d="M4.273 9.228c-.735-2.284.039-4.883 2.033-6.294s4.588-1.178 6.32.396c.542.497.484 1.4-.106 1.817l-6.601 4.66c-.6.416-1.414.132-1.646-.579m24.454 0c.735-2.284-.039-4.883-2.033-6.294s-4.588-1.178-6.32.396c-.542.497-.484 1.4.106 1.817l6.601 4.66c.6.416 1.414.132 1.646-.579"/><path fill="#F8312F" d="M15.168 16.445a1 1 0 0 1 1.387-.277l3 2a1 1 0 1 1-1.11 1.664l-3-2a1 1 0 0 1-.277-1.387"/><path fill="#212121" d="M16 11a1 1 0 0 1 1 1v5a1 1 0 1 1-2 0v-5a1 1 0 0 1 1-1"/></g></svg>`
  },
  {
    id: "kmind-icon://builtin/progress/check-mark-button",
    group: "progress",
    name: "check-mark-button",
    label: "Done",
    catalog: { "groupId": "progress", "groupLabel": "Progress", "order": 110, "surfaces": ["node-content"] },
    viewBox: "0 0 32 32",
    svg: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" width="100%" height="100%" aria-hidden="true" focusable="false"><g fill="none"><path fill="#00D26A" d="M2 6a4 4 0 0 1 4-4h20a4 4 0 0 1 4 4v20a4 4 0 0 1-4 4H6a4 4 0 0 1-4-4z"/><path fill="#F4F4F4" d="M13.242 23c-.383 0-.766-.143-1.059-.43l-5.744-5.642a1.453 1.453 0 0 1 0-2.08a1.517 1.517 0 0 1 2.118 0l4.685 4.601L23.443 9.431a1.517 1.517 0 0 1 2.118 0a1.45 1.45 0 0 1 0 2.08l-11.26 11.058a1.5 1.5 0 0 1-1.059.431"/></g></svg>`
  },
  {
    id: "kmind-icon://builtin/progress/cross-mark-button",
    group: "progress",
    name: "cross-mark-button",
    label: "Blocked",
    catalog: { "groupId": "progress", "groupLabel": "Progress", "order": 110, "surfaces": ["node-content"] },
    viewBox: "0 0 32 32",
    svg: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" width="100%" height="100%" aria-hidden="true" focusable="false"><g fill="none"><path fill="#00D26A" d="M2 6a4 4 0 0 1 4-4h20a4 4 0 0 1 4 4v20a4 4 0 0 1-4 4H6a4 4 0 0 1-4-4z"/><path fill="#fff" d="M21.564 8.314a1.5 1.5 0 0 1 2.122 2.122L18.12 16l5.565 5.564a1.5 1.5 0 0 1-2.122 2.122L16 18.12l-5.564 5.565a1.5 1.5 0 0 1-2.122-2.122L13.88 16l-5.565-5.564a1.5 1.5 0 0 1 2.122-2.122L16 13.88z"/></g></svg>`
  },
  {
    id: "kmind-icon://builtin/progress/hourglass-done",
    group: "progress",
    name: "hourglass-done",
    label: "Complete",
    catalog: { "groupId": "progress", "groupLabel": "Progress", "order": 110, "surfaces": ["node-content"] },
    viewBox: "0 0 32 32",
    svg: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" width="100%" height="100%" aria-hidden="true" focusable="false"><g fill="none"><path fill="#83CBFF" d="M25 6.4V3.9l-9-.4l-9 .4v2.5c0 4 2.8 7.3 6.5 8.2c.3.1.5.4.5.7v1.2c0 .3-.2.6-.5.6C9.8 18 7 21.3 7 25.3V28l9 1l9-1v-2.7c0-4-2.8-7.3-6.5-8.2c-.3-.1-.5-.3-.5-.6v-1.2c0-.3.2-.6.5-.6c3.7-1 6.5-4.3 6.5-8.3"/><path fill="#9B9B9B" d="M7 4h18c.6 0 1-.4 1-1s-.4-1-1-1H7c-.6 0-1 .4-1 1s.4 1 1 1m0 26h18c.6 0 1-.4 1-1s-.4-1-1-1H7c-.6 0-1 .4-1 1s.4 1 1 1"/><path fill="#FFB02E" d="M17 19.4v-4.3c0-.7.5-1.2 1.1-1.4c1.7-.4 3.2-1.4 4.3-2.7c.7-.8.1-2-.9-2h-11c-1 0-1.6 1.2-.9 2c1.1 1.3 2.6 2.2 4.3 2.7c.7.2 1.1.7 1.1 1.4V19c0 .7-.3 1-.6 1.1c-3.7.7-6.4 3.5-6.4 6.8V28h16v-1.1c0-3.3-2.7-6.1-6.4-6.8c-.3 0-.6-.3-.6-.7"/><path fill="#fff" d="M21.5 5.8c0-.5.4-.9.9-.9c.6.1 1 .5.9.9c-.1 1.6-.5 3-1.3 4.2c-.8 1.4-2 2.4-3.4 2.9c-.5.2-1 0-1.2-.5s0-1 .5-1.2c2.4-.9 3.4-3.5 3.6-5.4m0 20.1c0 .5.4.9.9.9c.6 0 1-.5.9-.9c-.1-1.6-.5-3-1.3-4.2c-.8-1.4-2-2.4-3.4-2.9c-.5-.2-1 0-1.2.5s0 1 .5 1.2c2.4.9 3.4 3.5 3.6 5.4"/></g></svg>`
  },
  {
    id: "kmind-icon://builtin/progress/hourglass-not-done",
    group: "progress",
    name: "hourglass-not-done",
    label: "Waiting",
    catalog: { "groupId": "progress", "groupLabel": "Progress", "order": 110, "surfaces": ["node-content"] },
    viewBox: "0 0 32 32",
    svg: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" width="100%" height="100%" aria-hidden="true" focusable="false"><g fill="none"><path fill="#83CBFF" d="m25 4l-9-1l-9 1v3.5c.19 2.484 1.823 6.52 7 7.348v2.304c-5.177.829-6.81 4.864-7 7.348V28l9 1l9-1v-3.5c-.19-2.484-1.823-6.52-7-7.348v-2.304c5.177-.829 6.81-4.864 7-7.348z"/><path fill="#FFB02E" d="M17 22.2v-7.4c0-.5.3-.9.8-1c3.2-.7 5.6-3.3 6.1-6.6c.1-.6-.4-1.2-1-1.2H9.1c-.6 0-1.1.6-1 1.2c.5 3.3 2.9 5.9 6.1 6.6c.5.1.8.5.8 1v7.4c0 .5-.3.9-.8 1c-1.9.4-3.5 1.5-4.6 3c-.6.8 0 1.8.9 1.8h11c.9 0 1.5-1 .9-1.7c-1.1-1.5-2.8-2.6-4.6-3c-.5-.2-.8-.6-.8-1.1"/><path fill="#D3D3D3" d="M7 2a1 1 0 0 0 0 2h18a1 1 0 1 0 0-2zm0 26a1 1 0 1 0 0 2h18a1 1 0 1 0 0-2z"/><path fill="#fff" d="M22.007 6.117c.14 1.193-.021 2.147-.4 2.86c-.37.696-.99 1.246-1.939 1.58a1 1 0 1 0 .664 1.886c1.376-.484 2.414-1.347 3.041-2.528c.618-1.164.794-2.551.62-4.032a1 1 0 1 0-1.986.234m-3.136 12.954a1 1 0 0 0-.742 1.857c1.151.46 2.117 1.079 2.79 1.887C21.58 23.605 22 24.628 22 26a1 1 0 1 0 2 0c0-1.828-.578-3.306-1.544-4.465c-.952-1.142-2.236-1.924-3.585-2.464"/></g></svg>`
  },
  {
    id: "kmind-icon://builtin/progress/warning",
    group: "progress",
    name: "warning",
    label: "Warning",
    catalog: { "groupId": "progress", "groupLabel": "Progress", "order": 110, "surfaces": ["node-content"] },
    viewBox: "0 0 32 32",
    svg: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" width="100%" height="100%" aria-hidden="true" focusable="false"><g fill="none"><path fill="#FFB02E" d="m14.839 5.668l-12.66 21.93c-.51.89.13 2.01 1.16 2.01h25.32c1.03 0 1.67-1.11 1.16-2.01l-12.66-21.93c-.52-.89-1.8-.89-2.32 0"/><path fill="#000" d="M14.599 21.498a1.4 1.4 0 1 0 2.8-.01v-9.16c0-.77-.62-1.4-1.4-1.4c-.77 0-1.4.62-1.4 1.4zm2.8 3.98a1.4 1.4 0 1 1-2.8 0a1.4 1.4 0 0 1 2.8 0"/></g></svg>`
  },
  {
    id: "kmind-icon://builtin/ui/back",
    group: "ui",
    name: "back",
    label: "Back",
    catalog: { "groupId": "ui", "groupLabel": "UI", "order": 300, "surfaces": ["external-link", "host-ui", "editor-ui"] },
    viewBox: "0 0 24 24",
    svg: `<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false" width="100%" height="100%"><path d="M15 6l-6 6 6 6" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>`
  },
  {
    id: "kmind-icon://builtin/ui/backlinks",
    group: "ui",
    name: "backlinks",
    label: "Backlinks",
    catalog: { "groupId": "ui", "groupLabel": "UI", "order": 300, "surfaces": ["external-link", "host-ui", "editor-ui"] },
    viewBox: "0 0 24 24",
    svg: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="100%" height="100%" aria-hidden="true" focusable="false"><path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="m4.929 12.707l7.778-7.778m0 0v4.95m0-4.95h-4.95m11.314 6.364l-7.778 7.778m0 0h4.95m-4.95 0v-4.95"/></svg>`
  },
  {
    id: "kmind-icon://builtin/ui/brush",
    group: "ui",
    name: "brush",
    label: "Brush",
    catalog: { "groupId": "ui", "groupLabel": "UI", "order": 300, "surfaces": ["external-link", "host-ui", "editor-ui"] },
    viewBox: "0 0 24 24",
    svg: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="100%" height="100%" aria-hidden="true" focusable="false"><path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.2" d="M6 12c-.87.739-4.053 2.566-4 3.901c.015.365.32.67.931 1.281l.972.972M12 18c-.739.87-2.566 4.053-3.901 4c-.365-.015-.67-.32-1.281-.931l-.972-.972m-1.943-1.943l2.392-2.392m-2.392 2.392l1.943 1.943m0 0l1.196-1.196m6.897-.42c-.32.343-.479.515-.694.519s-.386-.168-.73-.512l-7.003-7.003c-.344-.344-.516-.516-.512-.73c.004-.216.176-.375.519-.694c.232-.216.42-.368.624-.494c1.765-1.088 4.006-.058 5.79-1.068c2.057-1.164 3.862-3.313 5.566-5.24c.728-.823 1.093-1.235 1.607-1.258c.926-.043 2.935 1.972 2.893 2.894c-.023.514-.435.878-1.26 1.607c-1.925 1.703-4.074 3.508-5.238 5.564c-1.01 1.785.02 4.026-1.069 5.791a4 4 0 0 1-.493.624"/></svg>`
  },
  {
    id: "kmind-icon://builtin/ui/close",
    group: "ui",
    name: "close",
    label: "Close",
    catalog: { "groupId": "ui", "groupLabel": "UI", "order": 300, "surfaces": ["external-link", "host-ui", "editor-ui"] },
    viewBox: "0 0 24 24",
    svg: `<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false" width="100%" height="100%"><path d="M18 6L6 18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"/><path d="M6 6l12 12" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"/></svg>`
  },
  {
    id: "kmind-icon://builtin/ui/comments",
    group: "ui",
    name: "comments",
    label: "Comments",
    catalog: { "groupId": "ui", "groupLabel": "UI", "order": 300, "surfaces": ["external-link", "host-ui", "editor-ui"] },
    viewBox: "0 0 24 24",
    svg: `<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false" width="100%" height="100%"><path d="M4 5h16a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2H9l-5 3v-3H4a2 2 0 0 1-2-2V7a2 2 0 0 1 2-2z" fill="none" stroke="currentColor" stroke-width="2" stroke-linejoin="round"/></svg>`
  },
  {
    id: "kmind-icon://builtin/ui/delete",
    group: "ui",
    name: "delete",
    label: "Delete",
    catalog: { "groupId": "ui", "groupLabel": "UI", "order": 300, "surfaces": ["external-link", "host-ui", "editor-ui"] },
    viewBox: "0 0 24 24",
    svg: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="100%" height="100%" aria-hidden="true" focusable="false"><path fill="currentColor" d="M7.616 20q-.667 0-1.141-.475T6 18.386V6h-.5q-.213 0-.356-.144T5 5.499t.144-.356T5.5 5H9q0-.31.23-.54t.54-.23h4.46q.31 0 .54.23T15 5h3.5q.213 0 .356.144t.144.357t-.144.356T18.5 6H18v12.385q0 .666-.475 1.14t-1.14.475zM17 6H7v12.385q0 .269.173.442t.443.173h8.769q.269 0 .442-.173t.173-.442zm-6.692 11q.213 0 .357-.144t.143-.356v-8q0-.213-.144-.356T10.307 8t-.356.144t-.143.356v8q0 .213.144.356q.144.144.356.144m3.385 0q.213 0 .356-.144t.143-.356v-8q0-.213-.144-.356Q13.904 8 13.692 8q-.213 0-.357.144t-.143.356v8q0 .213.144.356t.357.144M7 6v13z"/></svg>`
  },
  {
    id: "kmind-icon://builtin/ui/drag",
    group: "ui",
    name: "drag",
    label: "Drag",
    catalog: { "groupId": "ui", "groupLabel": "UI", "order": 300, "surfaces": ["external-link", "host-ui", "editor-ui"] },
    viewBox: "0 0 24 24",
    svg: `<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false" width="100%" height="100%"><path d="M9 7h.01M9 12h.01M9 17h.01M15 7h.01M15 12h.01M15 17h.01" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" /></svg>`
  },
  {
    id: "kmind-icon://builtin/ui/enter-submap",
    group: "ui",
    name: "enter-submap",
    label: "Enter SubMap",
    catalog: { "groupId": "ui", "groupLabel": "UI", "order": 300, "surfaces": ["external-link", "host-ui", "editor-ui"] },
    viewBox: "0 0 24 24",
    svg: `<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false" width="100%" height="100%"><path d="M9 6l6 6-6 6" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>`
  },
  {
    id: "kmind-icon://builtin/ui/export",
    group: "ui",
    name: "export",
    label: "Export",
    catalog: { "groupId": "ui", "groupLabel": "UI", "order": 300, "surfaces": ["external-link", "host-ui", "editor-ui"] },
    viewBox: "0 0 24 24",
    svg: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="100%" height="100%" aria-hidden="true" focusable="false"><path fill="currentColor" d="M8.71 7.71L11 5.41V15a1 1 0 0 0 2 0V5.41l2.29 2.3a1 1 0 0 0 1.42 0a1 1 0 0 0 0-1.42l-4-4a1 1 0 0 0-.33-.21a1 1 0 0 0-.76 0a1 1 0 0 0-.33.21l-4 4a1 1 0 1 0 1.42 1.42M21 14a1 1 0 0 0-1 1v4a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1v-4a1 1 0 0 0-2 0v4a3 3 0 0 0 3 3h14a3 3 0 0 0 3-3v-4a1 1 0 0 0-1-1"/></svg>`
  },
  {
    id: "kmind-icon://builtin/ui/fit",
    group: "ui",
    name: "fit",
    label: "Fit View",
    catalog: { "groupId": "ui", "groupLabel": "UI", "order": 300, "surfaces": ["external-link", "host-ui", "editor-ui"] },
    viewBox: "0 0 24 24",
    svg: `<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false" width="100%" height="100%"><path d="M9 4H4v5" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/><path d="M15 4h5v5" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/><path d="M4 15v5h5" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/><path d="M15 20h5v-5" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>`
  },
  {
    id: "kmind-icon://builtin/ui/help",
    group: "ui",
    name: "help",
    label: "About",
    catalog: { "groupId": "ui", "groupLabel": "UI", "order": 300, "surfaces": ["external-link", "host-ui", "editor-ui"] },
    viewBox: "0 0 24 24",
    svg: `<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false" width="100%" height="100%"><circle cx="12" cy="12" r="9" fill="none" stroke="currentColor" stroke-width="2"/><path d="M9.6 9.2a2.4 2.4 0 1 1 4.6 1c-.4.7-.8 1-1.6 1.6-.9.7-1.4 1.3-1.4 2.4" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/><circle cx="12" cy="17.2" r="1.2" fill="currentColor"/></svg>`
  },
  {
    id: "kmind-icon://builtin/ui/history",
    group: "ui",
    name: "history",
    label: "History",
    catalog: { "groupId": "ui", "groupLabel": "UI", "order": 300, "surfaces": ["external-link", "host-ui", "editor-ui"] },
    viewBox: "0 0 24 24",
    svg: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="100%" height="100%" aria-hidden="true" focusable="false"><path fill="currentColor" d="M13 3a9 9 0 1 0 8.94 10h-2.02a7 7 0 1 1-6.92-8v3l4-4l-4-4v3ZM12 8v5l4.28 2.54l.72-1.21l-3.5-2.08V8H12Z"/></svg>`
  },
  {
    id: "kmind-icon://builtin/ui/icons",
    group: "ui",
    name: "icons",
    label: "Icons",
    catalog: { "groupId": "ui", "groupLabel": "UI", "order": 300, "surfaces": ["external-link", "host-ui", "editor-ui"] },
    viewBox: "0 0 24 24",
    svg: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="100%" height="100%" aria-hidden="true" focusable="false"><g fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.2"><path d="M9 15c.85.63 1.885 1 3 1s2.15-.37 3-1m-5.5-4.5V10m5 .5V10"/><path d="M21 12a9 9 0 1 1-18 0a9 9 0 0 1 18 0"/></g></svg>`
  },
  {
    id: "kmind-icon://builtin/ui/image",
    group: "ui",
    name: "image",
    label: "Image",
    catalog: { "groupId": "ui", "groupLabel": "UI", "order": 300, "surfaces": ["external-link", "host-ui", "editor-ui"] },
    viewBox: "0 0 24 24",
    svg: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="100%" height="100%" aria-hidden="true" focusable="false"><path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M6.5 4.5h11A3 3 0 0 1 20.5 7.5v9a3 3 0 0 1-3 3h-11a3 3 0 0 1-3-3v-9a3 3 0 0 1 3-3Z"/><path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M6.5 15.5l3-3 3 3 3-3 2 2"/><path fill="none" stroke="currentColor" stroke-width="1.5" d="M9 9.25a1.25 1.25 0 1 0 2.5 0a1.25 1.25 0 0 0-2.5 0Z"/></svg>`
  },
  {
    id: "kmind-icon://builtin/ui/import",
    group: "ui",
    name: "import",
    label: "Import",
    catalog: { "groupId": "ui", "groupLabel": "UI", "order": 300, "surfaces": ["external-link", "host-ui", "editor-ui"] },
    viewBox: "0 0 24 24",
    svg: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="100%" height="100%" aria-hidden="true" focusable="false"><path fill="currentColor" d="M21 14a1 1 0 0 0-1 1v4a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1v-4a1 1 0 0 0-2 0v4a3 3 0 0 0 3 3h14a3 3 0 0 0 3-3v-4a1 1 0 0 0-1-1m-9.71 1.71a1 1 0 0 0 .33.21a.94.94 0 0 0 .76 0a1 1 0 0 0 .33-.21l4-4a1 1 0 0 0-1.42-1.42L13 12.59V3a1 1 0 0 0-2 0v9.59l-2.29-2.3a1 1 0 1 0-1.42 1.42Z"/></svg>`
  },
  {
    id: "kmind-icon://builtin/ui/keyboard",
    group: "ui",
    name: "keyboard",
    label: "Shortcuts",
    catalog: { "groupId": "ui", "groupLabel": "UI", "order": 300, "surfaces": ["external-link", "host-ui", "editor-ui"] },
    viewBox: "0 0 24 24",
    svg: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="100%" height="100%" aria-hidden="true" focusable="false"><path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M2 11c0-2.828 0-4.243.879-5.121C3.757 5 5.172 5 8 5h8c2.828 0 4.243 0 5.121.879C22 6.757 22 8.172 22 11v2c0 2.828 0 4.243-.879 5.121C20.243 19 18.828 19 16 19H8c-2.828 0-4.243 0-5.121-.879C2 17.243 2 15.828 2 13zm5 5h10M5 9h3m3 0h3m3 0h2M5 12h2m3 0h3m3 0h3"/></svg>`
  },
  {
    id: "kmind-icon://builtin/ui/link",
    group: "ui",
    name: "link",
    label: "Link",
    catalog: { "groupId": "ui", "groupLabel": "UI", "order": 300, "surfaces": ["external-link", "host-ui", "editor-ui"] },
    viewBox: "0 0 24 24",
    svg: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="100%" height="100%" aria-hidden="true" focusable="false"><path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M21 3h-6.75M21 3v6.75M21 3l-8.25 8.25M9.4 3c-2.24 0-3.36 0-4.216.436a4 4 0 0 0-1.748 1.748C3 6.04 3 7.16 3 9.4v5.2c0 2.24 0 3.36.436 4.216a4 4 0 0 0 1.748 1.748C6.04 21 7.16 21 9.4 21h5.2c2.24 0 3.36 0 4.216-.436a4 4 0 0 0 1.748-1.748C21 17.96 21 16.84 21 14.6v-1.1"/></svg>`
  },
  {
    id: "kmind-icon://builtin/ui/minimap",
    group: "ui",
    name: "minimap",
    label: "Minimap",
    catalog: { "groupId": "ui", "groupLabel": "UI", "order": 300, "surfaces": ["external-link", "host-ui", "editor-ui"] },
    viewBox: "0 0 24 24",
    svg: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="100%" height="100%" aria-hidden="true" focusable="false"><path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M3 8.593c0-1.527 0-2.29.393-2.735c.139-.159.308-.285.497-.372c1.416-.653 3.272 1.066 4.77 1.013q.297-.011.587-.082c2.184-.535 3.552-3.08 5.798-3.39c1.287-.18 2.7.598 3.904 1.014c.99.342 1.485.513 1.768.92S21 5.91 21 6.99v8.422c0 1.526 0 2.29-.393 2.735a1.5 1.5 0 0 1-.497.371c-1.416.653-3.272-1.065-4.77-1.012a3 3 0 0 0-.587.081c-2.184.535-3.552 3.08-5.798 3.391c-1.281.178-4.847-.75-5.672-1.935C3 18.636 3 18.096 3 17.014zm6-2.052v14.255m6-17.615v14.255"/></svg>`
  },
  {
    id: "kmind-icon://builtin/ui/new",
    group: "ui",
    name: "new",
    label: "New",
    catalog: { "groupId": "ui", "groupLabel": "UI", "order": 300, "surfaces": ["external-link", "host-ui", "editor-ui"] },
    viewBox: "0 0 24 24",
    svg: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="100%" height="100%" aria-hidden="true" focusable="false"><path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M3 9v10.4c0 .56 0 .84.109 1.054a1 1 0 0 0 .437.437C3.76 21 4.04 21 4.598 21H15m-1-8v-3m0 0V7m0 3h-3m3 0h3M7 13.8V6.2c0-1.12 0-1.68.218-2.108c.192-.377.497-.682.874-.874C8.52 3 9.08 3 10.2 3h7.6c1.12 0 1.68 0 2.108.218a2 2 0 0 1 .874.874C21 4.52 21 5.08 21 6.2v7.6c0 1.12 0 1.68-.218 2.108a2 2 0 0 1-.874.874c-.428.218-.986.218-2.104.218h-7.607c-1.118 0-1.678 0-2.105-.218a2 2 0 0 1-.874-.874C7 15.48 7 14.92 7 13.8"/></svg>`
  },
  {
    id: "kmind-icon://builtin/ui/notes",
    group: "ui",
    name: "notes",
    label: "Notes",
    catalog: { "groupId": "ui", "groupLabel": "UI", "order": 300, "surfaces": ["external-link", "host-ui", "editor-ui"] },
    viewBox: "0 0 24 24",
    svg: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="100%" height="100%" aria-hidden="true" focusable="false"><path fill="currentColor" d="M4 4a2 2 0 0 1 2-2h8a1 1 0 0 1 .707.293l5 5A1 1 0 0 1 20 8v12a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2zm13.586 4L14 4.414V8zM12 4H6v16h12V10h-5a1 1 0 0 1-1-1zm-4 9a1 1 0 0 1 1-1h6a1 1 0 1 1 0 2H9a1 1 0 0 1-1-1m0 4a1 1 0 0 1 1-1h6a1 1 0 1 1 0 2H9a1 1 0 0 1-1-1"/></svg>`
  },
  {
    id: "kmind-icon://builtin/ui/open",
    group: "ui",
    name: "open",
    label: "Open",
    catalog: { "groupId": "ui", "groupLabel": "UI", "order": 300, "surfaces": ["external-link", "host-ui", "editor-ui"] },
    viewBox: "0 0 24 24",
    svg: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="100%" height="100%" aria-hidden="true" focusable="false"><g fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.75"><path d="M9 7.5H7.75A2.75 2.75 0 0 0 5 10.25v6A2.75 2.75 0 0 0 7.75 19h6A2.75 2.75 0 0 0 16.5 16.25V15" opacity="0.5" /><path d="M10 14 19 5" /><path d="M13.5 5H19v5.5" /></g></svg>`
  },
  {
    id: "kmind-icon://builtin/ui/open-bottom",
    group: "ui",
    name: "open-bottom",
    label: "Open Bottom",
    catalog: { "groupId": "ui", "groupLabel": "UI", "order": 300, "surfaces": ["external-link", "host-ui", "editor-ui"] },
    viewBox: "0 0 24 24",
    svg: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="100%" height="100%" aria-hidden="true" focusable="false"><g fill="none" stroke="currentColor" stroke-width="1.5" transform="rotate(90 12 12)"><path d="M12 21h1c3.771 0 5.657 0 6.828-1.172S21 16.771 21 13v-2c0-3.771 0-5.657-1.172-6.828S16.771 3 13 3h-1" /><path d="M13 21H9c-2.828 0-4.243 0-5.121-.879C3 19.243 3 17.828 3 15V9c0-2.828 0-4.243.879-5.121C4.757 3 6.172 3 9 3h4" opacity="0.5" stroke-dasharray="2.5 3" stroke-linecap="round" /><path d="M12 22V2" stroke-linecap="round" /></g></svg>`
  },
  {
    id: "kmind-icon://builtin/ui/open-right",
    group: "ui",
    name: "open-right",
    label: "Open Right",
    catalog: { "groupId": "ui", "groupLabel": "UI", "order": 300, "surfaces": ["external-link", "host-ui", "editor-ui"] },
    viewBox: "0 0 24 24",
    svg: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="100%" height="100%" aria-hidden="true" focusable="false"><g fill="none" stroke="currentColor" stroke-width="1.5"><path d="M12 21h1c3.771 0 5.657 0 6.828-1.172S21 16.771 21 13v-2c0-3.771 0-5.657-1.172-6.828S16.771 3 13 3h-1"/><path stroke-dasharray="2.5 3" stroke-linecap="round" d="M13 21H9c-2.828 0-4.243 0-5.121-.879C3 19.243 3 17.828 3 15V9c0-2.828 0-4.243.879-5.121C4.757 3 6.172 3 9 3h4" opacity="0.5"/><path stroke-linecap="round" d="M12 22V2"/></g></svg>`
  },
  {
    id: "kmind-icon://builtin/ui/pdf",
    group: "ui",
    name: "pdf",
    label: "PDF",
    catalog: { "groupId": "ui", "groupLabel": "UI", "order": 300, "surfaces": ["external-link", "host-ui", "editor-ui"] },
    viewBox: "0 0 16 16",
    svg: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="100%" height="100%" aria-hidden="true" focusable="false"><path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" d="M2.8 14.34c1.81-1.25 3.02-3.16 3.91-5.5.9-2.33 1.86-4.33 1.44-6.63-.06-.36-.57-.73-.83-.7-1.02.06-.95 1.21-.85 1.9.24 1.71 1.56 3.7 2.84 5.56 1.27 1.87 2.32 2.16 3.78 2.26.5.03 1.25-.14 1.37-.58.77-2.8-9.02-.54-12.28 2.08-.4.33-.86 1-.6 1.46.2.36.87.4 1.23.15Z"/></svg>`
  },
  {
    id: "kmind-icon://builtin/ui/preview",
    group: "ui",
    name: "preview",
    label: "Preview",
    catalog: { "groupId": "ui", "groupLabel": "UI", "order": 300, "surfaces": ["external-link", "host-ui", "editor-ui"] },
    viewBox: "0 0 24 24",
    svg: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="100%" height="100%" aria-hidden="true" focusable="false"><g fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.75"><path d="M2.75 12s3.3-5.5 9.25-5.5 9.25 5.5 9.25 5.5-3.3 5.5-9.25 5.5S2.75 12 2.75 12Z" /><circle cx="12" cy="12" r="2.75" /></g></svg>`
  },
  {
    id: "kmind-icon://builtin/ui/project",
    group: "ui",
    name: "project",
    label: "Project",
    catalog: { "groupId": "ui", "groupLabel": "UI", "order": 300, "surfaces": ["external-link", "host-ui", "editor-ui"] },
    viewBox: "0 0 24 24",
    svg: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="100%" height="100%" aria-hidden="true" focusable="false"><path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="1" d="M12 18.5L9 17l-6 3V7l6-3l6 3l6-3v8M9 4v13m6-10v6.5m2.001 5.5a2 2 0 1 0 4 0a2 2 0 1 0-4 0m2-3.5V17m0 4v1.5m3.031-5.25l-1.299.75m-3.463 2l-1.3.75m0-3.5l1.3.75m3.463 2l1.3.75"/></svg>`
  },
  {
    id: "kmind-icon://builtin/ui/projects",
    group: "ui",
    name: "projects",
    label: "Projects",
    catalog: { "groupId": "ui", "groupLabel": "UI", "order": 300, "surfaces": ["external-link", "host-ui", "editor-ui"] },
    viewBox: "0 0 24 24",
    svg: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="100%" height="100%" aria-hidden="true" focusable="false"><path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M19 7h-7.34a2 2 0 0 1-1.322-.5l-2.272-2M19 7a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h1.745a2 2 0 0 1 1.322.5M19 7a2.5 2.5 0 0 0-2.5-2.5H8.066"/></svg>`
  },
  {
    id: "kmind-icon://builtin/ui/read-only",
    group: "ui",
    name: "read-only",
    label: "Read-only",
    catalog: { "groupId": "ui", "groupLabel": "UI", "order": 300, "surfaces": ["external-link", "host-ui", "editor-ui"] },
    viewBox: "0 0 24 24",
    svg: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="100%" height="100%" aria-hidden="true" focusable="false"><path fill="currentColor" d="M16 8a3 3 0 0 1 3 3v8a3 3 0 0 1-3 3H7a3 3 0 0 1-3-3v-8a3 3 0 0 1 3-3V6.5C7 4 9 2 11.5 2S16 4 16 6.5zM7 9a2 2 0 0 0-2 2v8a2 2 0 0 0 2 2h9a2 2 0 0 0 2-2v-8a2 2 0 0 0-2-2zm8-1V6.5A3.5 3.5 0 0 0 11.5 3A3.5 3.5 0 0 0 8 6.5V8zm-3.5 6a1.5 1.5 0 0 0-1.5 1.5a1.5 1.5 0 0 0 1.5 1.5a1.5 1.5 0 0 0 1.5-1.5a1.5 1.5 0 0 0-1.5-1.5m0-1a2.5 2.5 0 0 1 2.5 2.5a2.5 2.5 0 0 1-2.5 2.5A2.5 2.5 0 0 1 9 15.5a2.5 2.5 0 0 1 2.5-2.5"/></svg>`
  },
  {
    id: "kmind-icon://builtin/ui/redo",
    group: "ui",
    name: "redo",
    label: "Redo",
    catalog: { "groupId": "ui", "groupLabel": "UI", "order": 300, "surfaces": ["external-link", "host-ui", "editor-ui"] },
    viewBox: "0 0 24 24",
    svg: `<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false" width="100%" height="100%"><path d="M15 6l4 4-4 4" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/><path d="M19 10h-8a5 5 0 1 0 0 10h4" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>`
  },
  {
    id: "kmind-icon://builtin/ui/relation",
    group: "ui",
    name: "relation",
    label: "Relation",
    catalog: { "groupId": "ui", "groupLabel": "UI", "order": 300, "surfaces": ["external-link", "host-ui", "editor-ui"] },
    viewBox: "0 0 24 24",
    svg: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="100%" height="100%" aria-hidden="true" focusable="false"><path fill="currentColor" d="M13 8v8a3 3 0 0 1-3 3H7.83a3.001 3.001 0 1 1 0-2H10a1 1 0 0 0 1-1V8a3 3 0 0 1 3-3h3V2l5 4l-5 4V7h-3a1 1 0 0 0-1 1M5 19a1 1 0 1 0 0-2a1 1 0 0 0 0 2"/></svg>`
  },
  {
    id: "kmind-icon://builtin/ui/search",
    group: "ui",
    name: "search",
    label: "Search",
    catalog: { "groupId": "ui", "groupLabel": "UI", "order": 300, "surfaces": ["external-link", "host-ui", "editor-ui"] },
    viewBox: "0 0 24 24",
    svg: `<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false" width="100%" height="100%"><circle cx="11" cy="11" r="7" fill="none" stroke="currentColor" stroke-width="2"/><path d="M16.5 16.5L20 20" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"/></svg>`
  },
  {
    id: "kmind-icon://builtin/ui/style",
    group: "ui",
    name: "style",
    label: "Style",
    catalog: { "groupId": "ui", "groupLabel": "UI", "order": 300, "surfaces": ["external-link", "host-ui", "editor-ui"] },
    viewBox: "0 0 24 24",
    svg: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="100%" height="100%" aria-hidden="true" focusable="false"><path fill="currentColor" d="M20.063 8.445a3.22 3.22 0 0 1-.002 4.551l-7.123 7.112a2.25 2.25 0 0 1-.943.562l-4.293 1.29a1 1 0 0 1-1.24-1.264l1.362-4.228c.11-.34.3-.65.552-.903l7.133-7.121a3.22 3.22 0 0 1 4.554.002m-3.494 1.06l-7.133 7.12a.75.75 0 0 0-.184.301l-1.07 3.323l3.382-1.015a.75.75 0 0 0 .314-.188L19 11.936a1.718 1.718 0 1 0-2.431-2.432M8.15 2.37l.05.105l3.253 8.249l-1.157 1.155L9.556 10H5.443l-.995 2.52a.75.75 0 0 1-.876.454l-.098-.031a.75.75 0 0 1-.452-.876l.03-.098l3.754-9.495a.75.75 0 0 1 1.345-.104m-.648 2.422L6.036 8.5h2.928z"/></svg>`
  },
  {
    id: "kmind-icon://builtin/ui/submap",
    group: "ui",
    name: "submap",
    label: "SubMap",
    catalog: { "groupId": "ui", "groupLabel": "UI", "order": 300, "surfaces": ["external-link", "host-ui", "editor-ui"] },
    viewBox: "0 0 24 24",
    svg: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="100%" height="100%" aria-hidden="true" focusable="false"><path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.2" d="m11 19l-1.106-.552a2 2 0 0 0-1.788 0l-3.659 1.83A1 1 0 0 1 3 19.381V6.618a1 1 0 0 1 .553-.894l4.553-2.277a2 2 0 0 1 1.788 0l4.212 2.106a2 2 0 0 0 1.788 0l3.659-1.83A1 1 0 0 1 21 4.619V12m-6-6.236V12m3 3v6m3-3h-6M9 3.236v15"/></svg>`
  },
  {
    id: "kmind-icon://builtin/ui/summary",
    group: "ui",
    name: "summary",
    label: "Summary",
    catalog: { "groupId": "ui", "groupLabel": "UI", "order": 300, "surfaces": ["external-link", "host-ui", "editor-ui"] },
    viewBox: "0 0 24 24",
    svg: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="100%" height="100%" aria-hidden="true" focusable="false"><path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.2" d="M9 20.25a3 3 0 0 1-3-3v0v-1.343a4 4 0 0 0-1.172-2.829L3.75 12l1.078-1.078A4 4 0 0 0 6 8.093V6.75v0a3 3 0 0 1 3-3v0m6 16.5a3 3 0 0 0 3-3v0v-1.343a4 4 0 0 1 1.172-2.829L20.25 12l-1.078-1.078A4 4 0 0 1 18 8.093V6.75v0a3 3 0 0 0-3-3v0"/></svg>`
  },
  {
    id: "kmind-icon://builtin/ui/switch-card",
    group: "ui",
    name: "switch-card",
    label: "Switch To Card",
    catalog: { "groupId": "ui", "groupLabel": "UI", "order": 300, "surfaces": ["external-link", "host-ui", "editor-ui"] },
    viewBox: "0 0 24 24",
    svg: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="100%" height="100%" aria-hidden="true" focusable="false"><g fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.75"><rect x="4.5" y="5.5" width="15" height="13" rx="2.5" /><path d="M4.5 9.5h15" /><path d="M8 13.25h8" opacity="0.7" /><path d="M8 16h4.5" opacity="0.7" /></g></svg>`
  },
  {
    id: "kmind-icon://builtin/ui/switch-live",
    group: "ui",
    name: "switch-live",
    label: "Switch To Live",
    catalog: { "groupId": "ui", "groupLabel": "UI", "order": 300, "surfaces": ["external-link", "host-ui", "editor-ui"] },
    viewBox: "0 0 24 24",
    svg: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="100%" height="100%" aria-hidden="true" focusable="false"><g fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.75"><path d="M8 4H4v4M16 4h4v4M4 16v4h4M20 16v4h-4" /><circle cx="12" cy="12" r="2.25" /></g></svg>`
  },
  {
    id: "kmind-icon://builtin/ui/tags",
    group: "ui",
    name: "tags",
    label: "Tags",
    catalog: { "groupId": "ui", "groupLabel": "UI", "order": 300, "surfaces": ["external-link", "host-ui", "editor-ui"] },
    viewBox: "0 0 24 24",
    svg: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="100%" height="100%" aria-hidden="true" focusable="false"><path fill="currentColor" fill-rule="evenodd" d="M3.207 14.207a1 1 0 0 1 0-1.414l9.5-9.5A1 1 0 0 1 13.414 3H20a1 1 0 0 1 1 1v6.586a1 1 0 0 1-.293.707l-9.5 9.5a1 1 0 0 1-1.414 0zM19.8 10.503V4.2h-6.303l-9.3 9.3l6.303 6.303zM16 9.5a1.5 1.5 0 1 1 0-3a1.5 1.5 0 0 1 0 3"/></svg>`
  },
  {
    id: "kmind-icon://builtin/ui/theme",
    group: "ui",
    name: "theme",
    label: "Theme",
    catalog: { "groupId": "ui", "groupLabel": "UI", "order": 300, "surfaces": ["external-link", "host-ui", "editor-ui"] },
    viewBox: "0 0 24 24",
    svg: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="100%" height="100%" aria-hidden="true" focusable="false"><path fill="currentColor" d="M11 13.5v8H3v-8zm-2 2H5v4h4zM12 2l5.5 9h-11zm0 3.86L10.08 9h3.84zM17.5 13c2.5 0 4.5 2 4.5 4.5S20 22 17.5 22S13 20 13 17.5s2-4.5 4.5-4.5m0 2a2.5 2.5 0 0 0-2.5 2.5a2.5 2.5 0 0 0 2.5 2.5a2.5 2.5 0 0 0 2.5-2.5a2.5 2.5 0 0 0-2.5-2.5"/></svg>`
  },
  {
    id: "kmind-icon://builtin/ui/unbind",
    group: "ui",
    name: "unbind",
    label: "Unbind",
    catalog: { "groupId": "ui", "groupLabel": "UI", "order": 300, "surfaces": ["external-link", "host-ui", "editor-ui"] },
    viewBox: "0 0 24 24",
    svg: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="100%" height="100%" aria-hidden="true" focusable="false"><path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M16 20v-2m2-2h2M7.05 11.293l-1.414 1.414a4 4 0 0 0 5.657 5.657l1.415-1.414M6 8H4m4-4v2m3.293 1.05l1.414-1.414a4 4 0 1 1 5.656 5.657l-1.414 1.414" /></svg>`
  },
  {
    id: "kmind-icon://builtin/ui/undo",
    group: "ui",
    name: "undo",
    label: "Undo",
    catalog: { "groupId": "ui", "groupLabel": "UI", "order": 300, "surfaces": ["external-link", "host-ui", "editor-ui"] },
    viewBox: "0 0 24 24",
    svg: `<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false" width="100%" height="100%"><path d="M9 14L5 10l4-4" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/><path d="M5 10h8a5 5 0 1 1 0 10H9" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>`
  },
  {
    id: "kmind-icon://builtin/ui/zen",
    group: "ui",
    name: "zen",
    label: "Zen",
    catalog: { "groupId": "ui", "groupLabel": "UI", "order": 300, "surfaces": ["external-link", "host-ui", "editor-ui"] },
    viewBox: "0 0 24 24",
    svg: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="100%" height="100%" aria-hidden="true" focusable="false"><path fill="currentColor" d="M12 13.5q.214 0 .357-.144T12.5 13V8q0-.213-.144-.356t-.357-.144t-.356.144T11.5 8v5q0 .213.144.356t.357.144m3-1.5q.213 0 .356-.144t.143-.356V9q0-.213-.144-.356t-.357-.144t-.356.144T14.5 9v2.5q0 .213.144.356t.357.144m-6-.5q.213 0 .356-.144T9.5 11V9q0-.213-.144-.356T8.999 8.5t-.356.144T8.5 9v2q0 .213.144.356t.357.144M7 17.238q-1.425-1.3-2.212-2.922T4 10.986q0-3.327 2.333-5.657T12 3q2.702 0 4.884 1.645t2.83 4.25l1.036 4.103q.1.38-.142.692q-.242.31-.646.31H18v3.385q0 .666-.475 1.14t-1.14.475H14v1.5q0 .213-.144.356t-.357.144t-.356-.144T13 20.5v-1.683q0-.357.232-.587t.576-.23h2.577q.269 0 .442-.173t.173-.442v-3.577q0-.344.232-.576t.576-.232H19.7l-.95-3.875q-.575-2.294-2.47-3.71Q14.388 4 12 4Q9.1 4 7.05 6.03Q5 8.062 5 10.97q0 1.494.613 2.84q.612 1.346 1.737 2.392L8 16.8v3.7q0 .213-.144.356T7.499 21t-.356-.144T7 20.5zm5.35-4.738"/></svg>`
  },
  {
    id: "kmind-icon://builtin/ui/zoom-in",
    group: "ui",
    name: "zoom-in",
    label: "Zoom In",
    catalog: { "groupId": "ui", "groupLabel": "UI", "order": 300, "surfaces": ["external-link", "host-ui", "editor-ui"] },
    viewBox: "0 0 24 24",
    svg: `<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false" width="100%" height="100%"><circle cx="11" cy="11" r="7" fill="none" stroke="currentColor" stroke-width="2"/><path d="M16.5 16.5L20 20" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"/><path d="M11 8v6M8 11h6" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"/></svg>`
  },
  {
    id: "kmind-icon://builtin/ui/zoom-out",
    group: "ui",
    name: "zoom-out",
    label: "Zoom Out",
    catalog: { "groupId": "ui", "groupLabel": "UI", "order": 300, "surfaces": ["external-link", "host-ui", "editor-ui"] },
    viewBox: "0 0 24 24",
    svg: `<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false" width="100%" height="100%"><circle cx="11" cy="11" r="7" fill="none" stroke="currentColor" stroke-width="2"/><path d="M16.5 16.5L20 20" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"/><path d="M8 11h6" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"/></svg>`
  }
];

// ../icons/src/index.ts
var ICON_BY_ID = /* @__PURE__ */ new Map();
for (const icon of BUILTIN_ICONS) {
  ICON_BY_ID.set(icon.id, icon);
  for (const alias of icon.aliases ?? []) {
    ICON_BY_ID.set(alias, icon);
  }
}
function resolveBuiltinIcon(id) {
  return ICON_BY_ID.get(id) ?? null;
}
function normalizeBuiltinIconId(id) {
  const resolved = resolveBuiltinIcon(id);
  return resolved?.id ?? id;
}
function getBuiltinIconSvg(id) {
  return resolveBuiltinIcon(id)?.svg ?? null;
}
function listBuiltinIconPickerGroups(options) {
  const surface = options?.surface;
  const groups = /* @__PURE__ */ new Map();
  for (const icon of BUILTIN_ICONS) {
    if (surface && !icon.catalog.surfaces.includes(surface)) continue;
    const existing = groups.get(icon.catalog.groupId);
    if (existing) {
      existing.icons.push(icon);
      continue;
    }
    groups.set(icon.catalog.groupId, {
      id: icon.catalog.groupId,
      label: icon.catalog.groupLabel,
      order: icon.catalog.order,
      icons: [icon]
    });
  }
  return Array.from(groups.values()).sort((a2, b2) => a2.order - b2.order || a2.id.localeCompare(b2.id));
}

// ../react/src/mindmap-editor/constants.ts
init_src();
var KMIND_ASSET_URL_PREFIX2 = "kmind-asset://";
var TRANSPARENT_PIXEL_DATA_URL = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==";
var defaultMaxWidth = 240;
var minNodeMainWidth = MIN_NODE_CONTENT_WIDTH;
var maxNodeMainWidth = MAX_NODE_CONTENT_WIDTH;
var cardV1SideAllowance = 320;
var exportPadding = 80;
var nodePaddingX = 12;
var nodePaddingY = 8;
var nodeFontSize = 14;
var nodeLineHeight = 1.4;
var nodeFontFamily = "ui-sans-serif, system-ui, sans-serif";
var exclusiveEmbedPaddingX = 6;
var exclusiveEmbedPaddingY = 6;
function clampNodeMainWidth(value) {
  if (typeof value !== "number" || !Number.isFinite(value)) return defaultMaxWidth;
  return Math.round(Math.max(minNodeMainWidth, Math.min(maxNodeMainWidth, value)));
}
var katexRichTextCssText = `
  .km-node-richtext .katex,
  .km-meta-popover .km-node-richtext .katex {
    display: inline-block;
    font-family: "Times New Roman", "Noto Serif SC", "Noto Serif CJK SC", serif;
    font-size: 1em;
    line-height: 1.2;
    text-indent: 0;
    text-rendering: auto;
    white-space: nowrap;
  }
  .km-node-richtext .katex *,
  .km-meta-popover .km-node-richtext .katex * {
    border-color: currentColor;
  }
  .km-node-richtext .katex .katex-mathml,
  .km-meta-popover .km-node-richtext .katex .katex-mathml {
    position: absolute;
    clip: rect(1px, 1px, 1px, 1px);
    padding: 0;
    border: 0;
    width: 1px;
    height: 1px;
    overflow: hidden;
  }
  .km-node-richtext .katex .katex-html > .newline,
  .km-meta-popover .km-node-richtext .katex .katex-html > .newline {
    display: block;
  }
  .km-node-richtext .katex .base,
  .km-meta-popover .km-node-richtext .katex .base {
    position: relative;
    display: inline-block;
    width: -webkit-min-content;
    width: min-content;
    white-space: nowrap;
  }
  .km-node-richtext .katex .strut,
  .km-node-richtext .katex .mspace,
  .km-meta-popover .km-node-richtext .katex .strut,
  .km-meta-popover .km-node-richtext .katex .mspace {
    display: inline-block;
  }
  .km-node-richtext .katex .mathnormal,
  .km-meta-popover .km-node-richtext .katex .mathnormal {
    font-style: italic;
  }
  .km-node-richtext .katex .mathrm,
  .km-meta-popover .km-node-richtext .katex .mathrm {
    font-style: normal;
  }
  .km-node-richtext .katex .cjk_fallback,
  .km-meta-popover .km-node-richtext .katex .cjk_fallback {
    font-family: var(--km-katex-cjk-font, ui-sans-serif, system-ui, sans-serif);
  }
  .km-node-richtext .katex .vlist-t,
  .km-meta-popover .km-node-richtext .katex .vlist-t {
    display: inline-table;
    table-layout: fixed;
    border-collapse: collapse;
  }
  .km-node-richtext .katex .vlist-r,
  .km-meta-popover .km-node-richtext .katex .vlist-r {
    display: table-row;
  }
  .km-node-richtext .katex .vlist,
  .km-meta-popover .km-node-richtext .katex .vlist {
    display: table-cell;
    position: relative;
    vertical-align: bottom;
  }
  .km-node-richtext .katex .vlist > span,
  .km-meta-popover .km-node-richtext .katex .vlist > span {
    display: block;
    position: relative;
    height: 0;
  }
  .km-node-richtext .katex .vlist > span > span,
  .km-meta-popover .km-node-richtext .katex .vlist > span > span {
    display: inline-block;
  }
  .km-node-richtext .katex .vlist > span > .pstrut,
  .km-meta-popover .km-node-richtext .katex .vlist > span > .pstrut {
    width: 0;
    overflow: hidden;
  }
  .km-node-richtext .katex .vlist-t2,
  .km-meta-popover .km-node-richtext .katex .vlist-t2 {
    margin-right: -2px;
  }
  .km-node-richtext .katex .vlist-s,
  .km-meta-popover .km-node-richtext .katex .vlist-s {
    display: table-cell;
    width: 2px;
    min-width: 2px;
    font-size: 1px;
    vertical-align: bottom;
  }
  .km-node-richtext .katex .msupsub,
  .km-meta-popover .km-node-richtext .katex .msupsub {
    text-align: left;
  }
  .km-node-richtext .katex .mfrac > span > span,
  .km-meta-popover .km-node-richtext .katex .mfrac > span > span,
  .km-node-richtext .katex .x-arrow,
  .km-node-richtext .katex .mover,
  .km-node-richtext .katex .munder,
  .km-meta-popover .km-node-richtext .katex .x-arrow,
  .km-meta-popover .km-node-richtext .katex .mover,
  .km-meta-popover .km-node-richtext .katex .munder {
    text-align: center;
  }
  .km-node-richtext .katex .mfrac .frac-line,
  .km-node-richtext .katex .overline .overline-line,
  .km-node-richtext .katex .underline .underline-line,
  .km-node-richtext .katex .hline,
  .km-node-richtext .katex .hdashline,
  .km-meta-popover .km-node-richtext .katex .mfrac .frac-line,
  .km-meta-popover .km-node-richtext .katex .overline .overline-line,
  .km-meta-popover .km-node-richtext .katex .underline .underline-line,
  .km-meta-popover .km-node-richtext .katex .hline,
  .km-meta-popover .km-node-richtext .katex .hdashline {
    display: inline-block;
    width: 100%;
    min-height: 1px;
    border-bottom-style: solid;
  }
  .km-node-richtext .katex .hdashline,
  .km-meta-popover .km-node-richtext .katex .hdashline {
    border-bottom-style: dashed;
  }
  .km-node-richtext .katex .rule,
  .km-meta-popover .km-node-richtext .katex .rule {
    display: inline-block;
    position: relative;
    min-height: 1px;
    border: solid 0;
  }
  .km-node-richtext .katex .llap,
  .km-node-richtext .katex .rlap,
  .km-node-richtext .katex .clap,
  .km-meta-popover .km-node-richtext .katex .llap,
  .km-meta-popover .km-node-richtext .katex .rlap,
  .km-meta-popover .km-node-richtext .katex .clap {
    position: relative;
    width: 0;
  }
  .km-node-richtext .katex .llap > .inner,
  .km-node-richtext .katex .rlap > .inner,
  .km-node-richtext .katex .clap > .inner,
  .km-meta-popover .km-node-richtext .katex .llap > .inner,
  .km-meta-popover .km-node-richtext .katex .rlap > .inner,
  .km-meta-popover .km-node-richtext .katex .clap > .inner {
    position: absolute;
  }
  .km-node-richtext .katex .llap > .inner,
  .km-meta-popover .km-node-richtext .katex .llap > .inner {
    right: 0;
  }
  .km-node-richtext .katex .rlap > .inner,
  .km-node-richtext .katex .clap > .inner,
  .km-meta-popover .km-node-richtext .katex .rlap > .inner,
  .km-meta-popover .km-node-richtext .katex .clap > .inner {
    left: 0;
  }
  .km-node-richtext .katex .llap > .fix,
  .km-node-richtext .katex .rlap > .fix,
  .km-node-richtext .katex .clap > .fix,
  .km-meta-popover .km-node-richtext .katex .llap > .fix,
  .km-meta-popover .km-node-richtext .katex .rlap > .fix,
  .km-meta-popover .km-node-richtext .katex .clap > .fix {
    display: inline-block;
  }
  .km-node-richtext .katex .x-arrow-pad,
  .km-meta-popover .km-node-richtext .katex .x-arrow-pad {
    padding: 0 0.5em;
  }
  .km-node-richtext .katex .svg-align,
  .km-meta-popover .km-node-richtext .katex .svg-align {
    text-align: left;
  }
  .km-node-richtext .katex svg,
  .km-meta-popover .km-node-richtext .katex svg {
    display: block;
    position: absolute;
    width: 100%;
    height: inherit;
    fill: currentColor;
    stroke: currentColor;
    fill-rule: nonzero;
    fill-opacity: 1;
    stroke-width: 1;
    stroke-linecap: butt;
    stroke-linejoin: miter;
    stroke-miterlimit: 4;
    stroke-dasharray: none;
    stroke-dashoffset: 0;
    stroke-opacity: 1;
  }
  .km-node-richtext .katex svg path,
  .km-meta-popover .km-node-richtext .katex svg path {
    stroke: none;
  }
  .km-node-richtext .katex .hide-tail,
  .km-node-richtext .katex .stretchy,
  .km-meta-popover .km-node-richtext .katex .hide-tail,
  .km-meta-popover .km-node-richtext .katex .stretchy {
    display: block;
    position: relative;
    width: 100%;
    overflow: hidden;
  }
  .km-node-richtext .katex .sizing.reset-size6.size3,
  .km-meta-popover .km-node-richtext .katex .sizing.reset-size6.size3 {
    font-size: 0.7em;
  }
`;
var nodeRichTextCssText = `
  .km-node-body,
  .km-node-body * {
    box-sizing: border-box;
  }
  .km-node-blur-hidden {
    filter: blur(8px);
  }
  .km-node-body {
    display: grid;
    grid-template-areas:
      "top top top"
      "left main right"
      "bottom bottom bottom";
    grid-template-columns: auto 1fr auto;
    grid-template-rows: auto auto auto;
    column-gap: 8px;
    row-gap: 6px;
  }
  .km-node-body--card-v1 {
    column-gap: 10px;
    row-gap: 4px;
    grid-template-columns: auto fit-content(var(--km-node-main-max-width, 240px)) auto;
    grid-template-areas:
      ". top ."
      "left main right"
      ". bottom .";
  }
  .km-node-body--card-v1.km-node-body--card-v1-fixed {
    grid-template-columns: auto var(--km-node-main-max-width, 240px) auto;
  }
  .km-node-body--card-v1.km-node-body--exclusive-embed {
    grid-template-columns: auto max-content auto;
  }
  .km-node-body--card-v1.km-node-body--card-v1-fixed.km-node-body--exclusive-embed {
    grid-template-columns: auto max-content auto;
  }
  .km-node-body--exclusive-embed {
    column-gap: 0;
    row-gap: 0;
  }
  .km-node-body--card-v1.km-node-body--card-v1-has-chrome-top {
    padding-top: 16px;
  }
  .km-node-body--card-v1 .km-node-region-left {
    display: flex;
    gap: 8px;
    align-items: center;
    flex-wrap: nowrap;
  }
  .km-node-body--card-v1 .km-node-region-left .km-node-icons {
    flex-wrap: nowrap;
  }
  .km-node-body--card-v1 .km-node-region-right {
    display: flex;
    align-items: center;
    gap: 6px;
  }
  .km-node-body--card-v1 .km-node-region-right .km-node-icons {
    flex-wrap: nowrap;
  }
  .km-node-main-layout {
    display: grid;
    grid-template-areas:
      ". top ."
      "left main right"
      ". bottom .";
    grid-template-columns: max-content minmax(0, 1fr) max-content;
    grid-template-rows: auto auto auto;
    justify-content: start;
    align-content: start;
  }
  .km-node-main-layout__top {
    grid-area: top;
    display: flex;
    flex-direction: column;
    gap: 8px;
    align-items: center;
    justify-content: flex-start;
    margin-bottom: 8px;
  }
  .km-node-main-layout__left {
    grid-area: left;
    display: flex;
    flex-direction: column;
    gap: 8px;
    align-items: center;
    justify-content: center;
    align-self: center;
    margin-right: 8px;
  }
  .km-node-main-layout__main {
    grid-area: main;
    min-width: 0;
  }
  .km-node-main-layout__right {
    grid-area: right;
    display: flex;
    flex-direction: column;
    gap: 8px;
    align-items: center;
    justify-content: center;
    align-self: center;
    margin-left: 8px;
  }
  .km-node-main-layout__bottom {
    grid-area: bottom;
    display: flex;
    flex-direction: column;
    gap: 8px;
    align-items: center;
    justify-content: flex-start;
    margin-top: 8px;
  }
  .km-node-region-top {
    grid-area: top;
  }
  .km-node-region-left {
    grid-area: left;
  }
  .km-node-region-main {
    grid-area: main;
    min-width: 0;
  }
  .km-node-region-right {
    grid-area: right;
  }
  .km-node-region-bottom {
    grid-area: bottom;
  }
  .km-node-seq {
    font-size: 12px;
    color: rgba(100, 116, 139, 0.9);
    font-variant-numeric: tabular-nums;
  }
  .km-node-tags {
    display: flex;
    flex-wrap: wrap;
    gap: 6px;
    align-items: center;
  }
  .km-node-tag {
    border: 1px solid rgba(148, 163, 184, 0.45);
    background: rgba(226, 232, 240, 0.6);
    padding: 1px 6px;
    border-radius: 999px;
    font-size: 11px;
    line-height: 16px;
    white-space: nowrap;
  }
  .km-node-icons {
    display: inline-flex;
    gap: 6px;
    align-items: center;
    flex-wrap: wrap;
  }
  .km-node-icon {
    font-size: 14px;
    line-height: 18px;
    flex-shrink: 0;
    cursor: pointer;
  }
  .km-node-icon--builtin {
    display: inline-flex;
    align-items: center;
  }
  .km-node-icon--builtin svg {
    width: 16px;
    height: 16px;
    display: block;
  }
  .km-node-icon--asset {
    display: inline-flex;
    align-items: center;
  }
  .km-node-icon--asset img {
    width: 16px;
    height: 16px;
    display: block;
  }
  .km-node-images {
    display: flex;
    flex-direction: column;
    gap: 8px;
  }
  .km-node-image {
    display: block;
    border-radius: 10px;
    max-width: 100%;
  }
  .km-node-tasks {
    display: flex;
    flex-direction: column;
    gap: 6px;
    font-size: 12px;
    color: rgba(15, 23, 42, 0.9);
  }
  .km-node-task {
    display: flex;
    gap: 8px;
    align-items: center;
    line-height: 16px;
  }
  .km-node-task-box {
    width: 14px;
    height: 14px;
    border-radius: 4px;
    border: 1px solid rgba(148, 163, 184, 0.55);
    background: rgba(255, 255, 255, 0.9);
    display: inline-flex;
    align-items: center;
    justify-content: center;
    font-size: 10px;
  }
  .km-node-task-toggle {
    width: 18px;
    height: 18px;
    border-radius: 6px;
    border: 1px solid rgba(148, 163, 184, 0.55);
    background: rgba(255, 255, 255, 0.9);
    display: inline-flex;
    align-items: center;
    justify-content: center;
    font-size: 12px;
    line-height: 1;
    cursor: pointer;
    user-select: none;
  }
  .km-node-task-toggle[aria-checked="true"] {
    border-color: rgba(34, 197, 94, 0.65);
    background: rgba(34, 197, 94, 0.92);
    color: rgba(255, 255, 255, 0.96);
  }
  .km-node-meta-btn {
    width: 18px;
    height: 18px;
    border-radius: 6px;
    border: none;
    background: transparent;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    padding: 0;
    cursor: pointer;
    user-select: none;
    color: var(--km-text);
    opacity: 0.78;
  }
  .km-node-meta-btn:hover {
    background: rgba(148, 163, 184, 0.14);
    color: var(--km-text);
    opacity: 1;
  }
  .km-node-meta-btn svg {
    width: 14px;
    height: 14px;
    display: block;
  }
  .km-node-leading-link {
    display: flex;
    align-items: center;
    gap: 7px;
    min-width: 0;
  }
  .km-node-leading-link__icon {
    flex: none;
    width: 18px;
    height: 18px;
    border: none;
    border-radius: 6px;
    background: transparent;
    color: var(--km-muted);
    display: inline-flex;
    align-items: center;
    justify-content: center;
    padding: 0;
    cursor: pointer;
    user-select: none;
    opacity: 0.86;
  }
  .km-node-leading-link__icon:hover {
    background: rgba(148, 163, 184, 0.14);
    color: var(--km-text);
    opacity: 1;
  }
  .km-node-leading-link__icon svg {
    width: 15px;
    height: 15px;
    display: block;
  }
  .km-node-leading-link__icon img,
  .km-node-leading-link__siyuan-icon {
    width: 15px;
    height: 15px;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    object-fit: contain;
    font-size: 14px;
    line-height: 1;
  }
  .km-node-leading-link__title {
    min-width: 0;
  }
  .km-node-links {
    display: flex;
    flex-direction: column;
    gap: 6px;
    font-size: 12px;
  }
  .km-node-link {
    display: inline-flex;
    align-items: center;
    gap: 8px;
    line-height: 16px;
    opacity: 0.9;
  }
  .km-node-link-code {
    font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;
    font-size: 11px;
    padding: 1px 6px;
    border-radius: 999px;
    border: 1px solid rgba(148, 163, 184, 0.45);
    background: rgba(241, 245, 249, 0.6);
  }
  .km-node-notes {
    font-size: 12px;
    color: var(--b3-theme-on-surface, #64748b);
    white-space: pre-wrap;
    overflow-wrap: anywhere;
  }
  .km-node-embed {
    border-radius: 12px;
    border: 1px dashed rgba(148, 163, 184, 0.55);
    background: rgba(241, 245, 249, 0.55);
    color: var(--b3-theme-on-surface, #64748b);
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 12px;
    line-height: 16px;
    text-align: center;
    padding: 10px 12px;
  }
  .km-node-body--exclusive-embed .km-node-region-main {
    text-align: left;
  }
  .km-node-body--exclusive-embed .km-node-embed-wrap {
    display: block;
  }
  .km-node-embed[data-km-embed-type="kmind:protyle"] {
    display: block;
    padding: 0;
    border: none;
    background: transparent;
    color: inherit;
    text-align: left;
  }
  .km-node-embed[data-km-embed-type="kmind:siyuan-doc"] {
    display: block;
    padding: 0;
    border: none;
    background: transparent;
    color: inherit;
    text-align: left;
  }
  .km-node-doc-ghost {
    display: flex;
    flex-direction: column;
    width: 100%;
    height: 100%;
    border-radius: 12px;
    overflow: hidden;
    border: 1px solid var(--b3-border-color, rgba(148, 163, 184, 0.35));
    background: var(--b3-theme-background, #fff);
    box-shadow: 0 10px 24px rgba(15, 23, 42, 0.06);
  }
  .km-node-doc-ghost__toolbar {
    flex: 0 0 auto;
    min-height: 30px;
    padding: 7px 10px;
    border-bottom: 1px solid var(--b3-border-color, rgba(148, 163, 184, 0.35));
    background: var(--b3-theme-surface, rgba(148, 163, 184, 0.12));
    color: var(--b3-theme-on-surface, #64748b);
    font-size: 12px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
  .km-node-doc-ghost__body {
    display: flex;
    flex: 1 1 auto;
    min-height: 0;
    flex-direction: column;
    gap: 12px;
    padding: 12px 14px 14px;
    text-align: left;
  }
  .km-node-doc-ghost__header {
    display: flex;
    align-items: flex-start;
    gap: 10px;
  }
  .km-node-doc-ghost__icon {
    width: 28px;
    height: 28px;
    flex: 0 0 auto;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    border-radius: 10px;
    overflow: hidden;
    background: var(--b3-theme-surface, rgba(148, 163, 184, 0.12));
    color: var(--b3-theme-on-background, #0f172a);
    font-size: 16px;
  }
  .km-node-doc-ghost__icon img {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
  .km-node-doc-ghost__content {
    display: flex;
    flex: 1 1 auto;
    min-width: 0;
    flex-direction: column;
    gap: 6px;
  }
  .km-node-doc-ghost__title {
    color: var(--b3-theme-on-background, #0f172a);
    font-size: 14px;
    font-weight: 600;
    line-height: 1.4;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
  .km-node-doc-ghost__meta {
    display: flex;
    flex-wrap: wrap;
    gap: 6px;
    color: var(--b3-theme-on-surface, #64748b);
    font-size: 11px;
  }
  .km-node-doc-ghost__meta span {
    padding: 1px 6px;
    border-radius: 999px;
    border: 1px solid var(--b3-border-color, rgba(148, 163, 184, 0.35));
    background: var(--b3-theme-surface, rgba(148, 163, 184, 0.12));
  }
  .km-node-doc-ghost__excerpt {
    color: var(--b3-theme-on-surface, #64748b);
    font-size: 12px;
    line-height: 1.65;
    display: -webkit-box;
    overflow: hidden;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 4;
  }
  .km-node-embed-wrap {
    position: relative;
    display: inline-block;
  }
  .km-node-embed__resize-handle {
    position: absolute;
    right: 6px;
    bottom: 6px;
    width: 14px;
    height: 14px;
    border-radius: 6px;
    cursor: nwse-resize;
    border: 1px solid rgba(148, 163, 184, 0.45);
    background: rgba(255, 255, 255, 0.75);
    opacity: 0;
    transition: opacity 120ms ease;
  }
  .km-node-embed__resize-handle::before {
    content: "";
    position: absolute;
    inset: 0;
    border-radius: 6px;
    background:
      linear-gradient(135deg,
        transparent 0 45%,
        rgba(100, 116, 139, 0.65) 45% 52%,
        transparent 52% 62%,
        rgba(100, 116, 139, 0.65) 62% 69%,
        transparent 69% 100%);
    opacity: 0.75;
  }
  .km-node-embed-wrap:hover .km-node-embed__resize-handle {
    opacity: 1;
  }
  .km-node-richtext,
  .km-node-richtext * {
    box-sizing: border-box;
  }
  .km-node-richtext {
    overflow-wrap: anywhere;
    word-break: break-word;
  }
  .km-node-richtext p {
    margin: 0;
  }
  .km-node-richtext img {
    display: inline-block;
    max-width: 100%;
    height: auto;
    border-radius: 10px;
    vertical-align: middle;
  }
  .km-node-richtext [data-km-cloze] {
    border-radius: 6px;
    padding: 0 2px;
    transition: filter 120ms ease, color 120ms ease, background 120ms ease;
  }
  .km-node-richtext [data-km-cloze][data-km-cloze-style="blur"]:not([data-km-revealed="true"]) {
    filter: blur(6px);
  }
  .km-node-richtext [data-km-cloze][data-km-cloze-style="hole"]:not([data-km-revealed="true"]) {
    color: transparent;
    background: rgba(15, 23, 42, 0.12);
  }
  .km-node-richtext [data-km-cloze][data-km-reveal-mode="hover"]:hover {
    filter: none;
    color: inherit;
    background: transparent;
  }
  .km-node-richtext [data-km-cloze][data-km-revealed="true"] {
    filter: none;
    color: inherit;
    background: transparent;
  }
  .km-node-richtext pre {
    margin: 0;
    padding: 8px 10px;
    border-radius: 8px;
    background: var(--km-code-bg, rgba(15, 23, 42, 0.06));
    box-shadow: inset 0 0 0 1px var(--km-code-border, rgba(148, 163, 184, 0.35));
    overflow: hidden;
    white-space: pre-wrap;
    word-break: break-word;
    font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;
    font-size: 13px;
    line-height: 1.4;
  }
  .km-node-richtext :not(pre) > code {
    padding: 0.12em 0.35em;
    border-radius: 6px;
    background: rgba(15, 23, 42, 0.08);
    border: 1px solid rgba(148, 163, 184, 0.35);
  }
  .km-node-richtext pre code {
    padding: 0;
    background: transparent;
    border: none;
  }
  .km-node-richtext code {
    font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;
  }
  .km-node-richtext .km-formula-block {
    display: flex;
    justify-content: center;
    align-items: center;
    margin: 6px 0;
    max-width: 100%;
    overflow: visible;
  }
  ${katexRichTextCssText}
  .km-node-richtext .km-code-token--keyword {
    color: var(--km-code-token-keyword, rgba(124, 58, 237, 0.95));
  }
  .km-node-richtext .km-code-token--string {
    color: var(--km-code-token-string, rgba(2, 132, 199, 0.95));
  }
  .km-node-richtext .km-code-token--number {
    color: var(--km-code-token-number, rgba(234, 88, 12, 0.95));
  }
  .km-node-richtext .km-code-token--comment {
    color: var(--km-code-token-comment, rgba(100, 116, 139, 0.85));
  }
  .km-node-richtext .km-code-token--property {
    color: var(--km-code-token-property, rgba(29, 78, 216, 0.95));
  }
  .km-node-richtext .km-code-token--punct {
    color: var(--km-code-token-punct, rgba(51, 65, 85, 0.88));
  }
  .km-node-richtext a {
    color: inherit;
    text-decoration: underline;
  }
`;

// ../react/src/mindmap-editor/node-html.ts
init_src();

// ../content-prosemirror/dist/index.js
var TEXT_STYLE_MARK_NAME = "kmindTextStyle";
var INLINE_IMAGE_PLACEHOLDER = "[\u56FE\u7247]";
function createProseMirrorDocFromText(text5) {
  const lines = String(text5 ?? "").split(/\r?\n/);
  const content = lines.map((line) => line.length > 0 ? { type: "paragraph", content: [{ type: "text", text: line }] } : { type: "paragraph" });
  return { type: "doc", content: content.length > 0 ? content : [{ type: "paragraph" }] };
}
function createEditableDocFromHtmlBackedContent(args) {
  const baseDoc = isProseMirrorDoc(args.doc) ? args.doc : createProseMirrorDocFromText(args.fallbackText);
  const html = typeof args.html === "string" ? args.html.trim() : "";
  if (!html)
    return baseDoc;
  if (!isPlainTextOnlyDoc(baseDoc))
    return baseDoc;
  const hydrated = createDocFromCompatibleHtml(html);
  return hasMeaningfulDocContent(hydrated) ? hydrated : baseDoc;
}
function isProseMirrorDoc(value) {
  return Boolean(value) && typeof value === "object" && !Array.isArray(value) && value.type === "doc";
}
function isPlainTextOnlyDoc(value) {
  if (!isProseMirrorDoc(value))
    return false;
  const blocks = Array.isArray(value.content) ? value.content : [];
  return blocks.every((block) => {
    if (!block || typeof block !== "object" || Array.isArray(block))
      return false;
    if (block.type !== "paragraph")
      return false;
    const children = Array.isArray(block.content) ? block.content : [];
    return children.every((child) => {
      if (!child || typeof child !== "object" || Array.isArray(child))
        return false;
      if (child.type !== "text")
        return false;
      const marks = Array.isArray(child.marks) ? child.marks : [];
      return marks.length === 0;
    });
  });
}
function hasMeaningfulDocContent(value) {
  if (!isProseMirrorDoc(value))
    return false;
  const blocks = Array.isArray(value.content) ? value.content : [];
  if (blocks.length === 0)
    return false;
  return blocks.some((block) => {
    if (!block || typeof block !== "object" || Array.isArray(block))
      return false;
    if (block.type === "codeBlock") {
      return Array.isArray(block.content) ? block.content.some((child) => child?.type === "text" && typeof child.text === "string" && child.text.length > 0) : false;
    }
    if (block.type !== "paragraph")
      return false;
    const children = Array.isArray(block.content) ? block.content : [];
    return children.some((child) => {
      if (!child || typeof child !== "object" || Array.isArray(child))
        return false;
      if (child.type === "hardBreak")
        return true;
      return typeof child.text === "string" && child.text.length > 0;
    });
  });
}
function sortJsonLike(value) {
  if (Array.isArray(value))
    return value.map((item) => sortJsonLike(item));
  if (!value || typeof value !== "object")
    return value;
  const sortedEntries = Object.entries(value).filter(([, child]) => child !== void 0).sort(([a2], [b2]) => a2.localeCompare(b2)).map(([key, child]) => [key, sortJsonLike(child)]);
  return Object.fromEntries(sortedEntries);
}
function stableStringifyJsonLike(value) {
  return JSON.stringify(sortJsonLike(value));
}
function sameMarks(a2, b2) {
  return stableStringifyJsonLike(a2 ?? []) === stableStringifyJsonLike(b2 ?? []);
}
function appendParagraphText(content, text5, marks) {
  if (!text5)
    return;
  const prev = content.at(-1);
  const nextMarks = marks.length > 0 ? marks.map((mark) => ({ ...mark })) : void 0;
  if (prev?.type === "text" && sameMarks(prev.marks, nextMarks)) {
    prev.text = `${prev.text ?? ""}${text5}`;
    return;
  }
  content.push({
    type: "text",
    text: text5,
    ...nextMarks ? { marks: nextMarks } : {}
  });
}
function decodeHtmlEntities(input) {
  return input.replace(/&#(\d+);/g, (_full, raw) => {
    const code = Number.parseInt(raw, 10);
    return Number.isFinite(code) ? String.fromCodePoint(code) : "";
  }).replace(/&#x([0-9a-f]+);/gi, (_full, raw) => {
    const code = Number.parseInt(raw, 16);
    return Number.isFinite(code) ? String.fromCodePoint(code) : "";
  }).replaceAll("&nbsp;", " ").replaceAll("&amp;", "&").replaceAll("&lt;", "<").replaceAll("&gt;", ">").replaceAll("&quot;", '"').replaceAll("&#39;", "'");
}
function parseHtmlAttributes(input) {
  const attrs = {};
  const pattern = /([^\s=/>]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+)))?/g;
  for (const match of input.matchAll(pattern)) {
    const name = String(match[1] ?? "").trim().toLowerCase();
    if (!name)
      continue;
    const value = String(match[2] ?? match[3] ?? match[4] ?? "");
    attrs[name] = value;
  }
  return attrs;
}
function tokenizeHtml(input) {
  const tokens = [];
  const pattern = /<!--[\s\S]*?-->|<[^>]+>|[^<]+/g;
  for (const match of input.matchAll(pattern)) {
    const raw = match[0];
    if (!raw || raw.startsWith("<!--"))
      continue;
    if (!raw.startsWith("<")) {
      tokens.push({ kind: "text", value: raw });
      continue;
    }
    const endMatch = raw.match(/^<\s*\/\s*([A-Za-z0-9:-]+)[^>]*>$/);
    if (endMatch) {
      tokens.push({ kind: "end", tag: String(endMatch[1] ?? "").toLowerCase() });
      continue;
    }
    const startMatch = raw.match(/^<\s*([A-Za-z0-9:-]+)([\s\S]*?)>$/);
    if (!startMatch)
      continue;
    const tag = String(startMatch[1] ?? "").toLowerCase();
    const body = String(startMatch[2] ?? "");
    const selfClosing = /\/\s*$/.test(body) || tag === "br" || tag === "img";
    tokens.push({
      kind: "start",
      tag,
      attrs: parseHtmlAttributes(selfClosing ? body.replace(/\/\s*$/, "") : body),
      selfClosing
    });
  }
  return tokens;
}
function sanitizeCssColor(input) {
  const value = input.trim();
  if (value.length === 0)
    return null;
  if (value === "transparent")
    return value;
  if (/^#[0-9a-f]{3,4}$/i.test(value))
    return value;
  if (/^#[0-9a-f]{6}([0-9a-f]{2})?$/i.test(value))
    return value;
  if (/^rgba?\(\s*\d+\s*,\s*\d+\s*,\s*\d+\s*(,\s*(0|1|0?\.\d+)\s*)?\)$/i.test(value))
    return value;
  if (/^hsla?\(\s*\d+\s*,\s*\d+%\s*,\s*\d+%\s*(,\s*(0|1|0?\.\d+)\s*)?\)$/i.test(value))
    return value;
  return null;
}
function sanitizeCssFontSize(input) {
  const match = input.trim().match(/^(\d+(\.\d+)?)(px)?$/i);
  if (!match)
    return null;
  const num = Number(match[1]);
  if (!Number.isFinite(num))
    return null;
  const clamped = Math.max(8, Math.min(72, num));
  return `${clamped}px`;
}
function sanitizeCssFontFamily(input) {
  const value = input.trim().replace(/\s*!important\s*$/i, "");
  if (value.length === 0 || value.length > 160)
    return null;
  if (/[;{}<>]/.test(value) || /url\s*\(/i.test(value))
    return null;
  if (!/^[\p{L}\p{N}\s"',._-]+$/u.test(value))
    return null;
  return value;
}
function normalizeFontFamilyAttrValue(input) {
  const value = input.trim().replace(/\s*!important\s*$/i, "");
  if (value.length === 0)
    return null;
  const lowered = value.toLowerCase();
  if (lowered.includes("sans-serif") || lowered.includes("system-ui"))
    return "sans";
  if (lowered.includes("monospace"))
    return "mono";
  if (lowered.includes("serif"))
    return lowered.includes("sans-serif") ? "sans" : "serif";
  return sanitizeCssFontFamily(value);
}
function parseTextStyleMark(attrs) {
  let color = null;
  let background = null;
  let fontSize = null;
  let fontFamily = normalizeFontFamilyAttrValue(attrs["data-km-font"] ?? "");
  const declarations = String(attrs.style ?? "").split(";");
  for (const decl of declarations) {
    const [rawProp, ...rawRest] = decl.split(":");
    if (!rawProp)
      continue;
    const prop = rawProp.trim().toLowerCase();
    const value = rawRest.join(":").trim();
    if (!value)
      continue;
    if (prop === "color") {
      color = sanitizeCssColor(value);
      continue;
    }
    if (prop === "background" || prop === "background-color") {
      background = sanitizeCssColor(value);
      continue;
    }
    if (prop === "font-size") {
      const safe = sanitizeCssFontSize(value);
      if (safe)
        fontSize = Number.parseFloat(safe);
      continue;
    }
    if (prop === "font-family") {
      fontFamily = normalizeFontFamilyAttrValue(value) ?? fontFamily;
    }
  }
  if (!color && !background && !fontSize && !fontFamily)
    return null;
  return {
    type: TEXT_STYLE_MARK_NAME,
    attrs: {
      ...color ? { color } : {},
      ...background ? { background } : {},
      ...fontSize ? { fontSize } : {},
      ...fontFamily ? { fontFamily } : {}
    }
  };
}
function createMarkForTag(tag, attrs, inCodeBlock) {
  if (inCodeBlock)
    return null;
  switch (tag) {
    case "strong":
    case "b":
      return { type: "bold" };
    case "em":
    case "i":
      return { type: "italic" };
    case "s":
    case "strike":
    case "del":
      return { type: "strike" };
    case "code":
      return { type: "code" };
    case "a": {
      const href = String(attrs.href ?? "").trim();
      if (!href || /^javascript:/i.test(href))
        return null;
      return { type: "link", attrs: { href } };
    }
    case "span":
      return parseTextStyleMark(attrs);
    default:
      return null;
  }
}
function createDocFromCompatibleHtml(html) {
  const tokens = tokenizeHtml(html);
  const blocks = [];
  let currentParagraph = null;
  let currentCodeBlock = null;
  const markStack = [];
  const activeMarks = [];
  const listStack = [];
  const flushParagraph = () => {
    if (!currentParagraph)
      return;
    blocks.push(currentParagraph.content.length > 0 ? { type: "paragraph", content: currentParagraph.content } : { type: "paragraph" });
    currentParagraph = null;
  };
  const flushCodeBlock = () => {
    if (!currentCodeBlock)
      return;
    const text5 = currentCodeBlock.text;
    blocks.push(text5.length > 0 ? { type: "codeBlock", content: [{ type: "text", text: text5 }] } : { type: "codeBlock" });
    currentCodeBlock = null;
  };
  const ensureParagraph = () => {
    if (currentCodeBlock)
      flushCodeBlock();
    if (!currentParagraph)
      currentParagraph = { type: "paragraph", content: [] };
    return currentParagraph;
  };
  const appendInlineText = (raw) => {
    if (currentCodeBlock) {
      currentCodeBlock.text += decodeHtmlEntities(raw);
      return;
    }
    const text5 = decodeHtmlEntities(raw).replace(/\u00a0/g, " ").replace(/[\r\n\t]+/g, " ");
    if (!text5)
      return;
    const paragraph = ensureParagraph();
    appendParagraphText(paragraph.content, text5, activeMarks);
  };
  const appendHardBreak = () => {
    if (currentCodeBlock) {
      currentCodeBlock.text += "\n";
      return;
    }
    const paragraph = ensureParagraph();
    paragraph.content.push({ type: "hardBreak" });
  };
  const closeMark = (tag) => {
    for (let index = markStack.length - 1; index >= 0; index -= 1) {
      const entry = markStack[index];
      if (!entry)
        continue;
      if (entry.tag !== tag)
        continue;
      markStack.splice(index, 1);
      if (entry.mark) {
        const activeIndex = activeMarks.lastIndexOf(entry.mark);
        if (activeIndex >= 0)
          activeMarks.splice(activeIndex, 1);
      }
      return;
    }
  };
  const startParagraphBoundary = () => {
    if (currentParagraph && currentParagraph.content.length > 0) {
      flushParagraph();
    } else if (currentCodeBlock) {
      flushCodeBlock();
    }
    ensureParagraph();
  };
  for (const token of tokens) {
    if (token.kind === "text") {
      appendInlineText(token.value);
      continue;
    }
    if (token.kind === "end") {
      switch (token.tag) {
        case "strong":
        case "b":
        case "em":
        case "i":
        case "s":
        case "strike":
        case "del":
        case "code":
        case "a":
        case "span":
          closeMark(token.tag);
          break;
        case "pre":
          flushCodeBlock();
          break;
        case "p":
        case "div":
        case "blockquote":
        case "h1":
        case "h2":
        case "li":
          flushParagraph();
          break;
        case "ul":
        case "ol":
          listStack.pop();
          break;
        default:
          break;
      }
      continue;
    }
    switch (token.tag) {
      case "br":
        appendHardBreak();
        break;
      case "p":
      case "div":
      case "blockquote":
      case "h1":
      case "h2":
        startParagraphBoundary();
        if (token.selfClosing)
          flushParagraph();
        break;
      case "ul":
      case "ol":
        {
          const paragraph = currentParagraph;
          if ((paragraph?.content.length ?? 0) === 0)
            currentParagraph = null;
        }
        listStack.push({
          ordered: token.tag === "ol",
          index: token.tag === "ol" ? Math.max(0, Number.parseInt(String(token.attrs.start ?? "1"), 10) - 1) : 0
        });
        break;
      case "li": {
        startParagraphBoundary();
        const list = listStack.at(-1);
        const prefix = list?.ordered ? `${list.index += 1}. ` : "\u2022 ";
        appendInlineText(prefix);
        if (token.selfClosing)
          flushParagraph();
        break;
      }
      case "pre":
        flushParagraph();
        currentCodeBlock = { type: "codeBlock", text: "" };
        if (token.selfClosing)
          flushCodeBlock();
        break;
      case "img":
        appendInlineText(String(token.attrs.alt ?? "").trim() || INLINE_IMAGE_PLACEHOLDER);
        break;
      case "strong":
      case "b":
      case "em":
      case "i":
      case "s":
      case "strike":
      case "del":
      case "code":
      case "a":
      case "span": {
        const mark = createMarkForTag(token.tag, token.attrs, Boolean(currentCodeBlock));
        markStack.push({ tag: token.tag, mark });
        if (mark)
          activeMarks.push(mark);
        if (token.selfClosing)
          closeMark(token.tag);
        break;
      }
      default:
        break;
    }
  }
  flushParagraph();
  flushCodeBlock();
  return { type: "doc", content: blocks.length > 0 ? blocks : [{ type: "paragraph" }] };
}

// ../../node_modules/.pnpm/orderedmap@2.1.1/node_modules/orderedmap/dist/index.js
function OrderedMap(content) {
  this.content = content;
}
OrderedMap.prototype = {
  constructor: OrderedMap,
  find: function(key) {
    for (var i = 0; i < this.content.length; i += 2)
      if (this.content[i] === key) return i;
    return -1;
  },
  // :: (string) → ?any
  // Retrieve the value stored under `key`, or return undefined when
  // no such key exists.
  get: function(key) {
    var found2 = this.find(key);
    return found2 == -1 ? void 0 : this.content[found2 + 1];
  },
  // :: (string, any, ?string) → OrderedMap
  // Create a new map by replacing the value of `key` with a new
  // value, or adding a binding to the end of the map. If `newKey` is
  // given, the key of the binding will be replaced with that key.
  update: function(key, value, newKey) {
    var self = newKey && newKey != key ? this.remove(newKey) : this;
    var found2 = self.find(key), content = self.content.slice();
    if (found2 == -1) {
      content.push(newKey || key, value);
    } else {
      content[found2 + 1] = value;
      if (newKey) content[found2] = newKey;
    }
    return new OrderedMap(content);
  },
  // :: (string) → OrderedMap
  // Return a map with the given key removed, if it existed.
  remove: function(key) {
    var found2 = this.find(key);
    if (found2 == -1) return this;
    var content = this.content.slice();
    content.splice(found2, 2);
    return new OrderedMap(content);
  },
  // :: (string, any) → OrderedMap
  // Add a new key to the start of the map.
  addToStart: function(key, value) {
    return new OrderedMap([key, value].concat(this.remove(key).content));
  },
  // :: (string, any) → OrderedMap
  // Add a new key to the end of the map.
  addToEnd: function(key, value) {
    var content = this.remove(key).content.slice();
    content.push(key, value);
    return new OrderedMap(content);
  },
  // :: (string, string, any) → OrderedMap
  // Add a key after the given key. If `place` is not found, the new
  // key is added to the end.
  addBefore: function(place, key, value) {
    var without = this.remove(key), content = without.content.slice();
    var found2 = without.find(place);
    content.splice(found2 == -1 ? content.length : found2, 0, key, value);
    return new OrderedMap(content);
  },
  // :: ((key: string, value: any))
  // Call the given function for each key/value pair in the map, in
  // order.
  forEach: function(f) {
    for (var i = 0; i < this.content.length; i += 2)
      f(this.content[i], this.content[i + 1]);
  },
  // :: (union<Object, OrderedMap>) → OrderedMap
  // Create a new map by prepending the keys in this map that don't
  // appear in `map` before the keys in `map`.
  prepend: function(map2) {
    map2 = OrderedMap.from(map2);
    if (!map2.size) return this;
    return new OrderedMap(map2.content.concat(this.subtract(map2).content));
  },
  // :: (union<Object, OrderedMap>) → OrderedMap
  // Create a new map by appending the keys in this map that don't
  // appear in `map` after the keys in `map`.
  append: function(map2) {
    map2 = OrderedMap.from(map2);
    if (!map2.size) return this;
    return new OrderedMap(this.subtract(map2).content.concat(map2.content));
  },
  // :: (union<Object, OrderedMap>) → OrderedMap
  // Create a map containing all the keys in this map that don't
  // appear in `map`.
  subtract: function(map2) {
    var result = this;
    map2 = OrderedMap.from(map2);
    for (var i = 0; i < map2.content.length; i += 2)
      result = result.remove(map2.content[i]);
    return result;
  },
  // :: () → Object
  // Turn ordered map into a plain object.
  toObject: function() {
    var result = {};
    this.forEach(function(key, value) {
      result[key] = value;
    });
    return result;
  },
  // :: number
  // The amount of keys in this map.
  get size() {
    return this.content.length >> 1;
  }
};
OrderedMap.from = function(value) {
  if (value instanceof OrderedMap) return value;
  var content = [];
  if (value) for (var prop in value) content.push(prop, value[prop]);
  return new OrderedMap(content);
};
var dist_default = OrderedMap;

// ../../node_modules/.pnpm/prosemirror-model@1.25.4/node_modules/prosemirror-model/dist/index.js
function findDiffStart(a2, b2, pos) {
  for (let i = 0; ; i++) {
    if (i == a2.childCount || i == b2.childCount)
      return a2.childCount == b2.childCount ? null : pos;
    let childA = a2.child(i), childB = b2.child(i);
    if (childA == childB) {
      pos += childA.nodeSize;
      continue;
    }
    if (!childA.sameMarkup(childB))
      return pos;
    if (childA.isText && childA.text != childB.text) {
      for (let j = 0; childA.text[j] == childB.text[j]; j++)
        pos++;
      return pos;
    }
    if (childA.content.size || childB.content.size) {
      let inner2 = findDiffStart(childA.content, childB.content, pos + 1);
      if (inner2 != null)
        return inner2;
    }
    pos += childA.nodeSize;
  }
}
function findDiffEnd(a2, b2, posA, posB) {
  for (let iA = a2.childCount, iB = b2.childCount; ; ) {
    if (iA == 0 || iB == 0)
      return iA == iB ? null : { a: posA, b: posB };
    let childA = a2.child(--iA), childB = b2.child(--iB), size = childA.nodeSize;
    if (childA == childB) {
      posA -= size;
      posB -= size;
      continue;
    }
    if (!childA.sameMarkup(childB))
      return { a: posA, b: posB };
    if (childA.isText && childA.text != childB.text) {
      let same = 0, minSize = Math.min(childA.text.length, childB.text.length);
      while (same < minSize && childA.text[childA.text.length - same - 1] == childB.text[childB.text.length - same - 1]) {
        same++;
        posA--;
        posB--;
      }
      return { a: posA, b: posB };
    }
    if (childA.content.size || childB.content.size) {
      let inner2 = findDiffEnd(childA.content, childB.content, posA - 1, posB - 1);
      if (inner2)
        return inner2;
    }
    posA -= size;
    posB -= size;
  }
}
var Fragment = class _Fragment {
  /**
  @internal
  */
  constructor(content, size) {
    this.content = content;
    this.size = size || 0;
    if (size == null)
      for (let i = 0; i < content.length; i++)
        this.size += content[i].nodeSize;
  }
  /**
  Invoke a callback for all descendant nodes between the given two
  positions (relative to start of this fragment). Doesn't descend
  into a node when the callback returns `false`.
  */
  nodesBetween(from2, to, f, nodeStart = 0, parent) {
    for (let i = 0, pos = 0; pos < to; i++) {
      let child = this.content[i], end = pos + child.nodeSize;
      if (end > from2 && f(child, nodeStart + pos, parent || null, i) !== false && child.content.size) {
        let start = pos + 1;
        child.nodesBetween(Math.max(0, from2 - start), Math.min(child.content.size, to - start), f, nodeStart + start);
      }
      pos = end;
    }
  }
  /**
  Call the given callback for every descendant node. `pos` will be
  relative to the start of the fragment. The callback may return
  `false` to prevent traversal of a given node's children.
  */
  descendants(f) {
    this.nodesBetween(0, this.size, f);
  }
  /**
  Extract the text between `from` and `to`. See the same method on
  [`Node`](https://prosemirror.net/docs/ref/#model.Node.textBetween).
  */
  textBetween(from2, to, blockSeparator, leafText) {
    let text5 = "", first2 = true;
    this.nodesBetween(from2, to, (node, pos) => {
      let nodeText = node.isText ? node.text.slice(Math.max(from2, pos) - pos, to - pos) : !node.isLeaf ? "" : leafText ? typeof leafText === "function" ? leafText(node) : leafText : node.type.spec.leafText ? node.type.spec.leafText(node) : "";
      if (node.isBlock && (node.isLeaf && nodeText || node.isTextblock) && blockSeparator) {
        if (first2)
          first2 = false;
        else
          text5 += blockSeparator;
      }
      text5 += nodeText;
    }, 0);
    return text5;
  }
  /**
  Create a new fragment containing the combined content of this
  fragment and the other.
  */
  append(other) {
    if (!other.size)
      return this;
    if (!this.size)
      return other;
    let last = this.lastChild, first2 = other.firstChild, content = this.content.slice(), i = 0;
    if (last.isText && last.sameMarkup(first2)) {
      content[content.length - 1] = last.withText(last.text + first2.text);
      i = 1;
    }
    for (; i < other.content.length; i++)
      content.push(other.content[i]);
    return new _Fragment(content, this.size + other.size);
  }
  /**
  Cut out the sub-fragment between the two given positions.
  */
  cut(from2, to = this.size) {
    if (from2 == 0 && to == this.size)
      return this;
    let result = [], size = 0;
    if (to > from2)
      for (let i = 0, pos = 0; pos < to; i++) {
        let child = this.content[i], end = pos + child.nodeSize;
        if (end > from2) {
          if (pos < from2 || end > to) {
            if (child.isText)
              child = child.cut(Math.max(0, from2 - pos), Math.min(child.text.length, to - pos));
            else
              child = child.cut(Math.max(0, from2 - pos - 1), Math.min(child.content.size, to - pos - 1));
          }
          result.push(child);
          size += child.nodeSize;
        }
        pos = end;
      }
    return new _Fragment(result, size);
  }
  /**
  @internal
  */
  cutByIndex(from2, to) {
    if (from2 == to)
      return _Fragment.empty;
    if (from2 == 0 && to == this.content.length)
      return this;
    return new _Fragment(this.content.slice(from2, to));
  }
  /**
  Create a new fragment in which the node at the given index is
  replaced by the given node.
  */
  replaceChild(index, node) {
    let current = this.content[index];
    if (current == node)
      return this;
    let copy3 = this.content.slice();
    let size = this.size + node.nodeSize - current.nodeSize;
    copy3[index] = node;
    return new _Fragment(copy3, size);
  }
  /**
  Create a new fragment by prepending the given node to this
  fragment.
  */
  addToStart(node) {
    return new _Fragment([node].concat(this.content), this.size + node.nodeSize);
  }
  /**
  Create a new fragment by appending the given node to this
  fragment.
  */
  addToEnd(node) {
    return new _Fragment(this.content.concat(node), this.size + node.nodeSize);
  }
  /**
  Compare this fragment to another one.
  */
  eq(other) {
    if (this.content.length != other.content.length)
      return false;
    for (let i = 0; i < this.content.length; i++)
      if (!this.content[i].eq(other.content[i]))
        return false;
    return true;
  }
  /**
  The first child of the fragment, or `null` if it is empty.
  */
  get firstChild() {
    return this.content.length ? this.content[0] : null;
  }
  /**
  The last child of the fragment, or `null` if it is empty.
  */
  get lastChild() {
    return this.content.length ? this.content[this.content.length - 1] : null;
  }
  /**
  The number of child nodes in this fragment.
  */
  get childCount() {
    return this.content.length;
  }
  /**
  Get the child node at the given index. Raise an error when the
  index is out of range.
  */
  child(index) {
    let found2 = this.content[index];
    if (!found2)
      throw new RangeError("Index " + index + " out of range for " + this);
    return found2;
  }
  /**
  Get the child node at the given index, if it exists.
  */
  maybeChild(index) {
    return this.content[index] || null;
  }
  /**
  Call `f` for every child node, passing the node, its offset
  into this parent node, and its index.
  */
  forEach(f) {
    for (let i = 0, p2 = 0; i < this.content.length; i++) {
      let child = this.content[i];
      f(child, p2, i);
      p2 += child.nodeSize;
    }
  }
  /**
  Find the first position at which this fragment and another
  fragment differ, or `null` if they are the same.
  */
  findDiffStart(other, pos = 0) {
    return findDiffStart(this, other, pos);
  }
  /**
  Find the first position, searching from the end, at which this
  fragment and the given fragment differ, or `null` if they are
  the same. Since this position will not be the same in both
  nodes, an object with two separate positions is returned.
  */
  findDiffEnd(other, pos = this.size, otherPos = other.size) {
    return findDiffEnd(this, other, pos, otherPos);
  }
  /**
  Find the index and inner offset corresponding to a given relative
  position in this fragment. The result object will be reused
  (overwritten) the next time the function is called. @internal
  */
  findIndex(pos) {
    if (pos == 0)
      return retIndex(0, pos);
    if (pos == this.size)
      return retIndex(this.content.length, pos);
    if (pos > this.size || pos < 0)
      throw new RangeError(`Position ${pos} outside of fragment (${this})`);
    for (let i = 0, curPos = 0; ; i++) {
      let cur = this.child(i), end = curPos + cur.nodeSize;
      if (end >= pos) {
        if (end == pos)
          return retIndex(i + 1, end);
        return retIndex(i, curPos);
      }
      curPos = end;
    }
  }
  /**
  Return a debugging string that describes this fragment.
  */
  toString() {
    return "<" + this.toStringInner() + ">";
  }
  /**
  @internal
  */
  toStringInner() {
    return this.content.join(", ");
  }
  /**
  Create a JSON-serializeable representation of this fragment.
  */
  toJSON() {
    return this.content.length ? this.content.map((n) => n.toJSON()) : null;
  }
  /**
  Deserialize a fragment from its JSON representation.
  */
  static fromJSON(schema, value) {
    if (!value)
      return _Fragment.empty;
    if (!Array.isArray(value))
      throw new RangeError("Invalid input for Fragment.fromJSON");
    return new _Fragment(value.map(schema.nodeFromJSON));
  }
  /**
  Build a fragment from an array of nodes. Ensures that adjacent
  text nodes with the same marks are joined together.
  */
  static fromArray(array) {
    if (!array.length)
      return _Fragment.empty;
    let joined, size = 0;
    for (let i = 0; i < array.length; i++) {
      let node = array[i];
      size += node.nodeSize;
      if (i && node.isText && array[i - 1].sameMarkup(node)) {
        if (!joined)
          joined = array.slice(0, i);
        joined[joined.length - 1] = node.withText(joined[joined.length - 1].text + node.text);
      } else if (joined) {
        joined.push(node);
      }
    }
    return new _Fragment(joined || array, size);
  }
  /**
  Create a fragment from something that can be interpreted as a
  set of nodes. For `null`, it returns the empty fragment. For a
  fragment, the fragment itself. For a node or array of nodes, a
  fragment containing those nodes.
  */
  static from(nodes) {
    if (!nodes)
      return _Fragment.empty;
    if (nodes instanceof _Fragment)
      return nodes;
    if (Array.isArray(nodes))
      return this.fromArray(nodes);
    if (nodes.attrs)
      return new _Fragment([nodes], nodes.nodeSize);
    throw new RangeError("Can not convert " + nodes + " to a Fragment" + (nodes.nodesBetween ? " (looks like multiple versions of prosemirror-model were loaded)" : ""));
  }
};
Fragment.empty = new Fragment([], 0);
var found = { index: 0, offset: 0 };
function retIndex(index, offset) {
  found.index = index;
  found.offset = offset;
  return found;
}
function compareDeep(a2, b2) {
  if (a2 === b2)
    return true;
  if (!(a2 && typeof a2 == "object") || !(b2 && typeof b2 == "object"))
    return false;
  let array = Array.isArray(a2);
  if (Array.isArray(b2) != array)
    return false;
  if (array) {
    if (a2.length != b2.length)
      return false;
    for (let i = 0; i < a2.length; i++)
      if (!compareDeep(a2[i], b2[i]))
        return false;
  } else {
    for (let p2 in a2)
      if (!(p2 in b2) || !compareDeep(a2[p2], b2[p2]))
        return false;
    for (let p2 in b2)
      if (!(p2 in a2))
        return false;
  }
  return true;
}
var Mark = class _Mark2 {
  /**
  @internal
  */
  constructor(type, attrs) {
    this.type = type;
    this.attrs = attrs;
  }
  /**
  Given a set of marks, create a new set which contains this one as
  well, in the right position. If this mark is already in the set,
  the set itself is returned. If any marks that are set to be
  [exclusive](https://prosemirror.net/docs/ref/#model.MarkSpec.excludes) with this mark are present,
  those are replaced by this one.
  */
  addToSet(set) {
    let copy3, placed = false;
    for (let i = 0; i < set.length; i++) {
      let other = set[i];
      if (this.eq(other))
        return set;
      if (this.type.excludes(other.type)) {
        if (!copy3)
          copy3 = set.slice(0, i);
      } else if (other.type.excludes(this.type)) {
        return set;
      } else {
        if (!placed && other.type.rank > this.type.rank) {
          if (!copy3)
            copy3 = set.slice(0, i);
          copy3.push(this);
          placed = true;
        }
        if (copy3)
          copy3.push(other);
      }
    }
    if (!copy3)
      copy3 = set.slice();
    if (!placed)
      copy3.push(this);
    return copy3;
  }
  /**
  Remove this mark from the given set, returning a new set. If this
  mark is not in the set, the set itself is returned.
  */
  removeFromSet(set) {
    for (let i = 0; i < set.length; i++)
      if (this.eq(set[i]))
        return set.slice(0, i).concat(set.slice(i + 1));
    return set;
  }
  /**
  Test whether this mark is in the given set of marks.
  */
  isInSet(set) {
    for (let i = 0; i < set.length; i++)
      if (this.eq(set[i]))
        return true;
    return false;
  }
  /**
  Test whether this mark has the same type and attributes as
  another mark.
  */
  eq(other) {
    return this == other || this.type == other.type && compareDeep(this.attrs, other.attrs);
  }
  /**
  Convert this mark to a JSON-serializeable representation.
  */
  toJSON() {
    let obj = { type: this.type.name };
    for (let _10 in this.attrs) {
      obj.attrs = this.attrs;
      break;
    }
    return obj;
  }
  /**
  Deserialize a mark from JSON.
  */
  static fromJSON(schema, json) {
    if (!json)
      throw new RangeError("Invalid input for Mark.fromJSON");
    let type = schema.marks[json.type];
    if (!type)
      throw new RangeError(`There is no mark type ${json.type} in this schema`);
    let mark = type.create(json.attrs);
    type.checkAttrs(mark.attrs);
    return mark;
  }
  /**
  Test whether two sets of marks are identical.
  */
  static sameSet(a2, b2) {
    if (a2 == b2)
      return true;
    if (a2.length != b2.length)
      return false;
    for (let i = 0; i < a2.length; i++)
      if (!a2[i].eq(b2[i]))
        return false;
    return true;
  }
  /**
  Create a properly sorted mark set from null, a single mark, or an
  unsorted array of marks.
  */
  static setFrom(marks) {
    if (!marks || Array.isArray(marks) && marks.length == 0)
      return _Mark2.none;
    if (marks instanceof _Mark2)
      return [marks];
    let copy3 = marks.slice();
    copy3.sort((a2, b2) => a2.type.rank - b2.type.rank);
    return copy3;
  }
};
Mark.none = [];
var ReplaceError = class extends Error {
};
var Slice = class _Slice {
  /**
  Create a slice. When specifying a non-zero open depth, you must
  make sure that there are nodes of at least that depth at the
  appropriate side of the fragment—i.e. if the fragment is an
  empty paragraph node, `openStart` and `openEnd` can't be greater
  than 1.
  
  It is not necessary for the content of open nodes to conform to
  the schema's content constraints, though it should be a valid
  start/end/middle for such a node, depending on which sides are
  open.
  */
  constructor(content, openStart, openEnd) {
    this.content = content;
    this.openStart = openStart;
    this.openEnd = openEnd;
  }
  /**
  The size this slice would add when inserted into a document.
  */
  get size() {
    return this.content.size - this.openStart - this.openEnd;
  }
  /**
  @internal
  */
  insertAt(pos, fragment) {
    let content = insertInto(this.content, pos + this.openStart, fragment);
    return content && new _Slice(content, this.openStart, this.openEnd);
  }
  /**
  @internal
  */
  removeBetween(from2, to) {
    return new _Slice(removeRange(this.content, from2 + this.openStart, to + this.openStart), this.openStart, this.openEnd);
  }
  /**
  Tests whether this slice is equal to another slice.
  */
  eq(other) {
    return this.content.eq(other.content) && this.openStart == other.openStart && this.openEnd == other.openEnd;
  }
  /**
  @internal
  */
  toString() {
    return this.content + "(" + this.openStart + "," + this.openEnd + ")";
  }
  /**
  Convert a slice to a JSON-serializable representation.
  */
  toJSON() {
    if (!this.content.size)
      return null;
    let json = { content: this.content.toJSON() };
    if (this.openStart > 0)
      json.openStart = this.openStart;
    if (this.openEnd > 0)
      json.openEnd = this.openEnd;
    return json;
  }
  /**
  Deserialize a slice from its JSON representation.
  */
  static fromJSON(schema, json) {
    if (!json)
      return _Slice.empty;
    let openStart = json.openStart || 0, openEnd = json.openEnd || 0;
    if (typeof openStart != "number" || typeof openEnd != "number")
      throw new RangeError("Invalid input for Slice.fromJSON");
    return new _Slice(Fragment.fromJSON(schema, json.content), openStart, openEnd);
  }
  /**
  Create a slice from a fragment by taking the maximum possible
  open value on both side of the fragment.
  */
  static maxOpen(fragment, openIsolating = true) {
    let openStart = 0, openEnd = 0;
    for (let n = fragment.firstChild; n && !n.isLeaf && (openIsolating || !n.type.spec.isolating); n = n.firstChild)
      openStart++;
    for (let n = fragment.lastChild; n && !n.isLeaf && (openIsolating || !n.type.spec.isolating); n = n.lastChild)
      openEnd++;
    return new _Slice(fragment, openStart, openEnd);
  }
};
Slice.empty = new Slice(Fragment.empty, 0, 0);
function removeRange(content, from2, to) {
  let { index, offset } = content.findIndex(from2), child = content.maybeChild(index);
  let { index: indexTo, offset: offsetTo } = content.findIndex(to);
  if (offset == from2 || child.isText) {
    if (offsetTo != to && !content.child(indexTo).isText)
      throw new RangeError("Removing non-flat range");
    return content.cut(0, from2).append(content.cut(to));
  }
  if (index != indexTo)
    throw new RangeError("Removing non-flat range");
  return content.replaceChild(index, child.copy(removeRange(child.content, from2 - offset - 1, to - offset - 1)));
}
function insertInto(content, dist, insert2, parent) {
  let { index, offset } = content.findIndex(dist), child = content.maybeChild(index);
  if (offset == dist || child.isText) {
    if (parent && !parent.canReplace(index, index, insert2))
      return null;
    return content.cut(0, dist).append(insert2).append(content.cut(dist));
  }
  let inner2 = insertInto(child.content, dist - offset - 1, insert2, child);
  return inner2 && content.replaceChild(index, child.copy(inner2));
}
function replace($from, $to, slice2) {
  if (slice2.openStart > $from.depth)
    throw new ReplaceError("Inserted content deeper than insertion position");
  if ($from.depth - slice2.openStart != $to.depth - slice2.openEnd)
    throw new ReplaceError("Inconsistent open depths");
  return replaceOuter($from, $to, slice2, 0);
}
function replaceOuter($from, $to, slice2, depth) {
  let index = $from.index(depth), node = $from.node(depth);
  if (index == $to.index(depth) && depth < $from.depth - slice2.openStart) {
    let inner2 = replaceOuter($from, $to, slice2, depth + 1);
    return node.copy(node.content.replaceChild(index, inner2));
  } else if (!slice2.content.size) {
    return close(node, replaceTwoWay($from, $to, depth));
  } else if (!slice2.openStart && !slice2.openEnd && $from.depth == depth && $to.depth == depth) {
    let parent = $from.parent, content = parent.content;
    return close(parent, content.cut(0, $from.parentOffset).append(slice2.content).append(content.cut($to.parentOffset)));
  } else {
    let { start, end } = prepareSliceForReplace(slice2, $from);
    return close(node, replaceThreeWay($from, start, end, $to, depth));
  }
}
function checkJoin(main2, sub2) {
  if (!sub2.type.compatibleContent(main2.type))
    throw new ReplaceError("Cannot join " + sub2.type.name + " onto " + main2.type.name);
}
function joinable($before, $after, depth) {
  let node = $before.node(depth);
  checkJoin(node, $after.node(depth));
  return node;
}
function addNode(child, target2) {
  let last = target2.length - 1;
  if (last >= 0 && child.isText && child.sameMarkup(target2[last]))
    target2[last] = child.withText(target2[last].text + child.text);
  else
    target2.push(child);
}
function addRange($start, $end, depth, target2) {
  let node = ($end || $start).node(depth);
  let startIndex = 0, endIndex = $end ? $end.index(depth) : node.childCount;
  if ($start) {
    startIndex = $start.index(depth);
    if ($start.depth > depth) {
      startIndex++;
    } else if ($start.textOffset) {
      addNode($start.nodeAfter, target2);
      startIndex++;
    }
  }
  for (let i = startIndex; i < endIndex; i++)
    addNode(node.child(i), target2);
  if ($end && $end.depth == depth && $end.textOffset)
    addNode($end.nodeBefore, target2);
}
function close(node, content) {
  node.type.checkContent(content);
  return node.copy(content);
}
function replaceThreeWay($from, $start, $end, $to, depth) {
  let openStart = $from.depth > depth && joinable($from, $start, depth + 1);
  let openEnd = $to.depth > depth && joinable($end, $to, depth + 1);
  let content = [];
  addRange(null, $from, depth, content);
  if (openStart && openEnd && $start.index(depth) == $end.index(depth)) {
    checkJoin(openStart, openEnd);
    addNode(close(openStart, replaceThreeWay($from, $start, $end, $to, depth + 1)), content);
  } else {
    if (openStart)
      addNode(close(openStart, replaceTwoWay($from, $start, depth + 1)), content);
    addRange($start, $end, depth, content);
    if (openEnd)
      addNode(close(openEnd, replaceTwoWay($end, $to, depth + 1)), content);
  }
  addRange($to, null, depth, content);
  return new Fragment(content);
}
function replaceTwoWay($from, $to, depth) {
  let content = [];
  addRange(null, $from, depth, content);
  if ($from.depth > depth) {
    let type = joinable($from, $to, depth + 1);
    addNode(close(type, replaceTwoWay($from, $to, depth + 1)), content);
  }
  addRange($to, null, depth, content);
  return new Fragment(content);
}
function prepareSliceForReplace(slice2, $along) {
  let extra = $along.depth - slice2.openStart, parent = $along.node(extra);
  let node = parent.copy(slice2.content);
  for (let i = extra - 1; i >= 0; i--)
    node = $along.node(i).copy(Fragment.from(node));
  return {
    start: node.resolveNoCache(slice2.openStart + extra),
    end: node.resolveNoCache(node.content.size - slice2.openEnd - extra)
  };
}
var ResolvedPos = class _ResolvedPos {
  /**
  @internal
  */
  constructor(pos, path2, parentOffset) {
    this.pos = pos;
    this.path = path2;
    this.parentOffset = parentOffset;
    this.depth = path2.length / 3 - 1;
  }
  /**
  @internal
  */
  resolveDepth(val) {
    if (val == null)
      return this.depth;
    if (val < 0)
      return this.depth + val;
    return val;
  }
  /**
  The parent node that the position points into. Note that even if
  a position points into a text node, that node is not considered
  the parent—text nodes are ‘flat’ in this model, and have no content.
  */
  get parent() {
    return this.node(this.depth);
  }
  /**
  The root node in which the position was resolved.
  */
  get doc() {
    return this.node(0);
  }
  /**
  The ancestor node at the given level. `p.node(p.depth)` is the
  same as `p.parent`.
  */
  node(depth) {
    return this.path[this.resolveDepth(depth) * 3];
  }
  /**
  The index into the ancestor at the given level. If this points
  at the 3rd node in the 2nd paragraph on the top level, for
  example, `p.index(0)` is 1 and `p.index(1)` is 2.
  */
  index(depth) {
    return this.path[this.resolveDepth(depth) * 3 + 1];
  }
  /**
  The index pointing after this position into the ancestor at the
  given level.
  */
  indexAfter(depth) {
    depth = this.resolveDepth(depth);
    return this.index(depth) + (depth == this.depth && !this.textOffset ? 0 : 1);
  }
  /**
  The (absolute) position at the start of the node at the given
  level.
  */
  start(depth) {
    depth = this.resolveDepth(depth);
    return depth == 0 ? 0 : this.path[depth * 3 - 1] + 1;
  }
  /**
  The (absolute) position at the end of the node at the given
  level.
  */
  end(depth) {
    depth = this.resolveDepth(depth);
    return this.start(depth) + this.node(depth).content.size;
  }
  /**
  The (absolute) position directly before the wrapping node at the
  given level, or, when `depth` is `this.depth + 1`, the original
  position.
  */
  before(depth) {
    depth = this.resolveDepth(depth);
    if (!depth)
      throw new RangeError("There is no position before the top-level node");
    return depth == this.depth + 1 ? this.pos : this.path[depth * 3 - 1];
  }
  /**
  The (absolute) position directly after the wrapping node at the
  given level, or the original position when `depth` is `this.depth + 1`.
  */
  after(depth) {
    depth = this.resolveDepth(depth);
    if (!depth)
      throw new RangeError("There is no position after the top-level node");
    return depth == this.depth + 1 ? this.pos : this.path[depth * 3 - 1] + this.path[depth * 3].nodeSize;
  }
  /**
  When this position points into a text node, this returns the
  distance between the position and the start of the text node.
  Will be zero for positions that point between nodes.
  */
  get textOffset() {
    return this.pos - this.path[this.path.length - 1];
  }
  /**
  Get the node directly after the position, if any. If the position
  points into a text node, only the part of that node after the
  position is returned.
  */
  get nodeAfter() {
    let parent = this.parent, index = this.index(this.depth);
    if (index == parent.childCount)
      return null;
    let dOff = this.pos - this.path[this.path.length - 1], child = parent.child(index);
    return dOff ? parent.child(index).cut(dOff) : child;
  }
  /**
  Get the node directly before the position, if any. If the
  position points into a text node, only the part of that node
  before the position is returned.
  */
  get nodeBefore() {
    let index = this.index(this.depth);
    let dOff = this.pos - this.path[this.path.length - 1];
    if (dOff)
      return this.parent.child(index).cut(0, dOff);
    return index == 0 ? null : this.parent.child(index - 1);
  }
  /**
  Get the position at the given index in the parent node at the
  given depth (which defaults to `this.depth`).
  */
  posAtIndex(index, depth) {
    depth = this.resolveDepth(depth);
    let node = this.path[depth * 3], pos = depth == 0 ? 0 : this.path[depth * 3 - 1] + 1;
    for (let i = 0; i < index; i++)
      pos += node.child(i).nodeSize;
    return pos;
  }
  /**
  Get the marks at this position, factoring in the surrounding
  marks' [`inclusive`](https://prosemirror.net/docs/ref/#model.MarkSpec.inclusive) property. If the
  position is at the start of a non-empty node, the marks of the
  node after it (if any) are returned.
  */
  marks() {
    let parent = this.parent, index = this.index();
    if (parent.content.size == 0)
      return Mark.none;
    if (this.textOffset)
      return parent.child(index).marks;
    let main2 = parent.maybeChild(index - 1), other = parent.maybeChild(index);
    if (!main2) {
      let tmp = main2;
      main2 = other;
      other = tmp;
    }
    let marks = main2.marks;
    for (var i = 0; i < marks.length; i++)
      if (marks[i].type.spec.inclusive === false && (!other || !marks[i].isInSet(other.marks)))
        marks = marks[i--].removeFromSet(marks);
    return marks;
  }
  /**
  Get the marks after the current position, if any, except those
  that are non-inclusive and not present at position `$end`. This
  is mostly useful for getting the set of marks to preserve after a
  deletion. Will return `null` if this position is at the end of
  its parent node or its parent node isn't a textblock (in which
  case no marks should be preserved).
  */
  marksAcross($end) {
    let after = this.parent.maybeChild(this.index());
    if (!after || !after.isInline)
      return null;
    let marks = after.marks, next = $end.parent.maybeChild($end.index());
    for (var i = 0; i < marks.length; i++)
      if (marks[i].type.spec.inclusive === false && (!next || !marks[i].isInSet(next.marks)))
        marks = marks[i--].removeFromSet(marks);
    return marks;
  }
  /**
  The depth up to which this position and the given (non-resolved)
  position share the same parent nodes.
  */
  sharedDepth(pos) {
    for (let depth = this.depth; depth > 0; depth--)
      if (this.start(depth) <= pos && this.end(depth) >= pos)
        return depth;
    return 0;
  }
  /**
  Returns a range based on the place where this position and the
  given position diverge around block content. If both point into
  the same textblock, for example, a range around that textblock
  will be returned. If they point into different blocks, the range
  around those blocks in their shared ancestor is returned. You can
  pass in an optional predicate that will be called with a parent
  node to see if a range into that parent is acceptable.
  */
  blockRange(other = this, pred) {
    if (other.pos < this.pos)
      return other.blockRange(this);
    for (let d2 = this.depth - (this.parent.inlineContent || this.pos == other.pos ? 1 : 0); d2 >= 0; d2--)
      if (other.pos <= this.end(d2) && (!pred || pred(this.node(d2))))
        return new NodeRange(this, other, d2);
    return null;
  }
  /**
  Query whether the given position shares the same parent node.
  */
  sameParent(other) {
    return this.pos - this.parentOffset == other.pos - other.parentOffset;
  }
  /**
  Return the greater of this and the given position.
  */
  max(other) {
    return other.pos > this.pos ? other : this;
  }
  /**
  Return the smaller of this and the given position.
  */
  min(other) {
    return other.pos < this.pos ? other : this;
  }
  /**
  @internal
  */
  toString() {
    let str = "";
    for (let i = 1; i <= this.depth; i++)
      str += (str ? "/" : "") + this.node(i).type.name + "_" + this.index(i - 1);
    return str + ":" + this.parentOffset;
  }
  /**
  @internal
  */
  static resolve(doc3, pos) {
    if (!(pos >= 0 && pos <= doc3.content.size))
      throw new RangeError("Position " + pos + " out of range");
    let path2 = [];
    let start = 0, parentOffset = pos;
    for (let node = doc3; ; ) {
      let { index, offset } = node.content.findIndex(parentOffset);
      let rem = parentOffset - offset;
      path2.push(node, index, start + offset);
      if (!rem)
        break;
      node = node.child(index);
      if (node.isText)
        break;
      parentOffset = rem - 1;
      start += offset + 1;
    }
    return new _ResolvedPos(pos, path2, parentOffset);
  }
  /**
  @internal
  */
  static resolveCached(doc3, pos) {
    let cache = resolveCache.get(doc3);
    if (cache) {
      for (let i = 0; i < cache.elts.length; i++) {
        let elt = cache.elts[i];
        if (elt.pos == pos)
          return elt;
      }
    } else {
      resolveCache.set(doc3, cache = new ResolveCache());
    }
    let result = cache.elts[cache.i] = _ResolvedPos.resolve(doc3, pos);
    cache.i = (cache.i + 1) % resolveCacheSize;
    return result;
  }
};
var ResolveCache = class {
  constructor() {
    this.elts = [];
    this.i = 0;
  }
};
var resolveCacheSize = 12;
var resolveCache = /* @__PURE__ */ new WeakMap();
var NodeRange = class {
  /**
  Construct a node range. `$from` and `$to` should point into the
  same node until at least the given `depth`, since a node range
  denotes an adjacent set of nodes in a single parent node.
  */
  constructor($from, $to, depth) {
    this.$from = $from;
    this.$to = $to;
    this.depth = depth;
  }
  /**
  The position at the start of the range.
  */
  get start() {
    return this.$from.before(this.depth + 1);
  }
  /**
  The position at the end of the range.
  */
  get end() {
    return this.$to.after(this.depth + 1);
  }
  /**
  The parent node that the range points into.
  */
  get parent() {
    return this.$from.node(this.depth);
  }
  /**
  The start index of the range in the parent node.
  */
  get startIndex() {
    return this.$from.index(this.depth);
  }
  /**
  The end index of the range in the parent node.
  */
  get endIndex() {
    return this.$to.indexAfter(this.depth);
  }
};
var emptyAttrs = /* @__PURE__ */ Object.create(null);
var Node2 = class _Node2 {
  /**
  @internal
  */
  constructor(type, attrs, content, marks = Mark.none) {
    this.type = type;
    this.attrs = attrs;
    this.marks = marks;
    this.content = content || Fragment.empty;
  }
  /**
  The array of this node's child nodes.
  */
  get children() {
    return this.content.content;
  }
  /**
  The size of this node, as defined by the integer-based [indexing
  scheme](https://prosemirror.net/docs/guide/#doc.indexing). For text nodes, this is the
  amount of characters. For other leaf nodes, it is one. For
  non-leaf nodes, it is the size of the content plus two (the
  start and end token).
  */
  get nodeSize() {
    return this.isLeaf ? 1 : 2 + this.content.size;
  }
  /**
  The number of children that the node has.
  */
  get childCount() {
    return this.content.childCount;
  }
  /**
  Get the child node at the given index. Raises an error when the
  index is out of range.
  */
  child(index) {
    return this.content.child(index);
  }
  /**
  Get the child node at the given index, if it exists.
  */
  maybeChild(index) {
    return this.content.maybeChild(index);
  }
  /**
  Call `f` for every child node, passing the node, its offset
  into this parent node, and its index.
  */
  forEach(f) {
    this.content.forEach(f);
  }
  /**
  Invoke a callback for all descendant nodes recursively between
  the given two positions that are relative to start of this
  node's content. The callback is invoked with the node, its
  position relative to the original node (method receiver),
  its parent node, and its child index. When the callback returns
  false for a given node, that node's children will not be
  recursed over. The last parameter can be used to specify a
  starting position to count from.
  */
  nodesBetween(from2, to, f, startPos = 0) {
    this.content.nodesBetween(from2, to, f, startPos, this);
  }
  /**
  Call the given callback for every descendant node. Doesn't
  descend into a node when the callback returns `false`.
  */
  descendants(f) {
    this.nodesBetween(0, this.content.size, f);
  }
  /**
  Concatenates all the text nodes found in this fragment and its
  children.
  */
  get textContent() {
    return this.isLeaf && this.type.spec.leafText ? this.type.spec.leafText(this) : this.textBetween(0, this.content.size, "");
  }
  /**
  Get all text between positions `from` and `to`. When
  `blockSeparator` is given, it will be inserted to separate text
  from different block nodes. If `leafText` is given, it'll be
  inserted for every non-text leaf node encountered, otherwise
  [`leafText`](https://prosemirror.net/docs/ref/#model.NodeSpec.leafText) will be used.
  */
  textBetween(from2, to, blockSeparator, leafText) {
    return this.content.textBetween(from2, to, blockSeparator, leafText);
  }
  /**
  Returns this node's first child, or `null` if there are no
  children.
  */
  get firstChild() {
    return this.content.firstChild;
  }
  /**
  Returns this node's last child, or `null` if there are no
  children.
  */
  get lastChild() {
    return this.content.lastChild;
  }
  /**
  Test whether two nodes represent the same piece of document.
  */
  eq(other) {
    return this == other || this.sameMarkup(other) && this.content.eq(other.content);
  }
  /**
  Compare the markup (type, attributes, and marks) of this node to
  those of another. Returns `true` if both have the same markup.
  */
  sameMarkup(other) {
    return this.hasMarkup(other.type, other.attrs, other.marks);
  }
  /**
  Check whether this node's markup correspond to the given type,
  attributes, and marks.
  */
  hasMarkup(type, attrs, marks) {
    return this.type == type && compareDeep(this.attrs, attrs || type.defaultAttrs || emptyAttrs) && Mark.sameSet(this.marks, marks || Mark.none);
  }
  /**
  Create a new node with the same markup as this node, containing
  the given content (or empty, if no content is given).
  */
  copy(content = null) {
    if (content == this.content)
      return this;
    return new _Node2(this.type, this.attrs, content, this.marks);
  }
  /**
  Create a copy of this node, with the given set of marks instead
  of the node's own marks.
  */
  mark(marks) {
    return marks == this.marks ? this : new _Node2(this.type, this.attrs, this.content, marks);
  }
  /**
  Create a copy of this node with only the content between the
  given positions. If `to` is not given, it defaults to the end of
  the node.
  */
  cut(from2, to = this.content.size) {
    if (from2 == 0 && to == this.content.size)
      return this;
    return this.copy(this.content.cut(from2, to));
  }
  /**
  Cut out the part of the document between the given positions, and
  return it as a `Slice` object.
  */
  slice(from2, to = this.content.size, includeParents = false) {
    if (from2 == to)
      return Slice.empty;
    let $from = this.resolve(from2), $to = this.resolve(to);
    let depth = includeParents ? 0 : $from.sharedDepth(to);
    let start = $from.start(depth), node = $from.node(depth);
    let content = node.content.cut($from.pos - start, $to.pos - start);
    return new Slice(content, $from.depth - depth, $to.depth - depth);
  }
  /**
  Replace the part of the document between the given positions with
  the given slice. The slice must 'fit', meaning its open sides
  must be able to connect to the surrounding content, and its
  content nodes must be valid children for the node they are placed
  into. If any of this is violated, an error of type
  [`ReplaceError`](https://prosemirror.net/docs/ref/#model.ReplaceError) is thrown.
  */
  replace(from2, to, slice2) {
    return replace(this.resolve(from2), this.resolve(to), slice2);
  }
  /**
  Find the node directly after the given position.
  */
  nodeAt(pos) {
    for (let node = this; ; ) {
      let { index, offset } = node.content.findIndex(pos);
      node = node.maybeChild(index);
      if (!node)
        return null;
      if (offset == pos || node.isText)
        return node;
      pos -= offset + 1;
    }
  }
  /**
  Find the (direct) child node after the given offset, if any,
  and return it along with its index and offset relative to this
  node.
  */
  childAfter(pos) {
    let { index, offset } = this.content.findIndex(pos);
    return { node: this.content.maybeChild(index), index, offset };
  }
  /**
  Find the (direct) child node before the given offset, if any,
  and return it along with its index and offset relative to this
  node.
  */
  childBefore(pos) {
    if (pos == 0)
      return { node: null, index: 0, offset: 0 };
    let { index, offset } = this.content.findIndex(pos);
    if (offset < pos)
      return { node: this.content.child(index), index, offset };
    let node = this.content.child(index - 1);
    return { node, index: index - 1, offset: offset - node.nodeSize };
  }
  /**
  Resolve the given position in the document, returning an
  [object](https://prosemirror.net/docs/ref/#model.ResolvedPos) with information about its context.
  */
  resolve(pos) {
    return ResolvedPos.resolveCached(this, pos);
  }
  /**
  @internal
  */
  resolveNoCache(pos) {
    return ResolvedPos.resolve(this, pos);
  }
  /**
  Test whether a given mark or mark type occurs in this document
  between the two given positions.
  */
  rangeHasMark(from2, to, type) {
    let found2 = false;
    if (to > from2)
      this.nodesBetween(from2, to, (node) => {
        if (type.isInSet(node.marks))
          found2 = true;
        return !found2;
      });
    return found2;
  }
  /**
  True when this is a block (non-inline node)
  */
  get isBlock() {
    return this.type.isBlock;
  }
  /**
  True when this is a textblock node, a block node with inline
  content.
  */
  get isTextblock() {
    return this.type.isTextblock;
  }
  /**
  True when this node allows inline content.
  */
  get inlineContent() {
    return this.type.inlineContent;
  }
  /**
  True when this is an inline node (a text node or a node that can
  appear among text).
  */
  get isInline() {
    return this.type.isInline;
  }
  /**
  True when this is a text node.
  */
  get isText() {
    return this.type.isText;
  }
  /**
  True when this is a leaf node.
  */
  get isLeaf() {
    return this.type.isLeaf;
  }
  /**
  True when this is an atom, i.e. when it does not have directly
  editable content. This is usually the same as `isLeaf`, but can
  be configured with the [`atom` property](https://prosemirror.net/docs/ref/#model.NodeSpec.atom)
  on a node's spec (typically used when the node is displayed as
  an uneditable [node view](https://prosemirror.net/docs/ref/#view.NodeView)).
  */
  get isAtom() {
    return this.type.isAtom;
  }
  /**
  Return a string representation of this node for debugging
  purposes.
  */
  toString() {
    if (this.type.spec.toDebugString)
      return this.type.spec.toDebugString(this);
    let name = this.type.name;
    if (this.content.size)
      name += "(" + this.content.toStringInner() + ")";
    return wrapMarks(this.marks, name);
  }
  /**
  Get the content match in this node at the given index.
  */
  contentMatchAt(index) {
    let match = this.type.contentMatch.matchFragment(this.content, 0, index);
    if (!match)
      throw new Error("Called contentMatchAt on a node with invalid content");
    return match;
  }
  /**
  Test whether replacing the range between `from` and `to` (by
  child index) with the given replacement fragment (which defaults
  to the empty fragment) would leave the node's content valid. You
  can optionally pass `start` and `end` indices into the
  replacement fragment.
  */
  canReplace(from2, to, replacement = Fragment.empty, start = 0, end = replacement.childCount) {
    let one = this.contentMatchAt(from2).matchFragment(replacement, start, end);
    let two = one && one.matchFragment(this.content, to);
    if (!two || !two.validEnd)
      return false;
    for (let i = start; i < end; i++)
      if (!this.type.allowsMarks(replacement.child(i).marks))
        return false;
    return true;
  }
  /**
  Test whether replacing the range `from` to `to` (by index) with
  a node of the given type would leave the node's content valid.
  */
  canReplaceWith(from2, to, type, marks) {
    if (marks && !this.type.allowsMarks(marks))
      return false;
    let start = this.contentMatchAt(from2).matchType(type);
    let end = start && start.matchFragment(this.content, to);
    return end ? end.validEnd : false;
  }
  /**
  Test whether the given node's content could be appended to this
  node. If that node is empty, this will only return true if there
  is at least one node type that can appear in both nodes (to avoid
  merging completely incompatible nodes).
  */
  canAppend(other) {
    if (other.content.size)
      return this.canReplace(this.childCount, this.childCount, other.content);
    else
      return this.type.compatibleContent(other.type);
  }
  /**
  Check whether this node and its descendants conform to the
  schema, and raise an exception when they do not.
  */
  check() {
    this.type.checkContent(this.content);
    this.type.checkAttrs(this.attrs);
    let copy3 = Mark.none;
    for (let i = 0; i < this.marks.length; i++) {
      let mark = this.marks[i];
      mark.type.checkAttrs(mark.attrs);
      copy3 = mark.addToSet(copy3);
    }
    if (!Mark.sameSet(copy3, this.marks))
      throw new RangeError(`Invalid collection of marks for node ${this.type.name}: ${this.marks.map((m) => m.type.name)}`);
    this.content.forEach((node) => node.check());
  }
  /**
  Return a JSON-serializeable representation of this node.
  */
  toJSON() {
    let obj = { type: this.type.name };
    for (let _10 in this.attrs) {
      obj.attrs = this.attrs;
      break;
    }
    if (this.content.size)
      obj.content = this.content.toJSON();
    if (this.marks.length)
      obj.marks = this.marks.map((n) => n.toJSON());
    return obj;
  }
  /**
  Deserialize a node from its JSON representation.
  */
  static fromJSON(schema, json) {
    if (!json)
      throw new RangeError("Invalid input for Node.fromJSON");
    let marks = void 0;
    if (json.marks) {
      if (!Array.isArray(json.marks))
        throw new RangeError("Invalid mark data for Node.fromJSON");
      marks = json.marks.map(schema.markFromJSON);
    }
    if (json.type == "text") {
      if (typeof json.text != "string")
        throw new RangeError("Invalid text node in JSON");
      return schema.text(json.text, marks);
    }
    let content = Fragment.fromJSON(schema, json.content);
    let node = schema.nodeType(json.type).create(json.attrs, content, marks);
    node.type.checkAttrs(node.attrs);
    return node;
  }
};
Node2.prototype.text = void 0;
var TextNode = class _TextNode extends Node2 {
  /**
  @internal
  */
  constructor(type, attrs, content, marks) {
    super(type, attrs, null, marks);
    if (!content)
      throw new RangeError("Empty text nodes are not allowed");
    this.text = content;
  }
  toString() {
    if (this.type.spec.toDebugString)
      return this.type.spec.toDebugString(this);
    return wrapMarks(this.marks, JSON.stringify(this.text));
  }
  get textContent() {
    return this.text;
  }
  textBetween(from2, to) {
    return this.text.slice(from2, to);
  }
  get nodeSize() {
    return this.text.length;
  }
  mark(marks) {
    return marks == this.marks ? this : new _TextNode(this.type, this.attrs, this.text, marks);
  }
  withText(text5) {
    if (text5 == this.text)
      return this;
    return new _TextNode(this.type, this.attrs, text5, this.marks);
  }
  cut(from2 = 0, to = this.text.length) {
    if (from2 == 0 && to == this.text.length)
      return this;
    return this.withText(this.text.slice(from2, to));
  }
  eq(other) {
    return this.sameMarkup(other) && this.text == other.text;
  }
  toJSON() {
    let base2 = super.toJSON();
    base2.text = this.text;
    return base2;
  }
};
function wrapMarks(marks, str) {
  for (let i = marks.length - 1; i >= 0; i--)
    str = marks[i].type.name + "(" + str + ")";
  return str;
}
var ContentMatch = class _ContentMatch {
  /**
  @internal
  */
  constructor(validEnd) {
    this.validEnd = validEnd;
    this.next = [];
    this.wrapCache = [];
  }
  /**
  @internal
  */
  static parse(string, nodeTypes) {
    let stream = new TokenStream(string, nodeTypes);
    if (stream.next == null)
      return _ContentMatch.empty;
    let expr = parseExpr(stream);
    if (stream.next)
      stream.err("Unexpected trailing text");
    let match = dfa(nfa(expr));
    checkForDeadEnds(match, stream);
    return match;
  }
  /**
  Match a node type, returning a match after that node if
  successful.
  */
  matchType(type) {
    for (let i = 0; i < this.next.length; i++)
      if (this.next[i].type == type)
        return this.next[i].next;
    return null;
  }
  /**
  Try to match a fragment. Returns the resulting match when
  successful.
  */
  matchFragment(frag, start = 0, end = frag.childCount) {
    let cur = this;
    for (let i = start; cur && i < end; i++)
      cur = cur.matchType(frag.child(i).type);
    return cur;
  }
  /**
  @internal
  */
  get inlineContent() {
    return this.next.length != 0 && this.next[0].type.isInline;
  }
  /**
  Get the first matching node type at this match position that can
  be generated.
  */
  get defaultType() {
    for (let i = 0; i < this.next.length; i++) {
      let { type } = this.next[i];
      if (!(type.isText || type.hasRequiredAttrs()))
        return type;
    }
    return null;
  }
  /**
  @internal
  */
  compatible(other) {
    for (let i = 0; i < this.next.length; i++)
      for (let j = 0; j < other.next.length; j++)
        if (this.next[i].type == other.next[j].type)
          return true;
    return false;
  }
  /**
  Try to match the given fragment, and if that fails, see if it can
  be made to match by inserting nodes in front of it. When
  successful, return a fragment of inserted nodes (which may be
  empty if nothing had to be inserted). When `toEnd` is true, only
  return a fragment if the resulting match goes to the end of the
  content expression.
  */
  fillBefore(after, toEnd = false, startIndex = 0) {
    let seen = [this];
    function search(match, types) {
      let finished = match.matchFragment(after, startIndex);
      if (finished && (!toEnd || finished.validEnd))
        return Fragment.from(types.map((tp) => tp.createAndFill()));
      for (let i = 0; i < match.next.length; i++) {
        let { type, next } = match.next[i];
        if (!(type.isText || type.hasRequiredAttrs()) && seen.indexOf(next) == -1) {
          seen.push(next);
          let found2 = search(next, types.concat(type));
          if (found2)
            return found2;
        }
      }
      return null;
    }
    return search(this, []);
  }
  /**
  Find a set of wrapping node types that would allow a node of the
  given type to appear at this position. The result may be empty
  (when it fits directly) and will be null when no such wrapping
  exists.
  */
  findWrapping(target2) {
    for (let i = 0; i < this.wrapCache.length; i += 2)
      if (this.wrapCache[i] == target2)
        return this.wrapCache[i + 1];
    let computed = this.computeWrapping(target2);
    this.wrapCache.push(target2, computed);
    return computed;
  }
  /**
  @internal
  */
  computeWrapping(target2) {
    let seen = /* @__PURE__ */ Object.create(null), active = [{ match: this, type: null, via: null }];
    while (active.length) {
      let current = active.shift(), match = current.match;
      if (match.matchType(target2)) {
        let result = [];
        for (let obj = current; obj.type; obj = obj.via)
          result.push(obj.type);
        return result.reverse();
      }
      for (let i = 0; i < match.next.length; i++) {
        let { type, next } = match.next[i];
        if (!type.isLeaf && !type.hasRequiredAttrs() && !(type.name in seen) && (!current.type || next.validEnd)) {
          active.push({ match: type.contentMatch, type, via: current });
          seen[type.name] = true;
        }
      }
    }
    return null;
  }
  /**
  The number of outgoing edges this node has in the finite
  automaton that describes the content expression.
  */
  get edgeCount() {
    return this.next.length;
  }
  /**
  Get the _n_​th outgoing edge from this node in the finite
  automaton that describes the content expression.
  */
  edge(n) {
    if (n >= this.next.length)
      throw new RangeError(`There's no ${n}th edge in this content match`);
    return this.next[n];
  }
  /**
  @internal
  */
  toString() {
    let seen = [];
    function scan(m) {
      seen.push(m);
      for (let i = 0; i < m.next.length; i++)
        if (seen.indexOf(m.next[i].next) == -1)
          scan(m.next[i].next);
    }
    scan(this);
    return seen.map((m, i) => {
      let out = i + (m.validEnd ? "*" : " ") + " ";
      for (let i2 = 0; i2 < m.next.length; i2++)
        out += (i2 ? ", " : "") + m.next[i2].type.name + "->" + seen.indexOf(m.next[i2].next);
      return out;
    }).join("\n");
  }
};
ContentMatch.empty = new ContentMatch(true);
var TokenStream = class {
  constructor(string, nodeTypes) {
    this.string = string;
    this.nodeTypes = nodeTypes;
    this.inline = null;
    this.pos = 0;
    this.tokens = string.split(/\s*(?=\b|\W|$)/);
    if (this.tokens[this.tokens.length - 1] == "")
      this.tokens.pop();
    if (this.tokens[0] == "")
      this.tokens.shift();
  }
  get next() {
    return this.tokens[this.pos];
  }
  eat(tok) {
    return this.next == tok && (this.pos++ || true);
  }
  err(str) {
    throw new SyntaxError(str + " (in content expression '" + this.string + "')");
  }
};
function parseExpr(stream) {
  let exprs = [];
  do {
    exprs.push(parseExprSeq(stream));
  } while (stream.eat("|"));
  return exprs.length == 1 ? exprs[0] : { type: "choice", exprs };
}
function parseExprSeq(stream) {
  let exprs = [];
  do {
    exprs.push(parseExprSubscript(stream));
  } while (stream.next && stream.next != ")" && stream.next != "|");
  return exprs.length == 1 ? exprs[0] : { type: "seq", exprs };
}
function parseExprSubscript(stream) {
  let expr = parseExprAtom(stream);
  for (; ; ) {
    if (stream.eat("+"))
      expr = { type: "plus", expr };
    else if (stream.eat("*"))
      expr = { type: "star", expr };
    else if (stream.eat("?"))
      expr = { type: "opt", expr };
    else if (stream.eat("{"))
      expr = parseExprRange(stream, expr);
    else
      break;
  }
  return expr;
}
function parseNum(stream) {
  if (/\D/.test(stream.next))
    stream.err("Expected number, got '" + stream.next + "'");
  let result = Number(stream.next);
  stream.pos++;
  return result;
}
function parseExprRange(stream, expr) {
  let min = parseNum(stream), max = min;
  if (stream.eat(",")) {
    if (stream.next != "}")
      max = parseNum(stream);
    else
      max = -1;
  }
  if (!stream.eat("}"))
    stream.err("Unclosed braced range");
  return { type: "range", min, max, expr };
}
function resolveName(stream, name) {
  let types = stream.nodeTypes, type = types[name];
  if (type)
    return [type];
  let result = [];
  for (let typeName in types) {
    let type2 = types[typeName];
    if (type2.isInGroup(name))
      result.push(type2);
  }
  if (result.length == 0)
    stream.err("No node type or group '" + name + "' found");
  return result;
}
function parseExprAtom(stream) {
  if (stream.eat("(")) {
    let expr = parseExpr(stream);
    if (!stream.eat(")"))
      stream.err("Missing closing paren");
    return expr;
  } else if (!/\W/.test(stream.next)) {
    let exprs = resolveName(stream, stream.next).map((type) => {
      if (stream.inline == null)
        stream.inline = type.isInline;
      else if (stream.inline != type.isInline)
        stream.err("Mixing inline and block content");
      return { type: "name", value: type };
    });
    stream.pos++;
    return exprs.length == 1 ? exprs[0] : { type: "choice", exprs };
  } else {
    stream.err("Unexpected token '" + stream.next + "'");
  }
}
function nfa(expr) {
  let nfa2 = [[]];
  connect(compile(expr, 0), node());
  return nfa2;
  function node() {
    return nfa2.push([]) - 1;
  }
  function edge(from2, to, term) {
    let edge2 = { term, to };
    nfa2[from2].push(edge2);
    return edge2;
  }
  function connect(edges, to) {
    edges.forEach((edge2) => edge2.to = to);
  }
  function compile(expr2, from2) {
    if (expr2.type == "choice") {
      return expr2.exprs.reduce((out, expr3) => out.concat(compile(expr3, from2)), []);
    } else if (expr2.type == "seq") {
      for (let i = 0; ; i++) {
        let next = compile(expr2.exprs[i], from2);
        if (i == expr2.exprs.length - 1)
          return next;
        connect(next, from2 = node());
      }
    } else if (expr2.type == "star") {
      let loop = node();
      edge(from2, loop);
      connect(compile(expr2.expr, loop), loop);
      return [edge(loop)];
    } else if (expr2.type == "plus") {
      let loop = node();
      connect(compile(expr2.expr, from2), loop);
      connect(compile(expr2.expr, loop), loop);
      return [edge(loop)];
    } else if (expr2.type == "opt") {
      return [edge(from2)].concat(compile(expr2.expr, from2));
    } else if (expr2.type == "range") {
      let cur = from2;
      for (let i = 0; i < expr2.min; i++) {
        let next = node();
        connect(compile(expr2.expr, cur), next);
        cur = next;
      }
      if (expr2.max == -1) {
        connect(compile(expr2.expr, cur), cur);
      } else {
        for (let i = expr2.min; i < expr2.max; i++) {
          let next = node();
          edge(cur, next);
          connect(compile(expr2.expr, cur), next);
          cur = next;
        }
      }
      return [edge(cur)];
    } else if (expr2.type == "name") {
      return [edge(from2, void 0, expr2.value)];
    } else {
      throw new Error("Unknown expr type");
    }
  }
}
function cmp(a2, b2) {
  return b2 - a2;
}
function nullFrom(nfa2, node) {
  let result = [];
  scan(node);
  return result.sort(cmp);
  function scan(node2) {
    let edges = nfa2[node2];
    if (edges.length == 1 && !edges[0].term)
      return scan(edges[0].to);
    result.push(node2);
    for (let i = 0; i < edges.length; i++) {
      let { term, to } = edges[i];
      if (!term && result.indexOf(to) == -1)
        scan(to);
    }
  }
}
function dfa(nfa2) {
  let labeled = /* @__PURE__ */ Object.create(null);
  return explore(nullFrom(nfa2, 0));
  function explore(states) {
    let out = [];
    states.forEach((node) => {
      nfa2[node].forEach(({ term, to }) => {
        if (!term)
          return;
        let set;
        for (let i = 0; i < out.length; i++)
          if (out[i][0] == term)
            set = out[i][1];
        nullFrom(nfa2, to).forEach((node2) => {
          if (!set)
            out.push([term, set = []]);
          if (set.indexOf(node2) == -1)
            set.push(node2);
        });
      });
    });
    let state = labeled[states.join(",")] = new ContentMatch(states.indexOf(nfa2.length - 1) > -1);
    for (let i = 0; i < out.length; i++) {
      let states2 = out[i][1].sort(cmp);
      state.next.push({ type: out[i][0], next: labeled[states2.join(",")] || explore(states2) });
    }
    return state;
  }
}
function checkForDeadEnds(match, stream) {
  for (let i = 0, work = [match]; i < work.length; i++) {
    let state = work[i], dead = !state.validEnd, nodes = [];
    for (let j = 0; j < state.next.length; j++) {
      let { type, next } = state.next[j];
      nodes.push(type.name);
      if (dead && !(type.isText || type.hasRequiredAttrs()))
        dead = false;
      if (work.indexOf(next) == -1)
        work.push(next);
    }
    if (dead)
      stream.err("Only non-generatable nodes (" + nodes.join(", ") + ") in a required position (see https://prosemirror.net/docs/guide/#generatable)");
  }
}
function defaultAttrs(attrs) {
  let defaults2 = /* @__PURE__ */ Object.create(null);
  for (let attrName in attrs) {
    let attr = attrs[attrName];
    if (!attr.hasDefault)
      return null;
    defaults2[attrName] = attr.default;
  }
  return defaults2;
}
function computeAttrs(attrs, value) {
  let built = /* @__PURE__ */ Object.create(null);
  for (let name in attrs) {
    let given = value && value[name];
    if (given === void 0) {
      let attr = attrs[name];
      if (attr.hasDefault)
        given = attr.default;
      else
        throw new RangeError("No value supplied for attribute " + name);
    }
    built[name] = given;
  }
  return built;
}
function checkAttrs(attrs, values, type, name) {
  for (let name2 in values)
    if (!(name2 in attrs))
      throw new RangeError(`Unsupported attribute ${name2} for ${type} of type ${name2}`);
  for (let name2 in attrs) {
    let attr = attrs[name2];
    if (attr.validate)
      attr.validate(values[name2]);
  }
}
function initAttrs(typeName, attrs) {
  let result = /* @__PURE__ */ Object.create(null);
  if (attrs)
    for (let name in attrs)
      result[name] = new Attribute(typeName, name, attrs[name]);
  return result;
}
var NodeType = class _NodeType {
  /**
  @internal
  */
  constructor(name, schema, spec) {
    this.name = name;
    this.schema = schema;
    this.spec = spec;
    this.markSet = null;
    this.groups = spec.group ? spec.group.split(" ") : [];
    this.attrs = initAttrs(name, spec.attrs);
    this.defaultAttrs = defaultAttrs(this.attrs);
    this.contentMatch = null;
    this.inlineContent = null;
    this.isBlock = !(spec.inline || name == "text");
    this.isText = name == "text";
  }
  /**
  True if this is an inline type.
  */
  get isInline() {
    return !this.isBlock;
  }
  /**
  True if this is a textblock type, a block that contains inline
  content.
  */
  get isTextblock() {
    return this.isBlock && this.inlineContent;
  }
  /**
  True for node types that allow no content.
  */
  get isLeaf() {
    return this.contentMatch == ContentMatch.empty;
  }
  /**
  True when this node is an atom, i.e. when it does not have
  directly editable content.
  */
  get isAtom() {
    return this.isLeaf || !!this.spec.atom;
  }
  /**
  Return true when this node type is part of the given
  [group](https://prosemirror.net/docs/ref/#model.NodeSpec.group).
  */
  isInGroup(group) {
    return this.groups.indexOf(group) > -1;
  }
  /**
  The node type's [whitespace](https://prosemirror.net/docs/ref/#model.NodeSpec.whitespace) option.
  */
  get whitespace() {
    return this.spec.whitespace || (this.spec.code ? "pre" : "normal");
  }
  /**
  Tells you whether this node type has any required attributes.
  */
  hasRequiredAttrs() {
    for (let n in this.attrs)
      if (this.attrs[n].isRequired)
        return true;
    return false;
  }
  /**
  Indicates whether this node allows some of the same content as
  the given node type.
  */
  compatibleContent(other) {
    return this == other || this.contentMatch.compatible(other.contentMatch);
  }
  /**
  @internal
  */
  computeAttrs(attrs) {
    if (!attrs && this.defaultAttrs)
      return this.defaultAttrs;
    else
      return computeAttrs(this.attrs, attrs);
  }
  /**
  Create a `Node` of this type. The given attributes are
  checked and defaulted (you can pass `null` to use the type's
  defaults entirely, if no required attributes exist). `content`
  may be a `Fragment`, a node, an array of nodes, or
  `null`. Similarly `marks` may be `null` to default to the empty
  set of marks.
  */
  create(attrs = null, content, marks) {
    if (this.isText)
      throw new Error("NodeType.create can't construct text nodes");
    return new Node2(this, this.computeAttrs(attrs), Fragment.from(content), Mark.setFrom(marks));
  }
  /**
  Like [`create`](https://prosemirror.net/docs/ref/#model.NodeType.create), but check the given content
  against the node type's content restrictions, and throw an error
  if it doesn't match.
  */
  createChecked(attrs = null, content, marks) {
    content = Fragment.from(content);
    this.checkContent(content);
    return new Node2(this, this.computeAttrs(attrs), content, Mark.setFrom(marks));
  }
  /**
  Like [`create`](https://prosemirror.net/docs/ref/#model.NodeType.create), but see if it is
  necessary to add nodes to the start or end of the given fragment
  to make it fit the node. If no fitting wrapping can be found,
  return null. Note that, due to the fact that required nodes can
  always be created, this will always succeed if you pass null or
  `Fragment.empty` as content.
  */
  createAndFill(attrs = null, content, marks) {
    attrs = this.computeAttrs(attrs);
    content = Fragment.from(content);
    if (content.size) {
      let before = this.contentMatch.fillBefore(content);
      if (!before)
        return null;
      content = before.append(content);
    }
    let matched = this.contentMatch.matchFragment(content);
    let after = matched && matched.fillBefore(Fragment.empty, true);
    if (!after)
      return null;
    return new Node2(this, attrs, content.append(after), Mark.setFrom(marks));
  }
  /**
  Returns true if the given fragment is valid content for this node
  type.
  */
  validContent(content) {
    let result = this.contentMatch.matchFragment(content);
    if (!result || !result.validEnd)
      return false;
    for (let i = 0; i < content.childCount; i++)
      if (!this.allowsMarks(content.child(i).marks))
        return false;
    return true;
  }
  /**
  Throws a RangeError if the given fragment is not valid content for this
  node type.
  @internal
  */
  checkContent(content) {
    if (!this.validContent(content))
      throw new RangeError(`Invalid content for node ${this.name}: ${content.toString().slice(0, 50)}`);
  }
  /**
  @internal
  */
  checkAttrs(attrs) {
    checkAttrs(this.attrs, attrs, "node", this.name);
  }
  /**
  Check whether the given mark type is allowed in this node.
  */
  allowsMarkType(markType) {
    return this.markSet == null || this.markSet.indexOf(markType) > -1;
  }
  /**
  Test whether the given set of marks are allowed in this node.
  */
  allowsMarks(marks) {
    if (this.markSet == null)
      return true;
    for (let i = 0; i < marks.length; i++)
      if (!this.allowsMarkType(marks[i].type))
        return false;
    return true;
  }
  /**
  Removes the marks that are not allowed in this node from the given set.
  */
  allowedMarks(marks) {
    if (this.markSet == null)
      return marks;
    let copy3;
    for (let i = 0; i < marks.length; i++) {
      if (!this.allowsMarkType(marks[i].type)) {
        if (!copy3)
          copy3 = marks.slice(0, i);
      } else if (copy3) {
        copy3.push(marks[i]);
      }
    }
    return !copy3 ? marks : copy3.length ? copy3 : Mark.none;
  }
  /**
  @internal
  */
  static compile(nodes, schema) {
    let result = /* @__PURE__ */ Object.create(null);
    nodes.forEach((name, spec) => result[name] = new _NodeType(name, schema, spec));
    let topType = schema.spec.topNode || "doc";
    if (!result[topType])
      throw new RangeError("Schema is missing its top node type ('" + topType + "')");
    if (!result.text)
      throw new RangeError("Every schema needs a 'text' type");
    for (let _10 in result.text.attrs)
      throw new RangeError("The text node type should not have attributes");
    return result;
  }
};
function validateType(typeName, attrName, type) {
  let types = type.split("|");
  return (value) => {
    let name = value === null ? "null" : typeof value;
    if (types.indexOf(name) < 0)
      throw new RangeError(`Expected value of type ${types} for attribute ${attrName} on type ${typeName}, got ${name}`);
  };
}
var Attribute = class {
  constructor(typeName, attrName, options) {
    this.hasDefault = Object.prototype.hasOwnProperty.call(options, "default");
    this.default = options.default;
    this.validate = typeof options.validate == "string" ? validateType(typeName, attrName, options.validate) : options.validate;
  }
  get isRequired() {
    return !this.hasDefault;
  }
};
var MarkType = class _MarkType {
  /**
  @internal
  */
  constructor(name, rank, schema, spec) {
    this.name = name;
    this.rank = rank;
    this.schema = schema;
    this.spec = spec;
    this.attrs = initAttrs(name, spec.attrs);
    this.excluded = null;
    let defaults2 = defaultAttrs(this.attrs);
    this.instance = defaults2 ? new Mark(this, defaults2) : null;
  }
  /**
  Create a mark of this type. `attrs` may be `null` or an object
  containing only some of the mark's attributes. The others, if
  they have defaults, will be added.
  */
  create(attrs = null) {
    if (!attrs && this.instance)
      return this.instance;
    return new Mark(this, computeAttrs(this.attrs, attrs));
  }
  /**
  @internal
  */
  static compile(marks, schema) {
    let result = /* @__PURE__ */ Object.create(null), rank = 0;
    marks.forEach((name, spec) => result[name] = new _MarkType(name, rank++, schema, spec));
    return result;
  }
  /**
  When there is a mark of this type in the given set, a new set
  without it is returned. Otherwise, the input set is returned.
  */
  removeFromSet(set) {
    for (var i = 0; i < set.length; i++)
      if (set[i].type == this) {
        set = set.slice(0, i).concat(set.slice(i + 1));
        i--;
      }
    return set;
  }
  /**
  Tests whether there is a mark of this type in the given set.
  */
  isInSet(set) {
    for (let i = 0; i < set.length; i++)
      if (set[i].type == this)
        return set[i];
  }
  /**
  @internal
  */
  checkAttrs(attrs) {
    checkAttrs(this.attrs, attrs, "mark", this.name);
  }
  /**
  Queries whether a given mark type is
  [excluded](https://prosemirror.net/docs/ref/#model.MarkSpec.excludes) by this one.
  */
  excludes(other) {
    return this.excluded.indexOf(other) > -1;
  }
};
var Schema = class {
  /**
  Construct a schema from a schema [specification](https://prosemirror.net/docs/ref/#model.SchemaSpec).
  */
  constructor(spec) {
    this.linebreakReplacement = null;
    this.cached = /* @__PURE__ */ Object.create(null);
    let instanceSpec = this.spec = {};
    for (let prop in spec)
      instanceSpec[prop] = spec[prop];
    instanceSpec.nodes = dist_default.from(spec.nodes), instanceSpec.marks = dist_default.from(spec.marks || {}), this.nodes = NodeType.compile(this.spec.nodes, this);
    this.marks = MarkType.compile(this.spec.marks, this);
    let contentExprCache = /* @__PURE__ */ Object.create(null);
    for (let prop in this.nodes) {
      if (prop in this.marks)
        throw new RangeError(prop + " can not be both a node and a mark");
      let type = this.nodes[prop], contentExpr = type.spec.content || "", markExpr = type.spec.marks;
      type.contentMatch = contentExprCache[contentExpr] || (contentExprCache[contentExpr] = ContentMatch.parse(contentExpr, this.nodes));
      type.inlineContent = type.contentMatch.inlineContent;
      if (type.spec.linebreakReplacement) {
        if (this.linebreakReplacement)
          throw new RangeError("Multiple linebreak nodes defined");
        if (!type.isInline || !type.isLeaf)
          throw new RangeError("Linebreak replacement nodes must be inline leaf nodes");
        this.linebreakReplacement = type;
      }
      type.markSet = markExpr == "_" ? null : markExpr ? gatherMarks(this, markExpr.split(" ")) : markExpr == "" || !type.inlineContent ? [] : null;
    }
    for (let prop in this.marks) {
      let type = this.marks[prop], excl = type.spec.excludes;
      type.excluded = excl == null ? [type] : excl == "" ? [] : gatherMarks(this, excl.split(" "));
    }
    this.nodeFromJSON = (json) => Node2.fromJSON(this, json);
    this.markFromJSON = (json) => Mark.fromJSON(this, json);
    this.topNodeType = this.nodes[this.spec.topNode || "doc"];
    this.cached.wrappings = /* @__PURE__ */ Object.create(null);
  }
  /**
  Create a node in this schema. The `type` may be a string or a
  `NodeType` instance. Attributes will be extended with defaults,
  `content` may be a `Fragment`, `null`, a `Node`, or an array of
  nodes.
  */
  node(type, attrs = null, content, marks) {
    if (typeof type == "string")
      type = this.nodeType(type);
    else if (!(type instanceof NodeType))
      throw new RangeError("Invalid node type: " + type);
    else if (type.schema != this)
      throw new RangeError("Node type from different schema used (" + type.name + ")");
    return type.createChecked(attrs, content, marks);
  }
  /**
  Create a text node in the schema. Empty text nodes are not
  allowed.
  */
  text(text5, marks) {
    let type = this.nodes.text;
    return new TextNode(type, type.defaultAttrs, text5, Mark.setFrom(marks));
  }
  /**
  Create a mark with the given type and attributes.
  */
  mark(type, attrs) {
    if (typeof type == "string")
      type = this.marks[type];
    return type.create(attrs);
  }
  /**
  @internal
  */
  nodeType(name) {
    let found2 = this.nodes[name];
    if (!found2)
      throw new RangeError("Unknown node type: " + name);
    return found2;
  }
};
function gatherMarks(schema, marks) {
  let found2 = [];
  for (let i = 0; i < marks.length; i++) {
    let name = marks[i], mark = schema.marks[name], ok = mark;
    if (mark) {
      found2.push(mark);
    } else {
      for (let prop in schema.marks) {
        let mark2 = schema.marks[prop];
        if (name == "_" || mark2.spec.group && mark2.spec.group.split(" ").indexOf(name) > -1)
          found2.push(ok = mark2);
      }
    }
    if (!ok)
      throw new SyntaxError("Unknown mark type: '" + marks[i] + "'");
  }
  return found2;
}
function isTagRule(rule) {
  return rule.tag != null;
}
function isStyleRule(rule) {
  return rule.style != null;
}
var DOMParser2 = class _DOMParser {
  /**
  Create a parser that targets the given schema, using the given
  parsing rules.
  */
  constructor(schema, rules) {
    this.schema = schema;
    this.rules = rules;
    this.tags = [];
    this.styles = [];
    let matchedStyles = this.matchedStyles = [];
    rules.forEach((rule) => {
      if (isTagRule(rule)) {
        this.tags.push(rule);
      } else if (isStyleRule(rule)) {
        let prop = /[^=]*/.exec(rule.style)[0];
        if (matchedStyles.indexOf(prop) < 0)
          matchedStyles.push(prop);
        this.styles.push(rule);
      }
    });
    this.normalizeLists = !this.tags.some((r2) => {
      if (!/^(ul|ol)\b/.test(r2.tag) || !r2.node)
        return false;
      let node = schema.nodes[r2.node];
      return node.contentMatch.matchType(node);
    });
  }
  /**
  Parse a document from the content of a DOM node.
  */
  parse(dom, options = {}) {
    let context = new ParseContext(this, options, false);
    context.addAll(dom, Mark.none, options.from, options.to);
    return context.finish();
  }
  /**
  Parses the content of the given DOM node, like
  [`parse`](https://prosemirror.net/docs/ref/#model.DOMParser.parse), and takes the same set of
  options. But unlike that method, which produces a whole node,
  this one returns a slice that is open at the sides, meaning that
  the schema constraints aren't applied to the start of nodes to
  the left of the input and the end of nodes at the end.
  */
  parseSlice(dom, options = {}) {
    let context = new ParseContext(this, options, true);
    context.addAll(dom, Mark.none, options.from, options.to);
    return Slice.maxOpen(context.finish());
  }
  /**
  @internal
  */
  matchTag(dom, context, after) {
    for (let i = after ? this.tags.indexOf(after) + 1 : 0; i < this.tags.length; i++) {
      let rule = this.tags[i];
      if (matches(dom, rule.tag) && (rule.namespace === void 0 || dom.namespaceURI == rule.namespace) && (!rule.context || context.matchesContext(rule.context))) {
        if (rule.getAttrs) {
          let result = rule.getAttrs(dom);
          if (result === false)
            continue;
          rule.attrs = result || void 0;
        }
        return rule;
      }
    }
  }
  /**
  @internal
  */
  matchStyle(prop, value, context, after) {
    for (let i = after ? this.styles.indexOf(after) + 1 : 0; i < this.styles.length; i++) {
      let rule = this.styles[i], style2 = rule.style;
      if (style2.indexOf(prop) != 0 || rule.context && !context.matchesContext(rule.context) || // Test that the style string either precisely matches the prop,
      // or has an '=' sign after the prop, followed by the given
      // value.
      style2.length > prop.length && (style2.charCodeAt(prop.length) != 61 || style2.slice(prop.length + 1) != value))
        continue;
      if (rule.getAttrs) {
        let result = rule.getAttrs(value);
        if (result === false)
          continue;
        rule.attrs = result || void 0;
      }
      return rule;
    }
  }
  /**
  @internal
  */
  static schemaRules(schema) {
    let result = [];
    function insert2(rule) {
      let priority = rule.priority == null ? 50 : rule.priority, i = 0;
      for (; i < result.length; i++) {
        let next = result[i], nextPriority = next.priority == null ? 50 : next.priority;
        if (nextPriority < priority)
          break;
      }
      result.splice(i, 0, rule);
    }
    for (let name in schema.marks) {
      let rules = schema.marks[name].spec.parseDOM;
      if (rules)
        rules.forEach((rule) => {
          insert2(rule = copy(rule));
          if (!(rule.mark || rule.ignore || rule.clearMark))
            rule.mark = name;
        });
    }
    for (let name in schema.nodes) {
      let rules = schema.nodes[name].spec.parseDOM;
      if (rules)
        rules.forEach((rule) => {
          insert2(rule = copy(rule));
          if (!(rule.node || rule.ignore || rule.mark))
            rule.node = name;
        });
    }
    return result;
  }
  /**
  Construct a DOM parser using the parsing rules listed in a
  schema's [node specs](https://prosemirror.net/docs/ref/#model.NodeSpec.parseDOM), reordered by
  [priority](https://prosemirror.net/docs/ref/#model.GenericParseRule.priority).
  */
  static fromSchema(schema) {
    return schema.cached.domParser || (schema.cached.domParser = new _DOMParser(schema, _DOMParser.schemaRules(schema)));
  }
};
var blockTags = {
  address: true,
  article: true,
  aside: true,
  blockquote: true,
  canvas: true,
  dd: true,
  div: true,
  dl: true,
  fieldset: true,
  figcaption: true,
  figure: true,
  footer: true,
  form: true,
  h1: true,
  h2: true,
  h3: true,
  h4: true,
  h5: true,
  h6: true,
  header: true,
  hgroup: true,
  hr: true,
  li: true,
  noscript: true,
  ol: true,
  output: true,
  p: true,
  pre: true,
  section: true,
  table: true,
  tfoot: true,
  ul: true
};
var ignoreTags = {
  head: true,
  noscript: true,
  object: true,
  script: true,
  style: true,
  title: true
};
var listTags = { ol: true, ul: true };
var OPT_PRESERVE_WS = 1;
var OPT_PRESERVE_WS_FULL = 2;
var OPT_OPEN_LEFT = 4;
function wsOptionsFor(type, preserveWhitespace, base2) {
  if (preserveWhitespace != null)
    return (preserveWhitespace ? OPT_PRESERVE_WS : 0) | (preserveWhitespace === "full" ? OPT_PRESERVE_WS_FULL : 0);
  return type && type.whitespace == "pre" ? OPT_PRESERVE_WS | OPT_PRESERVE_WS_FULL : base2 & ~OPT_OPEN_LEFT;
}
var NodeContext = class {
  constructor(type, attrs, marks, solid, match, options) {
    this.type = type;
    this.attrs = attrs;
    this.marks = marks;
    this.solid = solid;
    this.options = options;
    this.content = [];
    this.activeMarks = Mark.none;
    this.match = match || (options & OPT_OPEN_LEFT ? null : type.contentMatch);
  }
  findWrapping(node) {
    if (!this.match) {
      if (!this.type)
        return [];
      let fill = this.type.contentMatch.fillBefore(Fragment.from(node));
      if (fill) {
        this.match = this.type.contentMatch.matchFragment(fill);
      } else {
        let start = this.type.contentMatch, wrap2;
        if (wrap2 = start.findWrapping(node.type)) {
          this.match = start;
          return wrap2;
        } else {
          return null;
        }
      }
    }
    return this.match.findWrapping(node.type);
  }
  finish(openEnd) {
    if (!(this.options & OPT_PRESERVE_WS)) {
      let last = this.content[this.content.length - 1], m;
      if (last && last.isText && (m = /[ \t\r\n\u000c]+$/.exec(last.text))) {
        let text5 = last;
        if (last.text.length == m[0].length)
          this.content.pop();
        else
          this.content[this.content.length - 1] = text5.withText(text5.text.slice(0, text5.text.length - m[0].length));
      }
    }
    let content = Fragment.from(this.content);
    if (!openEnd && this.match)
      content = content.append(this.match.fillBefore(Fragment.empty, true));
    return this.type ? this.type.create(this.attrs, content, this.marks) : content;
  }
  inlineContext(node) {
    if (this.type)
      return this.type.inlineContent;
    if (this.content.length)
      return this.content[0].isInline;
    return node.parentNode && !blockTags.hasOwnProperty(node.parentNode.nodeName.toLowerCase());
  }
};
var ParseContext = class {
  constructor(parser, options, isOpen) {
    this.parser = parser;
    this.options = options;
    this.isOpen = isOpen;
    this.open = 0;
    this.localPreserveWS = false;
    let topNode = options.topNode, topContext;
    let topOptions = wsOptionsFor(null, options.preserveWhitespace, 0) | (isOpen ? OPT_OPEN_LEFT : 0);
    if (topNode)
      topContext = new NodeContext(topNode.type, topNode.attrs, Mark.none, true, options.topMatch || topNode.type.contentMatch, topOptions);
    else if (isOpen)
      topContext = new NodeContext(null, null, Mark.none, true, null, topOptions);
    else
      topContext = new NodeContext(parser.schema.topNodeType, null, Mark.none, true, null, topOptions);
    this.nodes = [topContext];
    this.find = options.findPositions;
    this.needsBlock = false;
  }
  get top() {
    return this.nodes[this.open];
  }
  // Add a DOM node to the content. Text is inserted as text node,
  // otherwise, the node is passed to `addElement` or, if it has a
  // `style` attribute, `addElementWithStyles`.
  addDOM(dom, marks) {
    if (dom.nodeType == 3)
      this.addTextNode(dom, marks);
    else if (dom.nodeType == 1)
      this.addElement(dom, marks);
  }
  addTextNode(dom, marks) {
    let value = dom.nodeValue;
    let top = this.top, preserveWS = top.options & OPT_PRESERVE_WS_FULL ? "full" : this.localPreserveWS || (top.options & OPT_PRESERVE_WS) > 0;
    let { schema } = this.parser;
    if (preserveWS === "full" || top.inlineContext(dom) || /[^ \t\r\n\u000c]/.test(value)) {
      if (!preserveWS) {
        value = value.replace(/[ \t\r\n\u000c]+/g, " ");
        if (/^[ \t\r\n\u000c]/.test(value) && this.open == this.nodes.length - 1) {
          let nodeBefore = top.content[top.content.length - 1];
          let domNodeBefore = dom.previousSibling;
          if (!nodeBefore || domNodeBefore && domNodeBefore.nodeName == "BR" || nodeBefore.isText && /[ \t\r\n\u000c]$/.test(nodeBefore.text))
            value = value.slice(1);
        }
      } else if (preserveWS === "full") {
        value = value.replace(/\r\n?/g, "\n");
      } else if (schema.linebreakReplacement && /[\r\n]/.test(value) && this.top.findWrapping(schema.linebreakReplacement.create())) {
        let lines = value.split(/\r?\n|\r/);
        for (let i = 0; i < lines.length; i++) {
          if (i)
            this.insertNode(schema.linebreakReplacement.create(), marks, true);
          if (lines[i])
            this.insertNode(schema.text(lines[i]), marks, !/\S/.test(lines[i]));
        }
        value = "";
      } else {
        value = value.replace(/\r?\n|\r/g, " ");
      }
      if (value)
        this.insertNode(schema.text(value), marks, !/\S/.test(value));
      this.findInText(dom);
    } else {
      this.findInside(dom);
    }
  }
  // Try to find a handler for the given tag and use that to parse. If
  // none is found, the element's content nodes are added directly.
  addElement(dom, marks, matchAfter) {
    let outerWS = this.localPreserveWS, top = this.top;
    if (dom.tagName == "PRE" || /pre/.test(dom.style && dom.style.whiteSpace))
      this.localPreserveWS = true;
    let name = dom.nodeName.toLowerCase(), ruleID;
    if (listTags.hasOwnProperty(name) && this.parser.normalizeLists)
      normalizeList(dom);
    let rule = this.options.ruleFromNode && this.options.ruleFromNode(dom) || (ruleID = this.parser.matchTag(dom, this, matchAfter));
    out: if (rule ? rule.ignore : ignoreTags.hasOwnProperty(name)) {
      this.findInside(dom);
      this.ignoreFallback(dom, marks);
    } else if (!rule || rule.skip || rule.closeParent) {
      if (rule && rule.closeParent)
        this.open = Math.max(0, this.open - 1);
      else if (rule && rule.skip.nodeType)
        dom = rule.skip;
      let sync, oldNeedsBlock = this.needsBlock;
      if (blockTags.hasOwnProperty(name)) {
        if (top.content.length && top.content[0].isInline && this.open) {
          this.open--;
          top = this.top;
        }
        sync = true;
        if (!top.type)
          this.needsBlock = true;
      } else if (!dom.firstChild) {
        this.leafFallback(dom, marks);
        break out;
      }
      let innerMarks = rule && rule.skip ? marks : this.readStyles(dom, marks);
      if (innerMarks)
        this.addAll(dom, innerMarks);
      if (sync)
        this.sync(top);
      this.needsBlock = oldNeedsBlock;
    } else {
      let innerMarks = this.readStyles(dom, marks);
      if (innerMarks)
        this.addElementByRule(dom, rule, innerMarks, rule.consuming === false ? ruleID : void 0);
    }
    this.localPreserveWS = outerWS;
  }
  // Called for leaf DOM nodes that would otherwise be ignored
  leafFallback(dom, marks) {
    if (dom.nodeName == "BR" && this.top.type && this.top.type.inlineContent)
      this.addTextNode(dom.ownerDocument.createTextNode("\n"), marks);
  }
  // Called for ignored nodes
  ignoreFallback(dom, marks) {
    if (dom.nodeName == "BR" && (!this.top.type || !this.top.type.inlineContent))
      this.findPlace(this.parser.schema.text("-"), marks, true);
  }
  // Run any style parser associated with the node's styles. Either
  // return an updated array of marks, or null to indicate some of the
  // styles had a rule with `ignore` set.
  readStyles(dom, marks) {
    let styles2 = dom.style;
    if (styles2 && styles2.length)
      for (let i = 0; i < this.parser.matchedStyles.length; i++) {
        let name = this.parser.matchedStyles[i], value = styles2.getPropertyValue(name);
        if (value)
          for (let after = void 0; ; ) {
            let rule = this.parser.matchStyle(name, value, this, after);
            if (!rule)
              break;
            if (rule.ignore)
              return null;
            if (rule.clearMark)
              marks = marks.filter((m) => !rule.clearMark(m));
            else
              marks = marks.concat(this.parser.schema.marks[rule.mark].create(rule.attrs));
            if (rule.consuming === false)
              after = rule;
            else
              break;
          }
      }
    return marks;
  }
  // Look up a handler for the given node. If none are found, return
  // false. Otherwise, apply it, use its return value to drive the way
  // the node's content is wrapped, and return true.
  addElementByRule(dom, rule, marks, continueAfter) {
    let sync, nodeType;
    if (rule.node) {
      nodeType = this.parser.schema.nodes[rule.node];
      if (!nodeType.isLeaf) {
        let inner2 = this.enter(nodeType, rule.attrs || null, marks, rule.preserveWhitespace);
        if (inner2) {
          sync = true;
          marks = inner2;
        }
      } else if (!this.insertNode(nodeType.create(rule.attrs), marks, dom.nodeName == "BR")) {
        this.leafFallback(dom, marks);
      }
    } else {
      let markType = this.parser.schema.marks[rule.mark];
      marks = marks.concat(markType.create(rule.attrs));
    }
    let startIn = this.top;
    if (nodeType && nodeType.isLeaf) {
      this.findInside(dom);
    } else if (continueAfter) {
      this.addElement(dom, marks, continueAfter);
    } else if (rule.getContent) {
      this.findInside(dom);
      rule.getContent(dom, this.parser.schema).forEach((node) => this.insertNode(node, marks, false));
    } else {
      let contentDOM = dom;
      if (typeof rule.contentElement == "string")
        contentDOM = dom.querySelector(rule.contentElement);
      else if (typeof rule.contentElement == "function")
        contentDOM = rule.contentElement(dom);
      else if (rule.contentElement)
        contentDOM = rule.contentElement;
      this.findAround(dom, contentDOM, true);
      this.addAll(contentDOM, marks);
      this.findAround(dom, contentDOM, false);
    }
    if (sync && this.sync(startIn))
      this.open--;
  }
  // Add all child nodes between `startIndex` and `endIndex` (or the
  // whole node, if not given). If `sync` is passed, use it to
  // synchronize after every block element.
  addAll(parent, marks, startIndex, endIndex) {
    let index = startIndex || 0;
    for (let dom = startIndex ? parent.childNodes[startIndex] : parent.firstChild, end = endIndex == null ? null : parent.childNodes[endIndex]; dom != end; dom = dom.nextSibling, ++index) {
      this.findAtPoint(parent, index);
      this.addDOM(dom, marks);
    }
    this.findAtPoint(parent, index);
  }
  // Try to find a way to fit the given node type into the current
  // context. May add intermediate wrappers and/or leave non-solid
  // nodes that we're in.
  findPlace(node, marks, cautious) {
    let route, sync;
    for (let depth = this.open, penalty = 0; depth >= 0; depth--) {
      let cx = this.nodes[depth];
      let found2 = cx.findWrapping(node);
      if (found2 && (!route || route.length > found2.length + penalty)) {
        route = found2;
        sync = cx;
        if (!found2.length)
          break;
      }
      if (cx.solid) {
        if (cautious)
          break;
        penalty += 2;
      }
    }
    if (!route)
      return null;
    this.sync(sync);
    for (let i = 0; i < route.length; i++)
      marks = this.enterInner(route[i], null, marks, false);
    return marks;
  }
  // Try to insert the given node, adjusting the context when needed.
  insertNode(node, marks, cautious) {
    if (node.isInline && this.needsBlock && !this.top.type) {
      let block = this.textblockFromContext();
      if (block)
        marks = this.enterInner(block, null, marks);
    }
    let innerMarks = this.findPlace(node, marks, cautious);
    if (innerMarks) {
      this.closeExtra();
      let top = this.top;
      if (top.match)
        top.match = top.match.matchType(node.type);
      let nodeMarks = Mark.none;
      for (let m of innerMarks.concat(node.marks))
        if (top.type ? top.type.allowsMarkType(m.type) : markMayApply(m.type, node.type))
          nodeMarks = m.addToSet(nodeMarks);
      top.content.push(node.mark(nodeMarks));
      return true;
    }
    return false;
  }
  // Try to start a node of the given type, adjusting the context when
  // necessary.
  enter(type, attrs, marks, preserveWS) {
    let innerMarks = this.findPlace(type.create(attrs), marks, false);
    if (innerMarks)
      innerMarks = this.enterInner(type, attrs, marks, true, preserveWS);
    return innerMarks;
  }
  // Open a node of the given type
  enterInner(type, attrs, marks, solid = false, preserveWS) {
    this.closeExtra();
    let top = this.top;
    top.match = top.match && top.match.matchType(type);
    let options = wsOptionsFor(type, preserveWS, top.options);
    if (top.options & OPT_OPEN_LEFT && top.content.length == 0)
      options |= OPT_OPEN_LEFT;
    let applyMarks = Mark.none;
    marks = marks.filter((m) => {
      if (top.type ? top.type.allowsMarkType(m.type) : markMayApply(m.type, type)) {
        applyMarks = m.addToSet(applyMarks);
        return false;
      }
      return true;
    });
    this.nodes.push(new NodeContext(type, attrs, applyMarks, solid, null, options));
    this.open++;
    return marks;
  }
  // Make sure all nodes above this.open are finished and added to
  // their parents
  closeExtra(openEnd = false) {
    let i = this.nodes.length - 1;
    if (i > this.open) {
      for (; i > this.open; i--)
        this.nodes[i - 1].content.push(this.nodes[i].finish(openEnd));
      this.nodes.length = this.open + 1;
    }
  }
  finish() {
    this.open = 0;
    this.closeExtra(this.isOpen);
    return this.nodes[0].finish(!!(this.isOpen || this.options.topOpen));
  }
  sync(to) {
    for (let i = this.open; i >= 0; i--) {
      if (this.nodes[i] == to) {
        this.open = i;
        return true;
      } else if (this.localPreserveWS) {
        this.nodes[i].options |= OPT_PRESERVE_WS;
      }
    }
    return false;
  }
  get currentPos() {
    this.closeExtra();
    let pos = 0;
    for (let i = this.open; i >= 0; i--) {
      let content = this.nodes[i].content;
      for (let j = content.length - 1; j >= 0; j--)
        pos += content[j].nodeSize;
      if (i)
        pos++;
    }
    return pos;
  }
  findAtPoint(parent, offset) {
    if (this.find)
      for (let i = 0; i < this.find.length; i++) {
        if (this.find[i].node == parent && this.find[i].offset == offset)
          this.find[i].pos = this.currentPos;
      }
  }
  findInside(parent) {
    if (this.find)
      for (let i = 0; i < this.find.length; i++) {
        if (this.find[i].pos == null && parent.nodeType == 1 && parent.contains(this.find[i].node))
          this.find[i].pos = this.currentPos;
      }
  }
  findAround(parent, content, before) {
    if (parent != content && this.find)
      for (let i = 0; i < this.find.length; i++) {
        if (this.find[i].pos == null && parent.nodeType == 1 && parent.contains(this.find[i].node)) {
          let pos = content.compareDocumentPosition(this.find[i].node);
          if (pos & (before ? 2 : 4))
            this.find[i].pos = this.currentPos;
        }
      }
  }
  findInText(textNode) {
    if (this.find)
      for (let i = 0; i < this.find.length; i++) {
        if (this.find[i].node == textNode)
          this.find[i].pos = this.currentPos - (textNode.nodeValue.length - this.find[i].offset);
      }
  }
  // Determines whether the given context string matches this context.
  matchesContext(context) {
    if (context.indexOf("|") > -1)
      return context.split(/\s*\|\s*/).some(this.matchesContext, this);
    let parts = context.split("/");
    let option = this.options.context;
    let useRoot = !this.isOpen && (!option || option.parent.type == this.nodes[0].type);
    let minDepth = -(option ? option.depth + 1 : 0) + (useRoot ? 0 : 1);
    let match = (i, depth) => {
      for (; i >= 0; i--) {
        let part = parts[i];
        if (part == "") {
          if (i == parts.length - 1 || i == 0)
            continue;
          for (; depth >= minDepth; depth--)
            if (match(i - 1, depth))
              return true;
          return false;
        } else {
          let next = depth > 0 || depth == 0 && useRoot ? this.nodes[depth].type : option && depth >= minDepth ? option.node(depth - minDepth).type : null;
          if (!next || next.name != part && !next.isInGroup(part))
            return false;
          depth--;
        }
      }
      return true;
    };
    return match(parts.length - 1, this.open);
  }
  textblockFromContext() {
    let $context = this.options.context;
    if ($context)
      for (let d2 = $context.depth; d2 >= 0; d2--) {
        let deflt3 = $context.node(d2).contentMatchAt($context.indexAfter(d2)).defaultType;
        if (deflt3 && deflt3.isTextblock && deflt3.defaultAttrs)
          return deflt3;
      }
    for (let name in this.parser.schema.nodes) {
      let type = this.parser.schema.nodes[name];
      if (type.isTextblock && type.defaultAttrs)
        return type;
    }
  }
};
function normalizeList(dom) {
  for (let child = dom.firstChild, prevItem = null; child; child = child.nextSibling) {
    let name = child.nodeType == 1 ? child.nodeName.toLowerCase() : null;
    if (name && listTags.hasOwnProperty(name) && prevItem) {
      prevItem.appendChild(child);
      child = prevItem;
    } else if (name == "li") {
      prevItem = child;
    } else if (name) {
      prevItem = null;
    }
  }
}
function matches(dom, selector) {
  return (dom.matches || dom.msMatchesSelector || dom.webkitMatchesSelector || dom.mozMatchesSelector).call(dom, selector);
}
function copy(obj) {
  let copy3 = {};
  for (let prop in obj)
    copy3[prop] = obj[prop];
  return copy3;
}
function markMayApply(markType, nodeType) {
  let nodes = nodeType.schema.nodes;
  for (let name in nodes) {
    let parent = nodes[name];
    if (!parent.allowsMarkType(markType))
      continue;
    let seen = [], scan = (match) => {
      seen.push(match);
      for (let i = 0; i < match.edgeCount; i++) {
        let { type, next } = match.edge(i);
        if (type == nodeType)
          return true;
        if (seen.indexOf(next) < 0 && scan(next))
          return true;
      }
    };
    if (scan(parent.contentMatch))
      return true;
  }
}
var DOMSerializer = class _DOMSerializer {
  /**
  Create a serializer. `nodes` should map node names to functions
  that take a node and return a description of the corresponding
  DOM. `marks` does the same for mark names, but also gets an
  argument that tells it whether the mark's content is block or
  inline content (for typical use, it'll always be inline). A mark
  serializer may be `null` to indicate that marks of that type
  should not be serialized.
  */
  constructor(nodes, marks) {
    this.nodes = nodes;
    this.marks = marks;
  }
  /**
  Serialize the content of this fragment to a DOM fragment. When
  not in the browser, the `document` option, containing a DOM
  document, should be passed so that the serializer can create
  nodes.
  */
  serializeFragment(fragment, options = {}, target2) {
    if (!target2)
      target2 = doc(options).createDocumentFragment();
    let top = target2, active = [];
    fragment.forEach((node) => {
      if (active.length || node.marks.length) {
        let keep = 0, rendered = 0;
        while (keep < active.length && rendered < node.marks.length) {
          let next = node.marks[rendered];
          if (!this.marks[next.type.name]) {
            rendered++;
            continue;
          }
          if (!next.eq(active[keep][0]) || next.type.spec.spanning === false)
            break;
          keep++;
          rendered++;
        }
        while (keep < active.length)
          top = active.pop()[1];
        while (rendered < node.marks.length) {
          let add = node.marks[rendered++];
          let markDOM = this.serializeMark(add, node.isInline, options);
          if (markDOM) {
            active.push([add, top]);
            top.appendChild(markDOM.dom);
            top = markDOM.contentDOM || markDOM.dom;
          }
        }
      }
      top.appendChild(this.serializeNodeInner(node, options));
    });
    return target2;
  }
  /**
  @internal
  */
  serializeNodeInner(node, options) {
    let { dom, contentDOM } = renderSpec(doc(options), this.nodes[node.type.name](node), null, node.attrs);
    if (contentDOM) {
      if (node.isLeaf)
        throw new RangeError("Content hole not allowed in a leaf node spec");
      this.serializeFragment(node.content, options, contentDOM);
    }
    return dom;
  }
  /**
  Serialize this node to a DOM node. This can be useful when you
  need to serialize a part of a document, as opposed to the whole
  document. To serialize a whole document, use
  [`serializeFragment`](https://prosemirror.net/docs/ref/#model.DOMSerializer.serializeFragment) on
  its [content](https://prosemirror.net/docs/ref/#model.Node.content).
  */
  serializeNode(node, options = {}) {
    let dom = this.serializeNodeInner(node, options);
    for (let i = node.marks.length - 1; i >= 0; i--) {
      let wrap2 = this.serializeMark(node.marks[i], node.isInline, options);
      if (wrap2) {
        (wrap2.contentDOM || wrap2.dom).appendChild(dom);
        dom = wrap2.dom;
      }
    }
    return dom;
  }
  /**
  @internal
  */
  serializeMark(mark, inline, options = {}) {
    let toDOM = this.marks[mark.type.name];
    return toDOM && renderSpec(doc(options), toDOM(mark, inline), null, mark.attrs);
  }
  static renderSpec(doc3, structure, xmlNS = null, blockArraysIn) {
    return renderSpec(doc3, structure, xmlNS, blockArraysIn);
  }
  /**
  Build a serializer using the [`toDOM`](https://prosemirror.net/docs/ref/#model.NodeSpec.toDOM)
  properties in a schema's node and mark specs.
  */
  static fromSchema(schema) {
    return schema.cached.domSerializer || (schema.cached.domSerializer = new _DOMSerializer(this.nodesFromSchema(schema), this.marksFromSchema(schema)));
  }
  /**
  Gather the serializers in a schema's node specs into an object.
  This can be useful as a base to build a custom serializer from.
  */
  static nodesFromSchema(schema) {
    let result = gatherToDOM(schema.nodes);
    if (!result.text)
      result.text = (node) => node.text;
    return result;
  }
  /**
  Gather the serializers in a schema's mark specs into an object.
  */
  static marksFromSchema(schema) {
    return gatherToDOM(schema.marks);
  }
};
function gatherToDOM(obj) {
  let result = {};
  for (let name in obj) {
    let toDOM = obj[name].spec.toDOM;
    if (toDOM)
      result[name] = toDOM;
  }
  return result;
}
function doc(options) {
  return options.document || window.document;
}
var suspiciousAttributeCache = /* @__PURE__ */ new WeakMap();
function suspiciousAttributes(attrs) {
  let value = suspiciousAttributeCache.get(attrs);
  if (value === void 0)
    suspiciousAttributeCache.set(attrs, value = suspiciousAttributesInner(attrs));
  return value;
}
function suspiciousAttributesInner(attrs) {
  let result = null;
  function scan(value) {
    if (value && typeof value == "object") {
      if (Array.isArray(value)) {
        if (typeof value[0] == "string") {
          if (!result)
            result = [];
          result.push(value);
        } else {
          for (let i = 0; i < value.length; i++)
            scan(value[i]);
        }
      } else {
        for (let prop in value)
          scan(value[prop]);
      }
    }
  }
  scan(attrs);
  return result;
}
function renderSpec(doc3, structure, xmlNS, blockArraysIn) {
  if (typeof structure == "string")
    return { dom: doc3.createTextNode(structure) };
  if (structure.nodeType != null)
    return { dom: structure };
  if (structure.dom && structure.dom.nodeType != null)
    return structure;
  let tagName = structure[0], suspicious;
  if (typeof tagName != "string")
    throw new RangeError("Invalid array passed to renderSpec");
  if (blockArraysIn && (suspicious = suspiciousAttributes(blockArraysIn)) && suspicious.indexOf(structure) > -1)
    throw new RangeError("Using an array from an attribute object as a DOM spec. This may be an attempted cross site scripting attack.");
  let space3 = tagName.indexOf(" ");
  if (space3 > 0) {
    xmlNS = tagName.slice(0, space3);
    tagName = tagName.slice(space3 + 1);
  }
  let contentDOM;
  let dom = xmlNS ? doc3.createElementNS(xmlNS, tagName) : doc3.createElement(tagName);
  let attrs = structure[1], start = 1;
  if (attrs && typeof attrs == "object" && attrs.nodeType == null && !Array.isArray(attrs)) {
    start = 2;
    for (let name in attrs)
      if (attrs[name] != null) {
        let space4 = name.indexOf(" ");
        if (space4 > 0)
          dom.setAttributeNS(name.slice(0, space4), name.slice(space4 + 1), attrs[name]);
        else if (name == "style" && dom.style)
          dom.style.cssText = attrs[name];
        else
          dom.setAttribute(name, attrs[name]);
      }
  }
  for (let i = start; i < structure.length; i++) {
    let child = structure[i];
    if (child === 0) {
      if (i < structure.length - 1 || i > start)
        throw new RangeError("Content hole must be the only child of its parent node");
      return { dom, contentDOM: dom };
    } else {
      let { dom: inner2, contentDOM: innerContent } = renderSpec(doc3, child, xmlNS, blockArraysIn);
      dom.appendChild(inner2);
      if (innerContent) {
        if (contentDOM)
          throw new RangeError("Multiple content holes");
        contentDOM = innerContent;
      }
    }
  }
  return { dom, contentDOM };
}

// ../../node_modules/.pnpm/prosemirror-transform@1.10.5/node_modules/prosemirror-transform/dist/index.js
var lower16 = 65535;
var factor16 = Math.pow(2, 16);
function makeRecover(index, offset) {
  return index + offset * factor16;
}
function recoverIndex(value) {
  return value & lower16;
}
function recoverOffset(value) {
  return (value - (value & lower16)) / factor16;
}
var DEL_BEFORE = 1;
var DEL_AFTER = 2;
var DEL_ACROSS = 4;
var DEL_SIDE = 8;
var MapResult = class {
  /**
  @internal
  */
  constructor(pos, delInfo, recover) {
    this.pos = pos;
    this.delInfo = delInfo;
    this.recover = recover;
  }
  /**
  Tells you whether the position was deleted, that is, whether the
  step removed the token on the side queried (via the `assoc`)
  argument from the document.
  */
  get deleted() {
    return (this.delInfo & DEL_SIDE) > 0;
  }
  /**
  Tells you whether the token before the mapped position was deleted.
  */
  get deletedBefore() {
    return (this.delInfo & (DEL_BEFORE | DEL_ACROSS)) > 0;
  }
  /**
  True when the token after the mapped position was deleted.
  */
  get deletedAfter() {
    return (this.delInfo & (DEL_AFTER | DEL_ACROSS)) > 0;
  }
  /**
  Tells whether any of the steps mapped through deletes across the
  position (including both the token before and after the
  position).
  */
  get deletedAcross() {
    return (this.delInfo & DEL_ACROSS) > 0;
  }
};
var StepMap = class _StepMap {
  /**
  Create a position map. The modifications to the document are
  represented as an array of numbers, in which each group of three
  represents a modified chunk as `[start, oldSize, newSize]`.
  */
  constructor(ranges, inverted = false) {
    this.ranges = ranges;
    this.inverted = inverted;
    if (!ranges.length && _StepMap.empty)
      return _StepMap.empty;
  }
  /**
  @internal
  */
  recover(value) {
    let diff = 0, index = recoverIndex(value);
    if (!this.inverted)
      for (let i = 0; i < index; i++)
        diff += this.ranges[i * 3 + 2] - this.ranges[i * 3 + 1];
    return this.ranges[index * 3] + diff + recoverOffset(value);
  }
  mapResult(pos, assoc = 1) {
    return this._map(pos, assoc, false);
  }
  map(pos, assoc = 1) {
    return this._map(pos, assoc, true);
  }
  /**
  @internal
  */
  _map(pos, assoc, simple) {
    let diff = 0, oldIndex = this.inverted ? 2 : 1, newIndex = this.inverted ? 1 : 2;
    for (let i = 0; i < this.ranges.length; i += 3) {
      let start = this.ranges[i] - (this.inverted ? diff : 0);
      if (start > pos)
        break;
      let oldSize = this.ranges[i + oldIndex], newSize = this.ranges[i + newIndex], end = start + oldSize;
      if (pos <= end) {
        let side = !oldSize ? assoc : pos == start ? -1 : pos == end ? 1 : assoc;
        let result = start + diff + (side < 0 ? 0 : newSize);
        if (simple)
          return result;
        let recover = pos == (assoc < 0 ? start : end) ? null : makeRecover(i / 3, pos - start);
        let del2 = pos == start ? DEL_AFTER : pos == end ? DEL_BEFORE : DEL_ACROSS;
        if (assoc < 0 ? pos != start : pos != end)
          del2 |= DEL_SIDE;
        return new MapResult(result, del2, recover);
      }
      diff += newSize - oldSize;
    }
    return simple ? pos + diff : new MapResult(pos + diff, 0, null);
  }
  /**
  @internal
  */
  touches(pos, recover) {
    let diff = 0, index = recoverIndex(recover);
    let oldIndex = this.inverted ? 2 : 1, newIndex = this.inverted ? 1 : 2;
    for (let i = 0; i < this.ranges.length; i += 3) {
      let start = this.ranges[i] - (this.inverted ? diff : 0);
      if (start > pos)
        break;
      let oldSize = this.ranges[i + oldIndex], end = start + oldSize;
      if (pos <= end && i == index * 3)
        return true;
      diff += this.ranges[i + newIndex] - oldSize;
    }
    return false;
  }
  /**
  Calls the given function on each of the changed ranges included in
  this map.
  */
  forEach(f) {
    let oldIndex = this.inverted ? 2 : 1, newIndex = this.inverted ? 1 : 2;
    for (let i = 0, diff = 0; i < this.ranges.length; i += 3) {
      let start = this.ranges[i], oldStart = start - (this.inverted ? diff : 0), newStart = start + (this.inverted ? 0 : diff);
      let oldSize = this.ranges[i + oldIndex], newSize = this.ranges[i + newIndex];
      f(oldStart, oldStart + oldSize, newStart, newStart + newSize);
      diff += newSize - oldSize;
    }
  }
  /**
  Create an inverted version of this map. The result can be used to
  map positions in the post-step document to the pre-step document.
  */
  invert() {
    return new _StepMap(this.ranges, !this.inverted);
  }
  /**
  @internal
  */
  toString() {
    return (this.inverted ? "-" : "") + JSON.stringify(this.ranges);
  }
  /**
  Create a map that moves all positions by offset `n` (which may be
  negative). This can be useful when applying steps meant for a
  sub-document to a larger document, or vice-versa.
  */
  static offset(n) {
    return n == 0 ? _StepMap.empty : new _StepMap(n < 0 ? [0, -n, 0] : [0, 0, n]);
  }
};
StepMap.empty = new StepMap([]);
var Mapping = class _Mapping {
  /**
  Create a new mapping with the given position maps.
  */
  constructor(maps, mirror, from2 = 0, to = maps ? maps.length : 0) {
    this.mirror = mirror;
    this.from = from2;
    this.to = to;
    this._maps = maps || [];
    this.ownData = !(maps || mirror);
  }
  /**
  The step maps in this mapping.
  */
  get maps() {
    return this._maps;
  }
  /**
  Create a mapping that maps only through a part of this one.
  */
  slice(from2 = 0, to = this.maps.length) {
    return new _Mapping(this._maps, this.mirror, from2, to);
  }
  /**
  Add a step map to the end of this mapping. If `mirrors` is
  given, it should be the index of the step map that is the mirror
  image of this one.
  */
  appendMap(map2, mirrors) {
    if (!this.ownData) {
      this._maps = this._maps.slice();
      this.mirror = this.mirror && this.mirror.slice();
      this.ownData = true;
    }
    this.to = this._maps.push(map2);
    if (mirrors != null)
      this.setMirror(this._maps.length - 1, mirrors);
  }
  /**
  Add all the step maps in a given mapping to this one (preserving
  mirroring information).
  */
  appendMapping(mapping) {
    for (let i = 0, startSize = this._maps.length; i < mapping._maps.length; i++) {
      let mirr = mapping.getMirror(i);
      this.appendMap(mapping._maps[i], mirr != null && mirr < i ? startSize + mirr : void 0);
    }
  }
  /**
  Finds the offset of the step map that mirrors the map at the
  given offset, in this mapping (as per the second argument to
  `appendMap`).
  */
  getMirror(n) {
    if (this.mirror) {
      for (let i = 0; i < this.mirror.length; i++)
        if (this.mirror[i] == n)
          return this.mirror[i + (i % 2 ? -1 : 1)];
    }
  }
  /**
  @internal
  */
  setMirror(n, m) {
    if (!this.mirror)
      this.mirror = [];
    this.mirror.push(n, m);
  }
  /**
  Append the inverse of the given mapping to this one.
  */
  appendMappingInverted(mapping) {
    for (let i = mapping.maps.length - 1, totalSize = this._maps.length + mapping._maps.length; i >= 0; i--) {
      let mirr = mapping.getMirror(i);
      this.appendMap(mapping._maps[i].invert(), mirr != null && mirr > i ? totalSize - mirr - 1 : void 0);
    }
  }
  /**
  Create an inverted version of this mapping.
  */
  invert() {
    let inverse = new _Mapping();
    inverse.appendMappingInverted(this);
    return inverse;
  }
  /**
  Map a position through this mapping.
  */
  map(pos, assoc = 1) {
    if (this.mirror)
      return this._map(pos, assoc, true);
    for (let i = this.from; i < this.to; i++)
      pos = this._maps[i].map(pos, assoc);
    return pos;
  }
  /**
  Map a position through this mapping, returning a mapping
  result.
  */
  mapResult(pos, assoc = 1) {
    return this._map(pos, assoc, false);
  }
  /**
  @internal
  */
  _map(pos, assoc, simple) {
    let delInfo = 0;
    for (let i = this.from; i < this.to; i++) {
      let map2 = this._maps[i], result = map2.mapResult(pos, assoc);
      if (result.recover != null) {
        let corr = this.getMirror(i);
        if (corr != null && corr > i && corr < this.to) {
          i = corr;
          pos = this._maps[corr].recover(result.recover);
          continue;
        }
      }
      delInfo |= result.delInfo;
      pos = result.pos;
    }
    return simple ? pos : new MapResult(pos, delInfo, null);
  }
};
var stepsByID = /* @__PURE__ */ Object.create(null);
var Step = class {
  /**
  Get the step map that represents the changes made by this step,
  and which can be used to transform between positions in the old
  and the new document.
  */
  getMap() {
    return StepMap.empty;
  }
  /**
  Try to merge this step with another one, to be applied directly
  after it. Returns the merged step when possible, null if the
  steps can't be merged.
  */
  merge(other) {
    return null;
  }
  /**
  Deserialize a step from its JSON representation. Will call
  through to the step class' own implementation of this method.
  */
  static fromJSON(schema, json) {
    if (!json || !json.stepType)
      throw new RangeError("Invalid input for Step.fromJSON");
    let type = stepsByID[json.stepType];
    if (!type)
      throw new RangeError(`No step type ${json.stepType} defined`);
    return type.fromJSON(schema, json);
  }
  /**
  To be able to serialize steps to JSON, each step needs a string
  ID to attach to its JSON representation. Use this method to
  register an ID for your step classes. Try to pick something
  that's unlikely to clash with steps from other modules.
  */
  static jsonID(id, stepClass) {
    if (id in stepsByID)
      throw new RangeError("Duplicate use of step JSON ID " + id);
    stepsByID[id] = stepClass;
    stepClass.prototype.jsonID = id;
    return stepClass;
  }
};
var StepResult = class _StepResult {
  /**
  @internal
  */
  constructor(doc3, failed) {
    this.doc = doc3;
    this.failed = failed;
  }
  /**
  Create a successful step result.
  */
  static ok(doc3) {
    return new _StepResult(doc3, null);
  }
  /**
  Create a failed step result.
  */
  static fail(message) {
    return new _StepResult(null, message);
  }
  /**
  Call [`Node.replace`](https://prosemirror.net/docs/ref/#model.Node.replace) with the given
  arguments. Create a successful result if it succeeds, and a
  failed one if it throws a `ReplaceError`.
  */
  static fromReplace(doc3, from2, to, slice2) {
    try {
      return _StepResult.ok(doc3.replace(from2, to, slice2));
    } catch (e) {
      if (e instanceof ReplaceError)
        return _StepResult.fail(e.message);
      throw e;
    }
  }
};
function mapFragment(fragment, f, parent) {
  let mapped = [];
  for (let i = 0; i < fragment.childCount; i++) {
    let child = fragment.child(i);
    if (child.content.size)
      child = child.copy(mapFragment(child.content, f, child));
    if (child.isInline)
      child = f(child, parent, i);
    mapped.push(child);
  }
  return Fragment.fromArray(mapped);
}
var AddMarkStep = class _AddMarkStep extends Step {
  /**
  Create a mark step.
  */
  constructor(from2, to, mark) {
    super();
    this.from = from2;
    this.to = to;
    this.mark = mark;
  }
  apply(doc3) {
    let oldSlice = doc3.slice(this.from, this.to), $from = doc3.resolve(this.from);
    let parent = $from.node($from.sharedDepth(this.to));
    let slice2 = new Slice(mapFragment(oldSlice.content, (node, parent2) => {
      if (!node.isAtom || !parent2.type.allowsMarkType(this.mark.type))
        return node;
      return node.mark(this.mark.addToSet(node.marks));
    }, parent), oldSlice.openStart, oldSlice.openEnd);
    return StepResult.fromReplace(doc3, this.from, this.to, slice2);
  }
  invert() {
    return new RemoveMarkStep(this.from, this.to, this.mark);
  }
  map(mapping) {
    let from2 = mapping.mapResult(this.from, 1), to = mapping.mapResult(this.to, -1);
    if (from2.deleted && to.deleted || from2.pos >= to.pos)
      return null;
    return new _AddMarkStep(from2.pos, to.pos, this.mark);
  }
  merge(other) {
    if (other instanceof _AddMarkStep && other.mark.eq(this.mark) && this.from <= other.to && this.to >= other.from)
      return new _AddMarkStep(Math.min(this.from, other.from), Math.max(this.to, other.to), this.mark);
    return null;
  }
  toJSON() {
    return {
      stepType: "addMark",
      mark: this.mark.toJSON(),
      from: this.from,
      to: this.to
    };
  }
  /**
  @internal
  */
  static fromJSON(schema, json) {
    if (typeof json.from != "number" || typeof json.to != "number")
      throw new RangeError("Invalid input for AddMarkStep.fromJSON");
    return new _AddMarkStep(json.from, json.to, schema.markFromJSON(json.mark));
  }
};
Step.jsonID("addMark", AddMarkStep);
var RemoveMarkStep = class _RemoveMarkStep extends Step {
  /**
  Create a mark-removing step.
  */
  constructor(from2, to, mark) {
    super();
    this.from = from2;
    this.to = to;
    this.mark = mark;
  }
  apply(doc3) {
    let oldSlice = doc3.slice(this.from, this.to);
    let slice2 = new Slice(mapFragment(oldSlice.content, (node) => {
      return node.mark(this.mark.removeFromSet(node.marks));
    }, doc3), oldSlice.openStart, oldSlice.openEnd);
    return StepResult.fromReplace(doc3, this.from, this.to, slice2);
  }
  invert() {
    return new AddMarkStep(this.from, this.to, this.mark);
  }
  map(mapping) {
    let from2 = mapping.mapResult(this.from, 1), to = mapping.mapResult(this.to, -1);
    if (from2.deleted && to.deleted || from2.pos >= to.pos)
      return null;
    return new _RemoveMarkStep(from2.pos, to.pos, this.mark);
  }
  merge(other) {
    if (other instanceof _RemoveMarkStep && other.mark.eq(this.mark) && this.from <= other.to && this.to >= other.from)
      return new _RemoveMarkStep(Math.min(this.from, other.from), Math.max(this.to, other.to), this.mark);
    return null;
  }
  toJSON() {
    return {
      stepType: "removeMark",
      mark: this.mark.toJSON(),
      from: this.from,
      to: this.to
    };
  }
  /**
  @internal
  */
  static fromJSON(schema, json) {
    if (typeof json.from != "number" || typeof json.to != "number")
      throw new RangeError("Invalid input for RemoveMarkStep.fromJSON");
    return new _RemoveMarkStep(json.from, json.to, schema.markFromJSON(json.mark));
  }
};
Step.jsonID("removeMark", RemoveMarkStep);
var AddNodeMarkStep = class _AddNodeMarkStep extends Step {
  /**
  Create a node mark step.
  */
  constructor(pos, mark) {
    super();
    this.pos = pos;
    this.mark = mark;
  }
  apply(doc3) {
    let node = doc3.nodeAt(this.pos);
    if (!node)
      return StepResult.fail("No node at mark step's position");
    let updated = node.type.create(node.attrs, null, this.mark.addToSet(node.marks));
    return StepResult.fromReplace(doc3, this.pos, this.pos + 1, new Slice(Fragment.from(updated), 0, node.isLeaf ? 0 : 1));
  }
  invert(doc3) {
    let node = doc3.nodeAt(this.pos);
    if (node) {
      let newSet = this.mark.addToSet(node.marks);
      if (newSet.length == node.marks.length) {
        for (let i = 0; i < node.marks.length; i++)
          if (!node.marks[i].isInSet(newSet))
            return new _AddNodeMarkStep(this.pos, node.marks[i]);
        return new _AddNodeMarkStep(this.pos, this.mark);
      }
    }
    return new RemoveNodeMarkStep(this.pos, this.mark);
  }
  map(mapping) {
    let pos = mapping.mapResult(this.pos, 1);
    return pos.deletedAfter ? null : new _AddNodeMarkStep(pos.pos, this.mark);
  }
  toJSON() {
    return { stepType: "addNodeMark", pos: this.pos, mark: this.mark.toJSON() };
  }
  /**
  @internal
  */
  static fromJSON(schema, json) {
    if (typeof json.pos != "number")
      throw new RangeError("Invalid input for AddNodeMarkStep.fromJSON");
    return new _AddNodeMarkStep(json.pos, schema.markFromJSON(json.mark));
  }
};
Step.jsonID("addNodeMark", AddNodeMarkStep);
var RemoveNodeMarkStep = class _RemoveNodeMarkStep extends Step {
  /**
  Create a mark-removing step.
  */
  constructor(pos, mark) {
    super();
    this.pos = pos;
    this.mark = mark;
  }
  apply(doc3) {
    let node = doc3.nodeAt(this.pos);
    if (!node)
      return StepResult.fail("No node at mark step's position");
    let updated = node.type.create(node.attrs, null, this.mark.removeFromSet(node.marks));
    return StepResult.fromReplace(doc3, this.pos, this.pos + 1, new Slice(Fragment.from(updated), 0, node.isLeaf ? 0 : 1));
  }
  invert(doc3) {
    let node = doc3.nodeAt(this.pos);
    if (!node || !this.mark.isInSet(node.marks))
      return this;
    return new AddNodeMarkStep(this.pos, this.mark);
  }
  map(mapping) {
    let pos = mapping.mapResult(this.pos, 1);
    return pos.deletedAfter ? null : new _RemoveNodeMarkStep(pos.pos, this.mark);
  }
  toJSON() {
    return { stepType: "removeNodeMark", pos: this.pos, mark: this.mark.toJSON() };
  }
  /**
  @internal
  */
  static fromJSON(schema, json) {
    if (typeof json.pos != "number")
      throw new RangeError("Invalid input for RemoveNodeMarkStep.fromJSON");
    return new _RemoveNodeMarkStep(json.pos, schema.markFromJSON(json.mark));
  }
};
Step.jsonID("removeNodeMark", RemoveNodeMarkStep);
var ReplaceStep = class _ReplaceStep extends Step {
  /**
  The given `slice` should fit the 'gap' between `from` and
  `to`—the depths must line up, and the surrounding nodes must be
  able to be joined with the open sides of the slice. When
  `structure` is true, the step will fail if the content between
  from and to is not just a sequence of closing and then opening
  tokens (this is to guard against rebased replace steps
  overwriting something they weren't supposed to).
  */
  constructor(from2, to, slice2, structure = false) {
    super();
    this.from = from2;
    this.to = to;
    this.slice = slice2;
    this.structure = structure;
  }
  apply(doc3) {
    if (this.structure && contentBetween(doc3, this.from, this.to))
      return StepResult.fail("Structure replace would overwrite content");
    return StepResult.fromReplace(doc3, this.from, this.to, this.slice);
  }
  getMap() {
    return new StepMap([this.from, this.to - this.from, this.slice.size]);
  }
  invert(doc3) {
    return new _ReplaceStep(this.from, this.from + this.slice.size, doc3.slice(this.from, this.to));
  }
  map(mapping) {
    let from2 = mapping.mapResult(this.from, 1), to = mapping.mapResult(this.to, -1);
    if (from2.deletedAcross && to.deletedAcross)
      return null;
    return new _ReplaceStep(from2.pos, Math.max(from2.pos, to.pos), this.slice, this.structure);
  }
  merge(other) {
    if (!(other instanceof _ReplaceStep) || other.structure || this.structure)
      return null;
    if (this.from + this.slice.size == other.from && !this.slice.openEnd && !other.slice.openStart) {
      let slice2 = this.slice.size + other.slice.size == 0 ? Slice.empty : new Slice(this.slice.content.append(other.slice.content), this.slice.openStart, other.slice.openEnd);
      return new _ReplaceStep(this.from, this.to + (other.to - other.from), slice2, this.structure);
    } else if (other.to == this.from && !this.slice.openStart && !other.slice.openEnd) {
      let slice2 = this.slice.size + other.slice.size == 0 ? Slice.empty : new Slice(other.slice.content.append(this.slice.content), other.slice.openStart, this.slice.openEnd);
      return new _ReplaceStep(other.from, this.to, slice2, this.structure);
    } else {
      return null;
    }
  }
  toJSON() {
    let json = { stepType: "replace", from: this.from, to: this.to };
    if (this.slice.size)
      json.slice = this.slice.toJSON();
    if (this.structure)
      json.structure = true;
    return json;
  }
  /**
  @internal
  */
  static fromJSON(schema, json) {
    if (typeof json.from != "number" || typeof json.to != "number")
      throw new RangeError("Invalid input for ReplaceStep.fromJSON");
    return new _ReplaceStep(json.from, json.to, Slice.fromJSON(schema, json.slice), !!json.structure);
  }
};
Step.jsonID("replace", ReplaceStep);
var ReplaceAroundStep = class _ReplaceAroundStep extends Step {
  /**
  Create a replace-around step with the given range and gap.
  `insert` should be the point in the slice into which the content
  of the gap should be moved. `structure` has the same meaning as
  it has in the [`ReplaceStep`](https://prosemirror.net/docs/ref/#transform.ReplaceStep) class.
  */
  constructor(from2, to, gapFrom, gapTo, slice2, insert2, structure = false) {
    super();
    this.from = from2;
    this.to = to;
    this.gapFrom = gapFrom;
    this.gapTo = gapTo;
    this.slice = slice2;
    this.insert = insert2;
    this.structure = structure;
  }
  apply(doc3) {
    if (this.structure && (contentBetween(doc3, this.from, this.gapFrom) || contentBetween(doc3, this.gapTo, this.to)))
      return StepResult.fail("Structure gap-replace would overwrite content");
    let gap = doc3.slice(this.gapFrom, this.gapTo);
    if (gap.openStart || gap.openEnd)
      return StepResult.fail("Gap is not a flat range");
    let inserted = this.slice.insertAt(this.insert, gap.content);
    if (!inserted)
      return StepResult.fail("Content does not fit in gap");
    return StepResult.fromReplace(doc3, this.from, this.to, inserted);
  }
  getMap() {
    return new StepMap([
      this.from,
      this.gapFrom - this.from,
      this.insert,
      this.gapTo,
      this.to - this.gapTo,
      this.slice.size - this.insert
    ]);
  }
  invert(doc3) {
    let gap = this.gapTo - this.gapFrom;
    return new _ReplaceAroundStep(this.from, this.from + this.slice.size + gap, this.from + this.insert, this.from + this.insert + gap, doc3.slice(this.from, this.to).removeBetween(this.gapFrom - this.from, this.gapTo - this.from), this.gapFrom - this.from, this.structure);
  }
  map(mapping) {
    let from2 = mapping.mapResult(this.from, 1), to = mapping.mapResult(this.to, -1);
    let gapFrom = this.from == this.gapFrom ? from2.pos : mapping.map(this.gapFrom, -1);
    let gapTo = this.to == this.gapTo ? to.pos : mapping.map(this.gapTo, 1);
    if (from2.deletedAcross && to.deletedAcross || gapFrom < from2.pos || gapTo > to.pos)
      return null;
    return new _ReplaceAroundStep(from2.pos, to.pos, gapFrom, gapTo, this.slice, this.insert, this.structure);
  }
  toJSON() {
    let json = {
      stepType: "replaceAround",
      from: this.from,
      to: this.to,
      gapFrom: this.gapFrom,
      gapTo: this.gapTo,
      insert: this.insert
    };
    if (this.slice.size)
      json.slice = this.slice.toJSON();
    if (this.structure)
      json.structure = true;
    return json;
  }
  /**
  @internal
  */
  static fromJSON(schema, json) {
    if (typeof json.from != "number" || typeof json.to != "number" || typeof json.gapFrom != "number" || typeof json.gapTo != "number" || typeof json.insert != "number")
      throw new RangeError("Invalid input for ReplaceAroundStep.fromJSON");
    return new _ReplaceAroundStep(json.from, json.to, json.gapFrom, json.gapTo, Slice.fromJSON(schema, json.slice), json.insert, !!json.structure);
  }
};
Step.jsonID("replaceAround", ReplaceAroundStep);
function contentBetween(doc3, from2, to) {
  let $from = doc3.resolve(from2), dist = to - from2, depth = $from.depth;
  while (dist > 0 && depth > 0 && $from.indexAfter(depth) == $from.node(depth).childCount) {
    depth--;
    dist--;
  }
  if (dist > 0) {
    let next = $from.node(depth).maybeChild($from.indexAfter(depth));
    while (dist > 0) {
      if (!next || next.isLeaf)
        return true;
      next = next.firstChild;
      dist--;
    }
  }
  return false;
}
function addMark(tr2, from2, to, mark) {
  let removed = [], added = [];
  let removing, adding;
  tr2.doc.nodesBetween(from2, to, (node, pos, parent) => {
    if (!node.isInline)
      return;
    let marks = node.marks;
    if (!mark.isInSet(marks) && parent.type.allowsMarkType(mark.type)) {
      let start = Math.max(pos, from2), end = Math.min(pos + node.nodeSize, to);
      let newSet = mark.addToSet(marks);
      for (let i = 0; i < marks.length; i++) {
        if (!marks[i].isInSet(newSet)) {
          if (removing && removing.to == start && removing.mark.eq(marks[i]))
            removing.to = end;
          else
            removed.push(removing = new RemoveMarkStep(start, end, marks[i]));
        }
      }
      if (adding && adding.to == start)
        adding.to = end;
      else
        added.push(adding = new AddMarkStep(start, end, mark));
    }
  });
  removed.forEach((s) => tr2.step(s));
  added.forEach((s) => tr2.step(s));
}
function removeMark(tr2, from2, to, mark) {
  let matched = [], step = 0;
  tr2.doc.nodesBetween(from2, to, (node, pos) => {
    if (!node.isInline)
      return;
    step++;
    let toRemove = null;
    if (mark instanceof MarkType) {
      let set = node.marks, found2;
      while (found2 = mark.isInSet(set)) {
        (toRemove || (toRemove = [])).push(found2);
        set = found2.removeFromSet(set);
      }
    } else if (mark) {
      if (mark.isInSet(node.marks))
        toRemove = [mark];
    } else {
      toRemove = node.marks;
    }
    if (toRemove && toRemove.length) {
      let end = Math.min(pos + node.nodeSize, to);
      for (let i = 0; i < toRemove.length; i++) {
        let style2 = toRemove[i], found2;
        for (let j = 0; j < matched.length; j++) {
          let m = matched[j];
          if (m.step == step - 1 && style2.eq(matched[j].style))
            found2 = m;
        }
        if (found2) {
          found2.to = end;
          found2.step = step;
        } else {
          matched.push({ style: style2, from: Math.max(pos, from2), to: end, step });
        }
      }
    }
  });
  matched.forEach((m) => tr2.step(new RemoveMarkStep(m.from, m.to, m.style)));
}
function clearIncompatible(tr2, pos, parentType, match = parentType.contentMatch, clearNewlines = true) {
  let node = tr2.doc.nodeAt(pos);
  let replSteps = [], cur = pos + 1;
  for (let i = 0; i < node.childCount; i++) {
    let child = node.child(i), end = cur + child.nodeSize;
    let allowed = match.matchType(child.type);
    if (!allowed) {
      replSteps.push(new ReplaceStep(cur, end, Slice.empty));
    } else {
      match = allowed;
      for (let j = 0; j < child.marks.length; j++)
        if (!parentType.allowsMarkType(child.marks[j].type))
          tr2.step(new RemoveMarkStep(cur, end, child.marks[j]));
      if (clearNewlines && child.isText && parentType.whitespace != "pre") {
        let m, newline = /\r?\n|\r/g, slice2;
        while (m = newline.exec(child.text)) {
          if (!slice2)
            slice2 = new Slice(Fragment.from(parentType.schema.text(" ", parentType.allowedMarks(child.marks))), 0, 0);
          replSteps.push(new ReplaceStep(cur + m.index, cur + m.index + m[0].length, slice2));
        }
      }
    }
    cur = end;
  }
  if (!match.validEnd) {
    let fill = match.fillBefore(Fragment.empty, true);
    tr2.replace(cur, cur, new Slice(fill, 0, 0));
  }
  for (let i = replSteps.length - 1; i >= 0; i--)
    tr2.step(replSteps[i]);
}
function canCut(node, start, end) {
  return (start == 0 || node.canReplace(start, node.childCount)) && (end == node.childCount || node.canReplace(0, end));
}
function liftTarget(range) {
  let parent = range.parent;
  let content = parent.content.cutByIndex(range.startIndex, range.endIndex);
  for (let depth = range.depth, contentBefore = 0, contentAfter = 0; ; --depth) {
    let node = range.$from.node(depth);
    let index = range.$from.index(depth) + contentBefore, endIndex = range.$to.indexAfter(depth) - contentAfter;
    if (depth < range.depth && node.canReplace(index, endIndex, content))
      return depth;
    if (depth == 0 || node.type.spec.isolating || !canCut(node, index, endIndex))
      break;
    if (index)
      contentBefore = 1;
    if (endIndex < node.childCount)
      contentAfter = 1;
  }
  return null;
}
function lift(tr2, range, target2) {
  let { $from, $to, depth } = range;
  let gapStart = $from.before(depth + 1), gapEnd = $to.after(depth + 1);
  let start = gapStart, end = gapEnd;
  let before = Fragment.empty, openStart = 0;
  for (let d2 = depth, splitting = false; d2 > target2; d2--)
    if (splitting || $from.index(d2) > 0) {
      splitting = true;
      before = Fragment.from($from.node(d2).copy(before));
      openStart++;
    } else {
      start--;
    }
  let after = Fragment.empty, openEnd = 0;
  for (let d2 = depth, splitting = false; d2 > target2; d2--)
    if (splitting || $to.after(d2 + 1) < $to.end(d2)) {
      splitting = true;
      after = Fragment.from($to.node(d2).copy(after));
      openEnd++;
    } else {
      end++;
    }
  tr2.step(new ReplaceAroundStep(start, end, gapStart, gapEnd, new Slice(before.append(after), openStart, openEnd), before.size - openStart, true));
}
function findWrapping(range, nodeType, attrs = null, innerRange = range) {
  let around = findWrappingOutside(range, nodeType);
  let inner2 = around && findWrappingInside(innerRange, nodeType);
  if (!inner2)
    return null;
  return around.map(withAttrs).concat({ type: nodeType, attrs }).concat(inner2.map(withAttrs));
}
function withAttrs(type) {
  return { type, attrs: null };
}
function findWrappingOutside(range, type) {
  let { parent, startIndex, endIndex } = range;
  let around = parent.contentMatchAt(startIndex).findWrapping(type);
  if (!around)
    return null;
  let outer = around.length ? around[0] : type;
  return parent.canReplaceWith(startIndex, endIndex, outer) ? around : null;
}
function findWrappingInside(range, type) {
  let { parent, startIndex, endIndex } = range;
  let inner2 = parent.child(startIndex);
  let inside = type.contentMatch.findWrapping(inner2.type);
  if (!inside)
    return null;
  let lastType = inside.length ? inside[inside.length - 1] : type;
  let innerMatch = lastType.contentMatch;
  for (let i = startIndex; innerMatch && i < endIndex; i++)
    innerMatch = innerMatch.matchType(parent.child(i).type);
  if (!innerMatch || !innerMatch.validEnd)
    return null;
  return inside;
}
function wrap(tr2, range, wrappers) {
  let content = Fragment.empty;
  for (let i = wrappers.length - 1; i >= 0; i--) {
    if (content.size) {
      let match = wrappers[i].type.contentMatch.matchFragment(content);
      if (!match || !match.validEnd)
        throw new RangeError("Wrapper type given to Transform.wrap does not form valid content of its parent wrapper");
    }
    content = Fragment.from(wrappers[i].type.create(wrappers[i].attrs, content));
  }
  let start = range.start, end = range.end;
  tr2.step(new ReplaceAroundStep(start, end, start, end, new Slice(content, 0, 0), wrappers.length, true));
}
function setBlockType(tr2, from2, to, type, attrs) {
  if (!type.isTextblock)
    throw new RangeError("Type given to setBlockType should be a textblock");
  let mapFrom = tr2.steps.length;
  tr2.doc.nodesBetween(from2, to, (node, pos) => {
    let attrsHere = typeof attrs == "function" ? attrs(node) : attrs;
    if (node.isTextblock && !node.hasMarkup(type, attrsHere) && canChangeType(tr2.doc, tr2.mapping.slice(mapFrom).map(pos), type)) {
      let convertNewlines = null;
      if (type.schema.linebreakReplacement) {
        let pre = type.whitespace == "pre", supportLinebreak = !!type.contentMatch.matchType(type.schema.linebreakReplacement);
        if (pre && !supportLinebreak)
          convertNewlines = false;
        else if (!pre && supportLinebreak)
          convertNewlines = true;
      }
      if (convertNewlines === false)
        replaceLinebreaks(tr2, node, pos, mapFrom);
      clearIncompatible(tr2, tr2.mapping.slice(mapFrom).map(pos, 1), type, void 0, convertNewlines === null);
      let mapping = tr2.mapping.slice(mapFrom);
      let startM = mapping.map(pos, 1), endM = mapping.map(pos + node.nodeSize, 1);
      tr2.step(new ReplaceAroundStep(startM, endM, startM + 1, endM - 1, new Slice(Fragment.from(type.create(attrsHere, null, node.marks)), 0, 0), 1, true));
      if (convertNewlines === true)
        replaceNewlines(tr2, node, pos, mapFrom);
      return false;
    }
  });
}
function replaceNewlines(tr2, node, pos, mapFrom) {
  node.forEach((child, offset) => {
    if (child.isText) {
      let m, newline = /\r?\n|\r/g;
      while (m = newline.exec(child.text)) {
        let start = tr2.mapping.slice(mapFrom).map(pos + 1 + offset + m.index);
        tr2.replaceWith(start, start + 1, node.type.schema.linebreakReplacement.create());
      }
    }
  });
}
function replaceLinebreaks(tr2, node, pos, mapFrom) {
  node.forEach((child, offset) => {
    if (child.type == child.type.schema.linebreakReplacement) {
      let start = tr2.mapping.slice(mapFrom).map(pos + 1 + offset);
      tr2.replaceWith(start, start + 1, node.type.schema.text("\n"));
    }
  });
}
function canChangeType(doc3, pos, type) {
  let $pos = doc3.resolve(pos), index = $pos.index();
  return $pos.parent.canReplaceWith(index, index + 1, type);
}
function setNodeMarkup(tr2, pos, type, attrs, marks) {
  let node = tr2.doc.nodeAt(pos);
  if (!node)
    throw new RangeError("No node at given position");
  if (!type)
    type = node.type;
  let newNode = type.create(attrs, null, marks || node.marks);
  if (node.isLeaf)
    return tr2.replaceWith(pos, pos + node.nodeSize, newNode);
  if (!type.validContent(node.content))
    throw new RangeError("Invalid content for node type " + type.name);
  tr2.step(new ReplaceAroundStep(pos, pos + node.nodeSize, pos + 1, pos + node.nodeSize - 1, new Slice(Fragment.from(newNode), 0, 0), 1, true));
}
function canSplit(doc3, pos, depth = 1, typesAfter) {
  let $pos = doc3.resolve(pos), base2 = $pos.depth - depth;
  let innerType = typesAfter && typesAfter[typesAfter.length - 1] || $pos.parent;
  if (base2 < 0 || $pos.parent.type.spec.isolating || !$pos.parent.canReplace($pos.index(), $pos.parent.childCount) || !innerType.type.validContent($pos.parent.content.cutByIndex($pos.index(), $pos.parent.childCount)))
    return false;
  for (let d2 = $pos.depth - 1, i = depth - 2; d2 > base2; d2--, i--) {
    let node = $pos.node(d2), index2 = $pos.index(d2);
    if (node.type.spec.isolating)
      return false;
    let rest = node.content.cutByIndex(index2, node.childCount);
    let overrideChild = typesAfter && typesAfter[i + 1];
    if (overrideChild)
      rest = rest.replaceChild(0, overrideChild.type.create(overrideChild.attrs));
    let after = typesAfter && typesAfter[i] || node;
    if (!node.canReplace(index2 + 1, node.childCount) || !after.type.validContent(rest))
      return false;
  }
  let index = $pos.indexAfter(base2);
  let baseType = typesAfter && typesAfter[0];
  return $pos.node(base2).canReplaceWith(index, index, baseType ? baseType.type : $pos.node(base2 + 1).type);
}
function split(tr2, pos, depth = 1, typesAfter) {
  let $pos = tr2.doc.resolve(pos), before = Fragment.empty, after = Fragment.empty;
  for (let d2 = $pos.depth, e = $pos.depth - depth, i = depth - 1; d2 > e; d2--, i--) {
    before = Fragment.from($pos.node(d2).copy(before));
    let typeAfter = typesAfter && typesAfter[i];
    after = Fragment.from(typeAfter ? typeAfter.type.create(typeAfter.attrs, after) : $pos.node(d2).copy(after));
  }
  tr2.step(new ReplaceStep(pos, pos, new Slice(before.append(after), depth, depth), true));
}
function canJoin(doc3, pos) {
  let $pos = doc3.resolve(pos), index = $pos.index();
  return joinable2($pos.nodeBefore, $pos.nodeAfter) && $pos.parent.canReplace(index, index + 1);
}
function canAppendWithSubstitutedLinebreaks(a2, b2) {
  if (!b2.content.size)
    a2.type.compatibleContent(b2.type);
  let match = a2.contentMatchAt(a2.childCount);
  let { linebreakReplacement } = a2.type.schema;
  for (let i = 0; i < b2.childCount; i++) {
    let child = b2.child(i);
    let type = child.type == linebreakReplacement ? a2.type.schema.nodes.text : child.type;
    match = match.matchType(type);
    if (!match)
      return false;
    if (!a2.type.allowsMarks(child.marks))
      return false;
  }
  return match.validEnd;
}
function joinable2(a2, b2) {
  return !!(a2 && b2 && !a2.isLeaf && canAppendWithSubstitutedLinebreaks(a2, b2));
}
function joinPoint(doc3, pos, dir = -1) {
  let $pos = doc3.resolve(pos);
  for (let d2 = $pos.depth; ; d2--) {
    let before, after, index = $pos.index(d2);
    if (d2 == $pos.depth) {
      before = $pos.nodeBefore;
      after = $pos.nodeAfter;
    } else if (dir > 0) {
      before = $pos.node(d2 + 1);
      index++;
      after = $pos.node(d2).maybeChild(index);
    } else {
      before = $pos.node(d2).maybeChild(index - 1);
      after = $pos.node(d2 + 1);
    }
    if (before && !before.isTextblock && joinable2(before, after) && $pos.node(d2).canReplace(index, index + 1))
      return pos;
    if (d2 == 0)
      break;
    pos = dir < 0 ? $pos.before(d2) : $pos.after(d2);
  }
}
function join(tr2, pos, depth) {
  let convertNewlines = null;
  let { linebreakReplacement } = tr2.doc.type.schema;
  let $before = tr2.doc.resolve(pos - depth), beforeType = $before.node().type;
  if (linebreakReplacement && beforeType.inlineContent) {
    let pre = beforeType.whitespace == "pre";
    let supportLinebreak = !!beforeType.contentMatch.matchType(linebreakReplacement);
    if (pre && !supportLinebreak)
      convertNewlines = false;
    else if (!pre && supportLinebreak)
      convertNewlines = true;
  }
  let mapFrom = tr2.steps.length;
  if (convertNewlines === false) {
    let $after = tr2.doc.resolve(pos + depth);
    replaceLinebreaks(tr2, $after.node(), $after.before(), mapFrom);
  }
  if (beforeType.inlineContent)
    clearIncompatible(tr2, pos + depth - 1, beforeType, $before.node().contentMatchAt($before.index()), convertNewlines == null);
  let mapping = tr2.mapping.slice(mapFrom), start = mapping.map(pos - depth);
  tr2.step(new ReplaceStep(start, mapping.map(pos + depth, -1), Slice.empty, true));
  if (convertNewlines === true) {
    let $full = tr2.doc.resolve(start);
    replaceNewlines(tr2, $full.node(), $full.before(), tr2.steps.length);
  }
  return tr2;
}
function insertPoint(doc3, pos, nodeType) {
  let $pos = doc3.resolve(pos);
  if ($pos.parent.canReplaceWith($pos.index(), $pos.index(), nodeType))
    return pos;
  if ($pos.parentOffset == 0)
    for (let d2 = $pos.depth - 1; d2 >= 0; d2--) {
      let index = $pos.index(d2);
      if ($pos.node(d2).canReplaceWith(index, index, nodeType))
        return $pos.before(d2 + 1);
      if (index > 0)
        return null;
    }
  if ($pos.parentOffset == $pos.parent.content.size)
    for (let d2 = $pos.depth - 1; d2 >= 0; d2--) {
      let index = $pos.indexAfter(d2);
      if ($pos.node(d2).canReplaceWith(index, index, nodeType))
        return $pos.after(d2 + 1);
      if (index < $pos.node(d2).childCount)
        return null;
    }
  return null;
}
function dropPoint(doc3, pos, slice2) {
  let $pos = doc3.resolve(pos);
  if (!slice2.content.size)
    return pos;
  let content = slice2.content;
  for (let i = 0; i < slice2.openStart; i++)
    content = content.firstChild.content;
  for (let pass = 1; pass <= (slice2.openStart == 0 && slice2.size ? 2 : 1); pass++) {
    for (let d2 = $pos.depth; d2 >= 0; d2--) {
      let bias = d2 == $pos.depth ? 0 : $pos.pos <= ($pos.start(d2 + 1) + $pos.end(d2 + 1)) / 2 ? -1 : 1;
      let insertPos = $pos.index(d2) + (bias > 0 ? 1 : 0);
      let parent = $pos.node(d2), fits = false;
      if (pass == 1) {
        fits = parent.canReplace(insertPos, insertPos, content);
      } else {
        let wrapping = parent.contentMatchAt(insertPos).findWrapping(content.firstChild.type);
        fits = wrapping && parent.canReplaceWith(insertPos, insertPos, wrapping[0]);
      }
      if (fits)
        return bias == 0 ? $pos.pos : bias < 0 ? $pos.before(d2 + 1) : $pos.after(d2 + 1);
    }
  }
  return null;
}
function replaceStep(doc3, from2, to = from2, slice2 = Slice.empty) {
  if (from2 == to && !slice2.size)
    return null;
  let $from = doc3.resolve(from2), $to = doc3.resolve(to);
  if (fitsTrivially($from, $to, slice2))
    return new ReplaceStep(from2, to, slice2);
  return new Fitter($from, $to, slice2).fit();
}
function fitsTrivially($from, $to, slice2) {
  return !slice2.openStart && !slice2.openEnd && $from.start() == $to.start() && $from.parent.canReplace($from.index(), $to.index(), slice2.content);
}
var Fitter = class {
  constructor($from, $to, unplaced) {
    this.$from = $from;
    this.$to = $to;
    this.unplaced = unplaced;
    this.frontier = [];
    this.placed = Fragment.empty;
    for (let i = 0; i <= $from.depth; i++) {
      let node = $from.node(i);
      this.frontier.push({
        type: node.type,
        match: node.contentMatchAt($from.indexAfter(i))
      });
    }
    for (let i = $from.depth; i > 0; i--)
      this.placed = Fragment.from($from.node(i).copy(this.placed));
  }
  get depth() {
    return this.frontier.length - 1;
  }
  fit() {
    while (this.unplaced.size) {
      let fit = this.findFittable();
      if (fit)
        this.placeNodes(fit);
      else
        this.openMore() || this.dropNode();
    }
    let moveInline = this.mustMoveInline(), placedSize = this.placed.size - this.depth - this.$from.depth;
    let $from = this.$from, $to = this.close(moveInline < 0 ? this.$to : $from.doc.resolve(moveInline));
    if (!$to)
      return null;
    let content = this.placed, openStart = $from.depth, openEnd = $to.depth;
    while (openStart && openEnd && content.childCount == 1) {
      content = content.firstChild.content;
      openStart--;
      openEnd--;
    }
    let slice2 = new Slice(content, openStart, openEnd);
    if (moveInline > -1)
      return new ReplaceAroundStep($from.pos, moveInline, this.$to.pos, this.$to.end(), slice2, placedSize);
    if (slice2.size || $from.pos != this.$to.pos)
      return new ReplaceStep($from.pos, $to.pos, slice2);
    return null;
  }
  // Find a position on the start spine of `this.unplaced` that has
  // content that can be moved somewhere on the frontier. Returns two
  // depths, one for the slice and one for the frontier.
  findFittable() {
    let startDepth = this.unplaced.openStart;
    for (let cur = this.unplaced.content, d2 = 0, openEnd = this.unplaced.openEnd; d2 < startDepth; d2++) {
      let node = cur.firstChild;
      if (cur.childCount > 1)
        openEnd = 0;
      if (node.type.spec.isolating && openEnd <= d2) {
        startDepth = d2;
        break;
      }
      cur = node.content;
    }
    for (let pass = 1; pass <= 2; pass++) {
      for (let sliceDepth = pass == 1 ? startDepth : this.unplaced.openStart; sliceDepth >= 0; sliceDepth--) {
        let fragment, parent = null;
        if (sliceDepth) {
          parent = contentAt(this.unplaced.content, sliceDepth - 1).firstChild;
          fragment = parent.content;
        } else {
          fragment = this.unplaced.content;
        }
        let first2 = fragment.firstChild;
        for (let frontierDepth = this.depth; frontierDepth >= 0; frontierDepth--) {
          let { type, match } = this.frontier[frontierDepth], wrap2, inject = null;
          if (pass == 1 && (first2 ? match.matchType(first2.type) || (inject = match.fillBefore(Fragment.from(first2), false)) : parent && type.compatibleContent(parent.type)))
            return { sliceDepth, frontierDepth, parent, inject };
          else if (pass == 2 && first2 && (wrap2 = match.findWrapping(first2.type)))
            return { sliceDepth, frontierDepth, parent, wrap: wrap2 };
          if (parent && match.matchType(parent.type))
            break;
        }
      }
    }
  }
  openMore() {
    let { content, openStart, openEnd } = this.unplaced;
    let inner2 = contentAt(content, openStart);
    if (!inner2.childCount || inner2.firstChild.isLeaf)
      return false;
    this.unplaced = new Slice(content, openStart + 1, Math.max(openEnd, inner2.size + openStart >= content.size - openEnd ? openStart + 1 : 0));
    return true;
  }
  dropNode() {
    let { content, openStart, openEnd } = this.unplaced;
    let inner2 = contentAt(content, openStart);
    if (inner2.childCount <= 1 && openStart > 0) {
      let openAtEnd = content.size - openStart <= openStart + inner2.size;
      this.unplaced = new Slice(dropFromFragment(content, openStart - 1, 1), openStart - 1, openAtEnd ? openStart - 1 : openEnd);
    } else {
      this.unplaced = new Slice(dropFromFragment(content, openStart, 1), openStart, openEnd);
    }
  }
  // Move content from the unplaced slice at `sliceDepth` to the
  // frontier node at `frontierDepth`. Close that frontier node when
  // applicable.
  placeNodes({ sliceDepth, frontierDepth, parent, inject, wrap: wrap2 }) {
    while (this.depth > frontierDepth)
      this.closeFrontierNode();
    if (wrap2)
      for (let i = 0; i < wrap2.length; i++)
        this.openFrontierNode(wrap2[i]);
    let slice2 = this.unplaced, fragment = parent ? parent.content : slice2.content;
    let openStart = slice2.openStart - sliceDepth;
    let taken = 0, add = [];
    let { match, type } = this.frontier[frontierDepth];
    if (inject) {
      for (let i = 0; i < inject.childCount; i++)
        add.push(inject.child(i));
      match = match.matchFragment(inject);
    }
    let openEndCount = fragment.size + sliceDepth - (slice2.content.size - slice2.openEnd);
    while (taken < fragment.childCount) {
      let next = fragment.child(taken), matches2 = match.matchType(next.type);
      if (!matches2)
        break;
      taken++;
      if (taken > 1 || openStart == 0 || next.content.size) {
        match = matches2;
        add.push(closeNodeStart(next.mark(type.allowedMarks(next.marks)), taken == 1 ? openStart : 0, taken == fragment.childCount ? openEndCount : -1));
      }
    }
    let toEnd = taken == fragment.childCount;
    if (!toEnd)
      openEndCount = -1;
    this.placed = addToFragment(this.placed, frontierDepth, Fragment.from(add));
    this.frontier[frontierDepth].match = match;
    if (toEnd && openEndCount < 0 && parent && parent.type == this.frontier[this.depth].type && this.frontier.length > 1)
      this.closeFrontierNode();
    for (let i = 0, cur = fragment; i < openEndCount; i++) {
      let node = cur.lastChild;
      this.frontier.push({ type: node.type, match: node.contentMatchAt(node.childCount) });
      cur = node.content;
    }
    this.unplaced = !toEnd ? new Slice(dropFromFragment(slice2.content, sliceDepth, taken), slice2.openStart, slice2.openEnd) : sliceDepth == 0 ? Slice.empty : new Slice(dropFromFragment(slice2.content, sliceDepth - 1, 1), sliceDepth - 1, openEndCount < 0 ? slice2.openEnd : sliceDepth - 1);
  }
  mustMoveInline() {
    if (!this.$to.parent.isTextblock)
      return -1;
    let top = this.frontier[this.depth], level;
    if (!top.type.isTextblock || !contentAfterFits(this.$to, this.$to.depth, top.type, top.match, false) || this.$to.depth == this.depth && (level = this.findCloseLevel(this.$to)) && level.depth == this.depth)
      return -1;
    let { depth } = this.$to, after = this.$to.after(depth);
    while (depth > 1 && after == this.$to.end(--depth))
      ++after;
    return after;
  }
  findCloseLevel($to) {
    scan: for (let i = Math.min(this.depth, $to.depth); i >= 0; i--) {
      let { match, type } = this.frontier[i];
      let dropInner = i < $to.depth && $to.end(i + 1) == $to.pos + ($to.depth - (i + 1));
      let fit = contentAfterFits($to, i, type, match, dropInner);
      if (!fit)
        continue;
      for (let d2 = i - 1; d2 >= 0; d2--) {
        let { match: match2, type: type2 } = this.frontier[d2];
        let matches2 = contentAfterFits($to, d2, type2, match2, true);
        if (!matches2 || matches2.childCount)
          continue scan;
      }
      return { depth: i, fit, move: dropInner ? $to.doc.resolve($to.after(i + 1)) : $to };
    }
  }
  close($to) {
    let close3 = this.findCloseLevel($to);
    if (!close3)
      return null;
    while (this.depth > close3.depth)
      this.closeFrontierNode();
    if (close3.fit.childCount)
      this.placed = addToFragment(this.placed, close3.depth, close3.fit);
    $to = close3.move;
    for (let d2 = close3.depth + 1; d2 <= $to.depth; d2++) {
      let node = $to.node(d2), add = node.type.contentMatch.fillBefore(node.content, true, $to.index(d2));
      this.openFrontierNode(node.type, node.attrs, add);
    }
    return $to;
  }
  openFrontierNode(type, attrs = null, content) {
    let top = this.frontier[this.depth];
    top.match = top.match.matchType(type);
    this.placed = addToFragment(this.placed, this.depth, Fragment.from(type.create(attrs, content)));
    this.frontier.push({ type, match: type.contentMatch });
  }
  closeFrontierNode() {
    let open2 = this.frontier.pop();
    let add = open2.match.fillBefore(Fragment.empty, true);
    if (add.childCount)
      this.placed = addToFragment(this.placed, this.frontier.length, add);
  }
};
function dropFromFragment(fragment, depth, count) {
  if (depth == 0)
    return fragment.cutByIndex(count, fragment.childCount);
  return fragment.replaceChild(0, fragment.firstChild.copy(dropFromFragment(fragment.firstChild.content, depth - 1, count)));
}
function addToFragment(fragment, depth, content) {
  if (depth == 0)
    return fragment.append(content);
  return fragment.replaceChild(fragment.childCount - 1, fragment.lastChild.copy(addToFragment(fragment.lastChild.content, depth - 1, content)));
}
function contentAt(fragment, depth) {
  for (let i = 0; i < depth; i++)
    fragment = fragment.firstChild.content;
  return fragment;
}
function closeNodeStart(node, openStart, openEnd) {
  if (openStart <= 0)
    return node;
  let frag = node.content;
  if (openStart > 1)
    frag = frag.replaceChild(0, closeNodeStart(frag.firstChild, openStart - 1, frag.childCount == 1 ? openEnd - 1 : 0));
  if (openStart > 0) {
    frag = node.type.contentMatch.fillBefore(frag).append(frag);
    if (openEnd <= 0)
      frag = frag.append(node.type.contentMatch.matchFragment(frag).fillBefore(Fragment.empty, true));
  }
  return node.copy(frag);
}
function contentAfterFits($to, depth, type, match, open2) {
  let node = $to.node(depth), index = open2 ? $to.indexAfter(depth) : $to.index(depth);
  if (index == node.childCount && !type.compatibleContent(node.type))
    return null;
  let fit = match.fillBefore(node.content, true, index);
  return fit && !invalidMarks(type, node.content, index) ? fit : null;
}
function invalidMarks(type, fragment, start) {
  for (let i = start; i < fragment.childCount; i++)
    if (!type.allowsMarks(fragment.child(i).marks))
      return true;
  return false;
}
function definesContent(type) {
  return type.spec.defining || type.spec.definingForContent;
}
function replaceRange(tr2, from2, to, slice2) {
  if (!slice2.size)
    return tr2.deleteRange(from2, to);
  let $from = tr2.doc.resolve(from2), $to = tr2.doc.resolve(to);
  if (fitsTrivially($from, $to, slice2))
    return tr2.step(new ReplaceStep(from2, to, slice2));
  let targetDepths = coveredDepths($from, $to);
  if (targetDepths[targetDepths.length - 1] == 0)
    targetDepths.pop();
  let preferredTarget = -($from.depth + 1);
  targetDepths.unshift(preferredTarget);
  for (let d2 = $from.depth, pos = $from.pos - 1; d2 > 0; d2--, pos--) {
    let spec = $from.node(d2).type.spec;
    if (spec.defining || spec.definingAsContext || spec.isolating)
      break;
    if (targetDepths.indexOf(d2) > -1)
      preferredTarget = d2;
    else if ($from.before(d2) == pos)
      targetDepths.splice(1, 0, -d2);
  }
  let preferredTargetIndex = targetDepths.indexOf(preferredTarget);
  let leftNodes = [], preferredDepth = slice2.openStart;
  for (let content = slice2.content, i = 0; ; i++) {
    let node = content.firstChild;
    leftNodes.push(node);
    if (i == slice2.openStart)
      break;
    content = node.content;
  }
  for (let d2 = preferredDepth - 1; d2 >= 0; d2--) {
    let leftNode = leftNodes[d2], def = definesContent(leftNode.type);
    if (def && !leftNode.sameMarkup($from.node(Math.abs(preferredTarget) - 1)))
      preferredDepth = d2;
    else if (def || !leftNode.type.isTextblock)
      break;
  }
  for (let j = slice2.openStart; j >= 0; j--) {
    let openDepth = (j + preferredDepth + 1) % (slice2.openStart + 1);
    let insert2 = leftNodes[openDepth];
    if (!insert2)
      continue;
    for (let i = 0; i < targetDepths.length; i++) {
      let targetDepth = targetDepths[(i + preferredTargetIndex) % targetDepths.length], expand = true;
      if (targetDepth < 0) {
        expand = false;
        targetDepth = -targetDepth;
      }
      let parent = $from.node(targetDepth - 1), index = $from.index(targetDepth - 1);
      if (parent.canReplaceWith(index, index, insert2.type, insert2.marks))
        return tr2.replace($from.before(targetDepth), expand ? $to.after(targetDepth) : to, new Slice(closeFragment(slice2.content, 0, slice2.openStart, openDepth), openDepth, slice2.openEnd));
    }
  }
  let startSteps = tr2.steps.length;
  for (let i = targetDepths.length - 1; i >= 0; i--) {
    tr2.replace(from2, to, slice2);
    if (tr2.steps.length > startSteps)
      break;
    let depth = targetDepths[i];
    if (depth < 0)
      continue;
    from2 = $from.before(depth);
    to = $to.after(depth);
  }
}
function closeFragment(fragment, depth, oldOpen, newOpen, parent) {
  if (depth < oldOpen) {
    let first2 = fragment.firstChild;
    fragment = fragment.replaceChild(0, first2.copy(closeFragment(first2.content, depth + 1, oldOpen, newOpen, first2)));
  }
  if (depth > newOpen) {
    let match = parent.contentMatchAt(0);
    let start = match.fillBefore(fragment).append(fragment);
    fragment = start.append(match.matchFragment(start).fillBefore(Fragment.empty, true));
  }
  return fragment;
}
function replaceRangeWith(tr2, from2, to, node) {
  if (!node.isInline && from2 == to && tr2.doc.resolve(from2).parent.content.size) {
    let point = insertPoint(tr2.doc, from2, node.type);
    if (point != null)
      from2 = to = point;
  }
  tr2.replaceRange(from2, to, new Slice(Fragment.from(node), 0, 0));
}
function deleteRange(tr2, from2, to) {
  let $from = tr2.doc.resolve(from2), $to = tr2.doc.resolve(to);
  let covered = coveredDepths($from, $to);
  for (let i = 0; i < covered.length; i++) {
    let depth = covered[i], last = i == covered.length - 1;
    if (last && depth == 0 || $from.node(depth).type.contentMatch.validEnd)
      return tr2.delete($from.start(depth), $to.end(depth));
    if (depth > 0 && (last || $from.node(depth - 1).canReplace($from.index(depth - 1), $to.indexAfter(depth - 1))))
      return tr2.delete($from.before(depth), $to.after(depth));
  }
  for (let d2 = 1; d2 <= $from.depth && d2 <= $to.depth; d2++) {
    if (from2 - $from.start(d2) == $from.depth - d2 && to > $from.end(d2) && $to.end(d2) - to != $to.depth - d2 && $from.start(d2 - 1) == $to.start(d2 - 1) && $from.node(d2 - 1).canReplace($from.index(d2 - 1), $to.index(d2 - 1)))
      return tr2.delete($from.before(d2), to);
  }
  tr2.delete(from2, to);
}
function coveredDepths($from, $to) {
  let result = [], minDepth = Math.min($from.depth, $to.depth);
  for (let d2 = minDepth; d2 >= 0; d2--) {
    let start = $from.start(d2);
    if (start < $from.pos - ($from.depth - d2) || $to.end(d2) > $to.pos + ($to.depth - d2) || $from.node(d2).type.spec.isolating || $to.node(d2).type.spec.isolating)
      break;
    if (start == $to.start(d2) || d2 == $from.depth && d2 == $to.depth && $from.parent.inlineContent && $to.parent.inlineContent && d2 && $to.start(d2 - 1) == start - 1)
      result.push(d2);
  }
  return result;
}
var AttrStep = class _AttrStep extends Step {
  /**
  Construct an attribute step.
  */
  constructor(pos, attr, value) {
    super();
    this.pos = pos;
    this.attr = attr;
    this.value = value;
  }
  apply(doc3) {
    let node = doc3.nodeAt(this.pos);
    if (!node)
      return StepResult.fail("No node at attribute step's position");
    let attrs = /* @__PURE__ */ Object.create(null);
    for (let name in node.attrs)
      attrs[name] = node.attrs[name];
    attrs[this.attr] = this.value;
    let updated = node.type.create(attrs, null, node.marks);
    return StepResult.fromReplace(doc3, this.pos, this.pos + 1, new Slice(Fragment.from(updated), 0, node.isLeaf ? 0 : 1));
  }
  getMap() {
    return StepMap.empty;
  }
  invert(doc3) {
    return new _AttrStep(this.pos, this.attr, doc3.nodeAt(this.pos).attrs[this.attr]);
  }
  map(mapping) {
    let pos = mapping.mapResult(this.pos, 1);
    return pos.deletedAfter ? null : new _AttrStep(pos.pos, this.attr, this.value);
  }
  toJSON() {
    return { stepType: "attr", pos: this.pos, attr: this.attr, value: this.value };
  }
  static fromJSON(schema, json) {
    if (typeof json.pos != "number" || typeof json.attr != "string")
      throw new RangeError("Invalid input for AttrStep.fromJSON");
    return new _AttrStep(json.pos, json.attr, json.value);
  }
};
Step.jsonID("attr", AttrStep);
var DocAttrStep = class _DocAttrStep extends Step {
  /**
  Construct an attribute step.
  */
  constructor(attr, value) {
    super();
    this.attr = attr;
    this.value = value;
  }
  apply(doc3) {
    let attrs = /* @__PURE__ */ Object.create(null);
    for (let name in doc3.attrs)
      attrs[name] = doc3.attrs[name];
    attrs[this.attr] = this.value;
    let updated = doc3.type.create(attrs, doc3.content, doc3.marks);
    return StepResult.ok(updated);
  }
  getMap() {
    return StepMap.empty;
  }
  invert(doc3) {
    return new _DocAttrStep(this.attr, doc3.attrs[this.attr]);
  }
  map(mapping) {
    return this;
  }
  toJSON() {
    return { stepType: "docAttr", attr: this.attr, value: this.value };
  }
  static fromJSON(schema, json) {
    if (typeof json.attr != "string")
      throw new RangeError("Invalid input for DocAttrStep.fromJSON");
    return new _DocAttrStep(json.attr, json.value);
  }
};
Step.jsonID("docAttr", DocAttrStep);
var TransformError = class extends Error {
};
TransformError = function TransformError2(message) {
  let err = Error.call(this, message);
  err.__proto__ = TransformError2.prototype;
  return err;
};
TransformError.prototype = Object.create(Error.prototype);
TransformError.prototype.constructor = TransformError;
TransformError.prototype.name = "TransformError";
var Transform = class {
  /**
  Create a transform that starts with the given document.
  */
  constructor(doc3) {
    this.doc = doc3;
    this.steps = [];
    this.docs = [];
    this.mapping = new Mapping();
  }
  /**
  The starting document.
  */
  get before() {
    return this.docs.length ? this.docs[0] : this.doc;
  }
  /**
  Apply a new step in this transform, saving the result. Throws an
  error when the step fails.
  */
  step(step) {
    let result = this.maybeStep(step);
    if (result.failed)
      throw new TransformError(result.failed);
    return this;
  }
  /**
  Try to apply a step in this transformation, ignoring it if it
  fails. Returns the step result.
  */
  maybeStep(step) {
    let result = step.apply(this.doc);
    if (!result.failed)
      this.addStep(step, result.doc);
    return result;
  }
  /**
  True when the document has been changed (when there are any
  steps).
  */
  get docChanged() {
    return this.steps.length > 0;
  }
  /**
  @internal
  */
  addStep(step, doc3) {
    this.docs.push(this.doc);
    this.steps.push(step);
    this.mapping.appendMap(step.getMap());
    this.doc = doc3;
  }
  /**
  Replace the part of the document between `from` and `to` with the
  given `slice`.
  */
  replace(from2, to = from2, slice2 = Slice.empty) {
    let step = replaceStep(this.doc, from2, to, slice2);
    if (step)
      this.step(step);
    return this;
  }
  /**
  Replace the given range with the given content, which may be a
  fragment, node, or array of nodes.
  */
  replaceWith(from2, to, content) {
    return this.replace(from2, to, new Slice(Fragment.from(content), 0, 0));
  }
  /**
  Delete the content between the given positions.
  */
  delete(from2, to) {
    return this.replace(from2, to, Slice.empty);
  }
  /**
  Insert the given content at the given position.
  */
  insert(pos, content) {
    return this.replaceWith(pos, pos, content);
  }
  /**
  Replace a range of the document with a given slice, using
  `from`, `to`, and the slice's
  [`openStart`](https://prosemirror.net/docs/ref/#model.Slice.openStart) property as hints, rather
  than fixed start and end points. This method may grow the
  replaced area or close open nodes in the slice in order to get a
  fit that is more in line with WYSIWYG expectations, by dropping
  fully covered parent nodes of the replaced region when they are
  marked [non-defining as
  context](https://prosemirror.net/docs/ref/#model.NodeSpec.definingAsContext), or including an
  open parent node from the slice that _is_ marked as [defining
  its content](https://prosemirror.net/docs/ref/#model.NodeSpec.definingForContent).
  
  This is the method, for example, to handle paste. The similar
  [`replace`](https://prosemirror.net/docs/ref/#transform.Transform.replace) method is a more
  primitive tool which will _not_ move the start and end of its given
  range, and is useful in situations where you need more precise
  control over what happens.
  */
  replaceRange(from2, to, slice2) {
    replaceRange(this, from2, to, slice2);
    return this;
  }
  /**
  Replace the given range with a node, but use `from` and `to` as
  hints, rather than precise positions. When from and to are the same
  and are at the start or end of a parent node in which the given
  node doesn't fit, this method may _move_ them out towards a parent
  that does allow the given node to be placed. When the given range
  completely covers a parent node, this method may completely replace
  that parent node.
  */
  replaceRangeWith(from2, to, node) {
    replaceRangeWith(this, from2, to, node);
    return this;
  }
  /**
  Delete the given range, expanding it to cover fully covered
  parent nodes until a valid replace is found.
  */
  deleteRange(from2, to) {
    deleteRange(this, from2, to);
    return this;
  }
  /**
  Split the content in the given range off from its parent, if there
  is sibling content before or after it, and move it up the tree to
  the depth specified by `target`. You'll probably want to use
  [`liftTarget`](https://prosemirror.net/docs/ref/#transform.liftTarget) to compute `target`, to make
  sure the lift is valid.
  */
  lift(range, target2) {
    lift(this, range, target2);
    return this;
  }
  /**
  Join the blocks around the given position. If depth is 2, their
  last and first siblings are also joined, and so on.
  */
  join(pos, depth = 1) {
    join(this, pos, depth);
    return this;
  }
  /**
  Wrap the given [range](https://prosemirror.net/docs/ref/#model.NodeRange) in the given set of wrappers.
  The wrappers are assumed to be valid in this position, and should
  probably be computed with [`findWrapping`](https://prosemirror.net/docs/ref/#transform.findWrapping).
  */
  wrap(range, wrappers) {
    wrap(this, range, wrappers);
    return this;
  }
  /**
  Set the type of all textblocks (partly) between `from` and `to` to
  the given node type with the given attributes.
  */
  setBlockType(from2, to = from2, type, attrs = null) {
    setBlockType(this, from2, to, type, attrs);
    return this;
  }
  /**
  Change the type, attributes, and/or marks of the node at `pos`.
  When `type` isn't given, the existing node type is preserved,
  */
  setNodeMarkup(pos, type, attrs = null, marks) {
    setNodeMarkup(this, pos, type, attrs, marks);
    return this;
  }
  /**
  Set a single attribute on a given node to a new value.
  The `pos` addresses the document content. Use `setDocAttribute`
  to set attributes on the document itself.
  */
  setNodeAttribute(pos, attr, value) {
    this.step(new AttrStep(pos, attr, value));
    return this;
  }
  /**
  Set a single attribute on the document to a new value.
  */
  setDocAttribute(attr, value) {
    this.step(new DocAttrStep(attr, value));
    return this;
  }
  /**
  Add a mark to the node at position `pos`.
  */
  addNodeMark(pos, mark) {
    this.step(new AddNodeMarkStep(pos, mark));
    return this;
  }
  /**
  Remove a mark (or all marks of the given type) from the node at
  position `pos`.
  */
  removeNodeMark(pos, mark) {
    let node = this.doc.nodeAt(pos);
    if (!node)
      throw new RangeError("No node at position " + pos);
    if (mark instanceof Mark) {
      if (mark.isInSet(node.marks))
        this.step(new RemoveNodeMarkStep(pos, mark));
    } else {
      let set = node.marks, found2, steps = [];
      while (found2 = mark.isInSet(set)) {
        steps.push(new RemoveNodeMarkStep(pos, found2));
        set = found2.removeFromSet(set);
      }
      for (let i = steps.length - 1; i >= 0; i--)
        this.step(steps[i]);
    }
    return this;
  }
  /**
  Split the node at the given position, and optionally, if `depth` is
  greater than one, any number of nodes above that. By default, the
  parts split off will inherit the node type of the original node.
  This can be changed by passing an array of types and attributes to
  use after the split (with the outermost nodes coming first).
  */
  split(pos, depth = 1, typesAfter) {
    split(this, pos, depth, typesAfter);
    return this;
  }
  /**
  Add the given mark to the inline content between `from` and `to`.
  */
  addMark(from2, to, mark) {
    addMark(this, from2, to, mark);
    return this;
  }
  /**
  Remove marks from inline nodes between `from` and `to`. When
  `mark` is a single mark, remove precisely that mark. When it is
  a mark type, remove all marks of that type. When it is null,
  remove all marks of any type.
  */
  removeMark(from2, to, mark) {
    removeMark(this, from2, to, mark);
    return this;
  }
  /**
  Removes all marks and nodes from the content of the node at
  `pos` that don't match the given new parent node type. Accepts
  an optional starting [content match](https://prosemirror.net/docs/ref/#model.ContentMatch) as
  third argument.
  */
  clearIncompatible(pos, parentType, match) {
    clearIncompatible(this, pos, parentType, match);
    return this;
  }
};

// ../../node_modules/.pnpm/prosemirror-state@1.4.4/node_modules/prosemirror-state/dist/index.js
var classesById = /* @__PURE__ */ Object.create(null);
var Selection = class {
  /**
  Initialize a selection with the head and anchor and ranges. If no
  ranges are given, constructs a single range across `$anchor` and
  `$head`.
  */
  constructor($anchor, $head, ranges) {
    this.$anchor = $anchor;
    this.$head = $head;
    this.ranges = ranges || [new SelectionRange($anchor.min($head), $anchor.max($head))];
  }
  /**
  The selection's anchor, as an unresolved position.
  */
  get anchor() {
    return this.$anchor.pos;
  }
  /**
  The selection's head.
  */
  get head() {
    return this.$head.pos;
  }
  /**
  The lower bound of the selection's main range.
  */
  get from() {
    return this.$from.pos;
  }
  /**
  The upper bound of the selection's main range.
  */
  get to() {
    return this.$to.pos;
  }
  /**
  The resolved lower  bound of the selection's main range.
  */
  get $from() {
    return this.ranges[0].$from;
  }
  /**
  The resolved upper bound of the selection's main range.
  */
  get $to() {
    return this.ranges[0].$to;
  }
  /**
  Indicates whether the selection contains any content.
  */
  get empty() {
    let ranges = this.ranges;
    for (let i = 0; i < ranges.length; i++)
      if (ranges[i].$from.pos != ranges[i].$to.pos)
        return false;
    return true;
  }
  /**
  Get the content of this selection as a slice.
  */
  content() {
    return this.$from.doc.slice(this.from, this.to, true);
  }
  /**
  Replace the selection with a slice or, if no slice is given,
  delete the selection. Will append to the given transaction.
  */
  replace(tr2, content = Slice.empty) {
    let lastNode = content.content.lastChild, lastParent = null;
    for (let i = 0; i < content.openEnd; i++) {
      lastParent = lastNode;
      lastNode = lastNode.lastChild;
    }
    let mapFrom = tr2.steps.length, ranges = this.ranges;
    for (let i = 0; i < ranges.length; i++) {
      let { $from, $to } = ranges[i], mapping = tr2.mapping.slice(mapFrom);
      tr2.replaceRange(mapping.map($from.pos), mapping.map($to.pos), i ? Slice.empty : content);
      if (i == 0)
        selectionToInsertionEnd(tr2, mapFrom, (lastNode ? lastNode.isInline : lastParent && lastParent.isTextblock) ? -1 : 1);
    }
  }
  /**
  Replace the selection with the given node, appending the changes
  to the given transaction.
  */
  replaceWith(tr2, node) {
    let mapFrom = tr2.steps.length, ranges = this.ranges;
    for (let i = 0; i < ranges.length; i++) {
      let { $from, $to } = ranges[i], mapping = tr2.mapping.slice(mapFrom);
      let from2 = mapping.map($from.pos), to = mapping.map($to.pos);
      if (i) {
        tr2.deleteRange(from2, to);
      } else {
        tr2.replaceRangeWith(from2, to, node);
        selectionToInsertionEnd(tr2, mapFrom, node.isInline ? -1 : 1);
      }
    }
  }
  /**
  Find a valid cursor or leaf node selection starting at the given
  position and searching back if `dir` is negative, and forward if
  positive. When `textOnly` is true, only consider cursor
  selections. Will return null when no valid selection position is
  found.
  */
  static findFrom($pos, dir, textOnly = false) {
    let inner2 = $pos.parent.inlineContent ? new TextSelection($pos) : findSelectionIn($pos.node(0), $pos.parent, $pos.pos, $pos.index(), dir, textOnly);
    if (inner2)
      return inner2;
    for (let depth = $pos.depth - 1; depth >= 0; depth--) {
      let found2 = dir < 0 ? findSelectionIn($pos.node(0), $pos.node(depth), $pos.before(depth + 1), $pos.index(depth), dir, textOnly) : findSelectionIn($pos.node(0), $pos.node(depth), $pos.after(depth + 1), $pos.index(depth) + 1, dir, textOnly);
      if (found2)
        return found2;
    }
    return null;
  }
  /**
  Find a valid cursor or leaf node selection near the given
  position. Searches forward first by default, but if `bias` is
  negative, it will search backwards first.
  */
  static near($pos, bias = 1) {
    return this.findFrom($pos, bias) || this.findFrom($pos, -bias) || new AllSelection($pos.node(0));
  }
  /**
  Find the cursor or leaf node selection closest to the start of
  the given document. Will return an
  [`AllSelection`](https://prosemirror.net/docs/ref/#state.AllSelection) if no valid position
  exists.
  */
  static atStart(doc3) {
    return findSelectionIn(doc3, doc3, 0, 0, 1) || new AllSelection(doc3);
  }
  /**
  Find the cursor or leaf node selection closest to the end of the
  given document.
  */
  static atEnd(doc3) {
    return findSelectionIn(doc3, doc3, doc3.content.size, doc3.childCount, -1) || new AllSelection(doc3);
  }
  /**
  Deserialize the JSON representation of a selection. Must be
  implemented for custom classes (as a static class method).
  */
  static fromJSON(doc3, json) {
    if (!json || !json.type)
      throw new RangeError("Invalid input for Selection.fromJSON");
    let cls = classesById[json.type];
    if (!cls)
      throw new RangeError(`No selection type ${json.type} defined`);
    return cls.fromJSON(doc3, json);
  }
  /**
  To be able to deserialize selections from JSON, custom selection
  classes must register themselves with an ID string, so that they
  can be disambiguated. Try to pick something that's unlikely to
  clash with classes from other modules.
  */
  static jsonID(id, selectionClass) {
    if (id in classesById)
      throw new RangeError("Duplicate use of selection JSON ID " + id);
    classesById[id] = selectionClass;
    selectionClass.prototype.jsonID = id;
    return selectionClass;
  }
  /**
  Get a [bookmark](https://prosemirror.net/docs/ref/#state.SelectionBookmark) for this selection,
  which is a value that can be mapped without having access to a
  current document, and later resolved to a real selection for a
  given document again. (This is used mostly by the history to
  track and restore old selections.) The default implementation of
  this method just converts the selection to a text selection and
  returns the bookmark for that.
  */
  getBookmark() {
    return TextSelection.between(this.$anchor, this.$head).getBookmark();
  }
};
Selection.prototype.visible = true;
var SelectionRange = class {
  /**
  Create a range.
  */
  constructor($from, $to) {
    this.$from = $from;
    this.$to = $to;
  }
};
var warnedAboutTextSelection = false;
function checkTextSelection($pos) {
  if (!warnedAboutTextSelection && !$pos.parent.inlineContent) {
    warnedAboutTextSelection = true;
    console["warn"]("TextSelection endpoint not pointing into a node with inline content (" + $pos.parent.type.name + ")");
  }
}
var TextSelection = class _TextSelection extends Selection {
  /**
  Construct a text selection between the given points.
  */
  constructor($anchor, $head = $anchor) {
    checkTextSelection($anchor);
    checkTextSelection($head);
    super($anchor, $head);
  }
  /**
  Returns a resolved position if this is a cursor selection (an
  empty text selection), and null otherwise.
  */
  get $cursor() {
    return this.$anchor.pos == this.$head.pos ? this.$head : null;
  }
  map(doc3, mapping) {
    let $head = doc3.resolve(mapping.map(this.head));
    if (!$head.parent.inlineContent)
      return Selection.near($head);
    let $anchor = doc3.resolve(mapping.map(this.anchor));
    return new _TextSelection($anchor.parent.inlineContent ? $anchor : $head, $head);
  }
  replace(tr2, content = Slice.empty) {
    super.replace(tr2, content);
    if (content == Slice.empty) {
      let marks = this.$from.marksAcross(this.$to);
      if (marks)
        tr2.ensureMarks(marks);
    }
  }
  eq(other) {
    return other instanceof _TextSelection && other.anchor == this.anchor && other.head == this.head;
  }
  getBookmark() {
    return new TextBookmark(this.anchor, this.head);
  }
  toJSON() {
    return { type: "text", anchor: this.anchor, head: this.head };
  }
  /**
  @internal
  */
  static fromJSON(doc3, json) {
    if (typeof json.anchor != "number" || typeof json.head != "number")
      throw new RangeError("Invalid input for TextSelection.fromJSON");
    return new _TextSelection(doc3.resolve(json.anchor), doc3.resolve(json.head));
  }
  /**
  Create a text selection from non-resolved positions.
  */
  static create(doc3, anchor, head = anchor) {
    let $anchor = doc3.resolve(anchor);
    return new this($anchor, head == anchor ? $anchor : doc3.resolve(head));
  }
  /**
  Return a text selection that spans the given positions or, if
  they aren't text positions, find a text selection near them.
  `bias` determines whether the method searches forward (default)
  or backwards (negative number) first. Will fall back to calling
  [`Selection.near`](https://prosemirror.net/docs/ref/#state.Selection^near) when the document
  doesn't contain a valid text position.
  */
  static between($anchor, $head, bias) {
    let dPos = $anchor.pos - $head.pos;
    if (!bias || dPos)
      bias = dPos >= 0 ? 1 : -1;
    if (!$head.parent.inlineContent) {
      let found2 = Selection.findFrom($head, bias, true) || Selection.findFrom($head, -bias, true);
      if (found2)
        $head = found2.$head;
      else
        return Selection.near($head, bias);
    }
    if (!$anchor.parent.inlineContent) {
      if (dPos == 0) {
        $anchor = $head;
      } else {
        $anchor = (Selection.findFrom($anchor, -bias, true) || Selection.findFrom($anchor, bias, true)).$anchor;
        if ($anchor.pos < $head.pos != dPos < 0)
          $anchor = $head;
      }
    }
    return new _TextSelection($anchor, $head);
  }
};
Selection.jsonID("text", TextSelection);
var TextBookmark = class _TextBookmark {
  constructor(anchor, head) {
    this.anchor = anchor;
    this.head = head;
  }
  map(mapping) {
    return new _TextBookmark(mapping.map(this.anchor), mapping.map(this.head));
  }
  resolve(doc3) {
    return TextSelection.between(doc3.resolve(this.anchor), doc3.resolve(this.head));
  }
};
var NodeSelection = class _NodeSelection extends Selection {
  /**
  Create a node selection. Does not verify the validity of its
  argument.
  */
  constructor($pos) {
    let node = $pos.nodeAfter;
    let $end = $pos.node(0).resolve($pos.pos + node.nodeSize);
    super($pos, $end);
    this.node = node;
  }
  map(doc3, mapping) {
    let { deleted, pos } = mapping.mapResult(this.anchor);
    let $pos = doc3.resolve(pos);
    if (deleted)
      return Selection.near($pos);
    return new _NodeSelection($pos);
  }
  content() {
    return new Slice(Fragment.from(this.node), 0, 0);
  }
  eq(other) {
    return other instanceof _NodeSelection && other.anchor == this.anchor;
  }
  toJSON() {
    return { type: "node", anchor: this.anchor };
  }
  getBookmark() {
    return new NodeBookmark(this.anchor);
  }
  /**
  @internal
  */
  static fromJSON(doc3, json) {
    if (typeof json.anchor != "number")
      throw new RangeError("Invalid input for NodeSelection.fromJSON");
    return new _NodeSelection(doc3.resolve(json.anchor));
  }
  /**
  Create a node selection from non-resolved positions.
  */
  static create(doc3, from2) {
    return new _NodeSelection(doc3.resolve(from2));
  }
  /**
  Determines whether the given node may be selected as a node
  selection.
  */
  static isSelectable(node) {
    return !node.isText && node.type.spec.selectable !== false;
  }
};
NodeSelection.prototype.visible = false;
Selection.jsonID("node", NodeSelection);
var NodeBookmark = class _NodeBookmark {
  constructor(anchor) {
    this.anchor = anchor;
  }
  map(mapping) {
    let { deleted, pos } = mapping.mapResult(this.anchor);
    return deleted ? new TextBookmark(pos, pos) : new _NodeBookmark(pos);
  }
  resolve(doc3) {
    let $pos = doc3.resolve(this.anchor), node = $pos.nodeAfter;
    if (node && NodeSelection.isSelectable(node))
      return new NodeSelection($pos);
    return Selection.near($pos);
  }
};
var AllSelection = class _AllSelection extends Selection {
  /**
  Create an all-selection over the given document.
  */
  constructor(doc3) {
    super(doc3.resolve(0), doc3.resolve(doc3.content.size));
  }
  replace(tr2, content = Slice.empty) {
    if (content == Slice.empty) {
      tr2.delete(0, tr2.doc.content.size);
      let sel = Selection.atStart(tr2.doc);
      if (!sel.eq(tr2.selection))
        tr2.setSelection(sel);
    } else {
      super.replace(tr2, content);
    }
  }
  toJSON() {
    return { type: "all" };
  }
  /**
  @internal
  */
  static fromJSON(doc3) {
    return new _AllSelection(doc3);
  }
  map(doc3) {
    return new _AllSelection(doc3);
  }
  eq(other) {
    return other instanceof _AllSelection;
  }
  getBookmark() {
    return AllBookmark;
  }
};
Selection.jsonID("all", AllSelection);
var AllBookmark = {
  map() {
    return this;
  },
  resolve(doc3) {
    return new AllSelection(doc3);
  }
};
function findSelectionIn(doc3, node, pos, index, dir, text5 = false) {
  if (node.inlineContent)
    return TextSelection.create(doc3, pos);
  for (let i = index - (dir > 0 ? 0 : 1); dir > 0 ? i < node.childCount : i >= 0; i += dir) {
    let child = node.child(i);
    if (!child.isAtom) {
      let inner2 = findSelectionIn(doc3, child, pos + dir, dir < 0 ? child.childCount : 0, dir, text5);
      if (inner2)
        return inner2;
    } else if (!text5 && NodeSelection.isSelectable(child)) {
      return NodeSelection.create(doc3, pos - (dir < 0 ? child.nodeSize : 0));
    }
    pos += child.nodeSize * dir;
  }
  return null;
}
function selectionToInsertionEnd(tr2, startLen, bias) {
  let last = tr2.steps.length - 1;
  if (last < startLen)
    return;
  let step = tr2.steps[last];
  if (!(step instanceof ReplaceStep || step instanceof ReplaceAroundStep))
    return;
  let map2 = tr2.mapping.maps[last], end;
  map2.forEach((_from, _to, _newFrom, newTo) => {
    if (end == null)
      end = newTo;
  });
  tr2.setSelection(Selection.near(tr2.doc.resolve(end), bias));
}
var UPDATED_SEL = 1;
var UPDATED_MARKS = 2;
var UPDATED_SCROLL = 4;
var Transaction = class extends Transform {
  /**
  @internal
  */
  constructor(state) {
    super(state.doc);
    this.curSelectionFor = 0;
    this.updated = 0;
    this.meta = /* @__PURE__ */ Object.create(null);
    this.time = Date.now();
    this.curSelection = state.selection;
    this.storedMarks = state.storedMarks;
  }
  /**
  The transaction's current selection. This defaults to the editor
  selection [mapped](https://prosemirror.net/docs/ref/#state.Selection.map) through the steps in the
  transaction, but can be overwritten with
  [`setSelection`](https://prosemirror.net/docs/ref/#state.Transaction.setSelection).
  */
  get selection() {
    if (this.curSelectionFor < this.steps.length) {
      this.curSelection = this.curSelection.map(this.doc, this.mapping.slice(this.curSelectionFor));
      this.curSelectionFor = this.steps.length;
    }
    return this.curSelection;
  }
  /**
  Update the transaction's current selection. Will determine the
  selection that the editor gets when the transaction is applied.
  */
  setSelection(selection) {
    if (selection.$from.doc != this.doc)
      throw new RangeError("Selection passed to setSelection must point at the current document");
    this.curSelection = selection;
    this.curSelectionFor = this.steps.length;
    this.updated = (this.updated | UPDATED_SEL) & ~UPDATED_MARKS;
    this.storedMarks = null;
    return this;
  }
  /**
  Whether the selection was explicitly updated by this transaction.
  */
  get selectionSet() {
    return (this.updated & UPDATED_SEL) > 0;
  }
  /**
  Set the current stored marks.
  */
  setStoredMarks(marks) {
    this.storedMarks = marks;
    this.updated |= UPDATED_MARKS;
    return this;
  }
  /**
  Make sure the current stored marks or, if that is null, the marks
  at the selection, match the given set of marks. Does nothing if
  this is already the case.
  */
  ensureMarks(marks) {
    if (!Mark.sameSet(this.storedMarks || this.selection.$from.marks(), marks))
      this.setStoredMarks(marks);
    return this;
  }
  /**
  Add a mark to the set of stored marks.
  */
  addStoredMark(mark) {
    return this.ensureMarks(mark.addToSet(this.storedMarks || this.selection.$head.marks()));
  }
  /**
  Remove a mark or mark type from the set of stored marks.
  */
  removeStoredMark(mark) {
    return this.ensureMarks(mark.removeFromSet(this.storedMarks || this.selection.$head.marks()));
  }
  /**
  Whether the stored marks were explicitly set for this transaction.
  */
  get storedMarksSet() {
    return (this.updated & UPDATED_MARKS) > 0;
  }
  /**
  @internal
  */
  addStep(step, doc3) {
    super.addStep(step, doc3);
    this.updated = this.updated & ~UPDATED_MARKS;
    this.storedMarks = null;
  }
  /**
  Update the timestamp for the transaction.
  */
  setTime(time) {
    this.time = time;
    return this;
  }
  /**
  Replace the current selection with the given slice.
  */
  replaceSelection(slice2) {
    this.selection.replace(this, slice2);
    return this;
  }
  /**
  Replace the selection with the given node. When `inheritMarks` is
  true and the content is inline, it inherits the marks from the
  place where it is inserted.
  */
  replaceSelectionWith(node, inheritMarks = true) {
    let selection = this.selection;
    if (inheritMarks)
      node = node.mark(this.storedMarks || (selection.empty ? selection.$from.marks() : selection.$from.marksAcross(selection.$to) || Mark.none));
    selection.replaceWith(this, node);
    return this;
  }
  /**
  Delete the selection.
  */
  deleteSelection() {
    this.selection.replace(this);
    return this;
  }
  /**
  Replace the given range, or the selection if no range is given,
  with a text node containing the given string.
  */
  insertText(text5, from2, to) {
    let schema = this.doc.type.schema;
    if (from2 == null) {
      if (!text5)
        return this.deleteSelection();
      return this.replaceSelectionWith(schema.text(text5), true);
    } else {
      if (to == null)
        to = from2;
      if (!text5)
        return this.deleteRange(from2, to);
      let marks = this.storedMarks;
      if (!marks) {
        let $from = this.doc.resolve(from2);
        marks = to == from2 ? $from.marks() : $from.marksAcross(this.doc.resolve(to));
      }
      this.replaceRangeWith(from2, to, schema.text(text5, marks));
      if (!this.selection.empty && this.selection.to == from2 + text5.length)
        this.setSelection(Selection.near(this.selection.$to));
      return this;
    }
  }
  /**
  Store a metadata property in this transaction, keyed either by
  name or by plugin.
  */
  setMeta(key, value) {
    this.meta[typeof key == "string" ? key : key.key] = value;
    return this;
  }
  /**
  Retrieve a metadata property for a given name or plugin.
  */
  getMeta(key) {
    return this.meta[typeof key == "string" ? key : key.key];
  }
  /**
  Returns true if this transaction doesn't contain any metadata,
  and can thus safely be extended.
  */
  get isGeneric() {
    for (let _10 in this.meta)
      return false;
    return true;
  }
  /**
  Indicate that the editor should scroll the selection into view
  when updated to the state produced by this transaction.
  */
  scrollIntoView() {
    this.updated |= UPDATED_SCROLL;
    return this;
  }
  /**
  True when this transaction has had `scrollIntoView` called on it.
  */
  get scrolledIntoView() {
    return (this.updated & UPDATED_SCROLL) > 0;
  }
};
function bind(f, self) {
  return !self || !f ? f : f.bind(self);
}
var FieldDesc = class {
  constructor(name, desc, self) {
    this.name = name;
    this.init = bind(desc.init, self);
    this.apply = bind(desc.apply, self);
  }
};
var baseFields = [
  new FieldDesc("doc", {
    init(config) {
      return config.doc || config.schema.topNodeType.createAndFill();
    },
    apply(tr2) {
      return tr2.doc;
    }
  }),
  new FieldDesc("selection", {
    init(config, instance) {
      return config.selection || Selection.atStart(instance.doc);
    },
    apply(tr2) {
      return tr2.selection;
    }
  }),
  new FieldDesc("storedMarks", {
    init(config) {
      return config.storedMarks || null;
    },
    apply(tr2, _marks, _old, state) {
      return state.selection.$cursor ? tr2.storedMarks : null;
    }
  }),
  new FieldDesc("scrollToSelection", {
    init() {
      return 0;
    },
    apply(tr2, prev) {
      return tr2.scrolledIntoView ? prev + 1 : prev;
    }
  })
];
var Configuration = class {
  constructor(schema, plugins) {
    this.schema = schema;
    this.plugins = [];
    this.pluginsByKey = /* @__PURE__ */ Object.create(null);
    this.fields = baseFields.slice();
    if (plugins)
      plugins.forEach((plugin) => {
        if (this.pluginsByKey[plugin.key])
          throw new RangeError("Adding different instances of a keyed plugin (" + plugin.key + ")");
        this.plugins.push(plugin);
        this.pluginsByKey[plugin.key] = plugin;
        if (plugin.spec.state)
          this.fields.push(new FieldDesc(plugin.key, plugin.spec.state, plugin));
      });
  }
};
var EditorState = class _EditorState {
  /**
  @internal
  */
  constructor(config) {
    this.config = config;
  }
  /**
  The schema of the state's document.
  */
  get schema() {
    return this.config.schema;
  }
  /**
  The plugins that are active in this state.
  */
  get plugins() {
    return this.config.plugins;
  }
  /**
  Apply the given transaction to produce a new state.
  */
  apply(tr2) {
    return this.applyTransaction(tr2).state;
  }
  /**
  @internal
  */
  filterTransaction(tr2, ignore = -1) {
    for (let i = 0; i < this.config.plugins.length; i++)
      if (i != ignore) {
        let plugin = this.config.plugins[i];
        if (plugin.spec.filterTransaction && !plugin.spec.filterTransaction.call(plugin, tr2, this))
          return false;
      }
    return true;
  }
  /**
  Verbose variant of [`apply`](https://prosemirror.net/docs/ref/#state.EditorState.apply) that
  returns the precise transactions that were applied (which might
  be influenced by the [transaction
  hooks](https://prosemirror.net/docs/ref/#state.PluginSpec.filterTransaction) of
  plugins) along with the new state.
  */
  applyTransaction(rootTr) {
    if (!this.filterTransaction(rootTr))
      return { state: this, transactions: [] };
    let trs = [rootTr], newState = this.applyInner(rootTr), seen = null;
    for (; ; ) {
      let haveNew = false;
      for (let i = 0; i < this.config.plugins.length; i++) {
        let plugin = this.config.plugins[i];
        if (plugin.spec.appendTransaction) {
          let n = seen ? seen[i].n : 0, oldState = seen ? seen[i].state : this;
          let tr2 = n < trs.length && plugin.spec.appendTransaction.call(plugin, n ? trs.slice(n) : trs, oldState, newState);
          if (tr2 && newState.filterTransaction(tr2, i)) {
            tr2.setMeta("appendedTransaction", rootTr);
            if (!seen) {
              seen = [];
              for (let j = 0; j < this.config.plugins.length; j++)
                seen.push(j < i ? { state: newState, n: trs.length } : { state: this, n: 0 });
            }
            trs.push(tr2);
            newState = newState.applyInner(tr2);
            haveNew = true;
          }
          if (seen)
            seen[i] = { state: newState, n: trs.length };
        }
      }
      if (!haveNew)
        return { state: newState, transactions: trs };
    }
  }
  /**
  @internal
  */
  applyInner(tr2) {
    if (!tr2.before.eq(this.doc))
      throw new RangeError("Applying a mismatched transaction");
    let newInstance = new _EditorState(this.config), fields = this.config.fields;
    for (let i = 0; i < fields.length; i++) {
      let field = fields[i];
      newInstance[field.name] = field.apply(tr2, this[field.name], this, newInstance);
    }
    return newInstance;
  }
  /**
  Accessor that constructs and returns a new [transaction](https://prosemirror.net/docs/ref/#state.Transaction) from this state.
  */
  get tr() {
    return new Transaction(this);
  }
  /**
  Create a new state.
  */
  static create(config) {
    let $config = new Configuration(config.doc ? config.doc.type.schema : config.schema, config.plugins);
    let instance = new _EditorState($config);
    for (let i = 0; i < $config.fields.length; i++)
      instance[$config.fields[i].name] = $config.fields[i].init(config, instance);
    return instance;
  }
  /**
  Create a new state based on this one, but with an adjusted set
  of active plugins. State fields that exist in both sets of
  plugins are kept unchanged. Those that no longer exist are
  dropped, and those that are new are initialized using their
  [`init`](https://prosemirror.net/docs/ref/#state.StateField.init) method, passing in the new
  configuration object..
  */
  reconfigure(config) {
    let $config = new Configuration(this.schema, config.plugins);
    let fields = $config.fields, instance = new _EditorState($config);
    for (let i = 0; i < fields.length; i++) {
      let name = fields[i].name;
      instance[name] = this.hasOwnProperty(name) ? this[name] : fields[i].init(config, instance);
    }
    return instance;
  }
  /**
  Serialize this state to JSON. If you want to serialize the state
  of plugins, pass an object mapping property names to use in the
  resulting JSON object to plugin objects. The argument may also be
  a string or number, in which case it is ignored, to support the
  way `JSON.stringify` calls `toString` methods.
  */
  toJSON(pluginFields) {
    let result = { doc: this.doc.toJSON(), selection: this.selection.toJSON() };
    if (this.storedMarks)
      result.storedMarks = this.storedMarks.map((m) => m.toJSON());
    if (pluginFields && typeof pluginFields == "object")
      for (let prop in pluginFields) {
        if (prop == "doc" || prop == "selection")
          throw new RangeError("The JSON fields `doc` and `selection` are reserved");
        let plugin = pluginFields[prop], state = plugin.spec.state;
        if (state && state.toJSON)
          result[prop] = state.toJSON.call(plugin, this[plugin.key]);
      }
    return result;
  }
  /**
  Deserialize a JSON representation of a state. `config` should
  have at least a `schema` field, and should contain array of
  plugins to initialize the state with. `pluginFields` can be used
  to deserialize the state of plugins, by associating plugin
  instances with the property names they use in the JSON object.
  */
  static fromJSON(config, json, pluginFields) {
    if (!json)
      throw new RangeError("Invalid input for EditorState.fromJSON");
    if (!config.schema)
      throw new RangeError("Required config field 'schema' missing");
    let $config = new Configuration(config.schema, config.plugins);
    let instance = new _EditorState($config);
    $config.fields.forEach((field) => {
      if (field.name == "doc") {
        instance.doc = Node2.fromJSON(config.schema, json.doc);
      } else if (field.name == "selection") {
        instance.selection = Selection.fromJSON(instance.doc, json.selection);
      } else if (field.name == "storedMarks") {
        if (json.storedMarks)
          instance.storedMarks = json.storedMarks.map(config.schema.markFromJSON);
      } else {
        if (pluginFields)
          for (let prop in pluginFields) {
            let plugin = pluginFields[prop], state = plugin.spec.state;
            if (plugin.key == field.name && state && state.fromJSON && Object.prototype.hasOwnProperty.call(json, prop)) {
              instance[field.name] = state.fromJSON.call(plugin, config, json[prop], instance);
              return;
            }
          }
        instance[field.name] = field.init(config, instance);
      }
    });
    return instance;
  }
};
function bindProps(obj, self, target2) {
  for (let prop in obj) {
    let val = obj[prop];
    if (val instanceof Function)
      val = val.bind(self);
    else if (prop == "handleDOMEvents")
      val = bindProps(val, self, {});
    target2[prop] = val;
  }
  return target2;
}
var Plugin = class {
  /**
  Create a plugin.
  */
  constructor(spec) {
    this.spec = spec;
    this.props = {};
    if (spec.props)
      bindProps(spec.props, this, this.props);
    this.key = spec.key ? spec.key.key : createKey("plugin");
  }
  /**
  Extract the plugin's state field from an editor state.
  */
  getState(state) {
    return state[this.key];
  }
};
var keys = /* @__PURE__ */ Object.create(null);
function createKey(name) {
  if (name in keys)
    return name + "$" + ++keys[name];
  keys[name] = 0;
  return name + "$";
}
var PluginKey = class {
  /**
  Create a plugin key.
  */
  constructor(name = "key") {
    this.key = createKey(name);
  }
  /**
  Get the active plugin with this key, if any, from an editor
  state.
  */
  get(state) {
    return state.config.pluginsByKey[this.key];
  }
  /**
  Get the plugin's state from an editor state.
  */
  getState(state) {
    return state[this.key];
  }
};

// ../../node_modules/.pnpm/prosemirror-commands@1.7.1/node_modules/prosemirror-commands/dist/index.js
var deleteSelection = (state, dispatch) => {
  if (state.selection.empty)
    return false;
  if (dispatch)
    dispatch(state.tr.deleteSelection().scrollIntoView());
  return true;
};
function atBlockStart(state, view) {
  let { $cursor } = state.selection;
  if (!$cursor || (view ? !view.endOfTextblock("backward", state) : $cursor.parentOffset > 0))
    return null;
  return $cursor;
}
var joinBackward = (state, dispatch, view) => {
  let $cursor = atBlockStart(state, view);
  if (!$cursor)
    return false;
  let $cut = findCutBefore($cursor);
  if (!$cut) {
    let range = $cursor.blockRange(), target2 = range && liftTarget(range);
    if (target2 == null)
      return false;
    if (dispatch)
      dispatch(state.tr.lift(range, target2).scrollIntoView());
    return true;
  }
  let before = $cut.nodeBefore;
  if (deleteBarrier(state, $cut, dispatch, -1))
    return true;
  if ($cursor.parent.content.size == 0 && (textblockAt(before, "end") || NodeSelection.isSelectable(before))) {
    for (let depth = $cursor.depth; ; depth--) {
      let delStep = replaceStep(state.doc, $cursor.before(depth), $cursor.after(depth), Slice.empty);
      if (delStep && delStep.slice.size < delStep.to - delStep.from) {
        if (dispatch) {
          let tr2 = state.tr.step(delStep);
          tr2.setSelection(textblockAt(before, "end") ? Selection.findFrom(tr2.doc.resolve(tr2.mapping.map($cut.pos, -1)), -1) : NodeSelection.create(tr2.doc, $cut.pos - before.nodeSize));
          dispatch(tr2.scrollIntoView());
        }
        return true;
      }
      if (depth == 1 || $cursor.node(depth - 1).childCount > 1)
        break;
    }
  }
  if (before.isAtom && $cut.depth == $cursor.depth - 1) {
    if (dispatch)
      dispatch(state.tr.delete($cut.pos - before.nodeSize, $cut.pos).scrollIntoView());
    return true;
  }
  return false;
};
var joinTextblockBackward = (state, dispatch, view) => {
  let $cursor = atBlockStart(state, view);
  if (!$cursor)
    return false;
  let $cut = findCutBefore($cursor);
  return $cut ? joinTextblocksAround(state, $cut, dispatch) : false;
};
var joinTextblockForward = (state, dispatch, view) => {
  let $cursor = atBlockEnd(state, view);
  if (!$cursor)
    return false;
  let $cut = findCutAfter($cursor);
  return $cut ? joinTextblocksAround(state, $cut, dispatch) : false;
};
function joinTextblocksAround(state, $cut, dispatch) {
  let before = $cut.nodeBefore, beforeText = before, beforePos = $cut.pos - 1;
  for (; !beforeText.isTextblock; beforePos--) {
    if (beforeText.type.spec.isolating)
      return false;
    let child = beforeText.lastChild;
    if (!child)
      return false;
    beforeText = child;
  }
  let after = $cut.nodeAfter, afterText = after, afterPos = $cut.pos + 1;
  for (; !afterText.isTextblock; afterPos++) {
    if (afterText.type.spec.isolating)
      return false;
    let child = afterText.firstChild;
    if (!child)
      return false;
    afterText = child;
  }
  let step = replaceStep(state.doc, beforePos, afterPos, Slice.empty);
  if (!step || step.from != beforePos || step instanceof ReplaceStep && step.slice.size >= afterPos - beforePos)
    return false;
  if (dispatch) {
    let tr2 = state.tr.step(step);
    tr2.setSelection(TextSelection.create(tr2.doc, beforePos));
    dispatch(tr2.scrollIntoView());
  }
  return true;
}
function textblockAt(node, side, only = false) {
  for (let scan = node; scan; scan = side == "start" ? scan.firstChild : scan.lastChild) {
    if (scan.isTextblock)
      return true;
    if (only && scan.childCount != 1)
      return false;
  }
  return false;
}
var selectNodeBackward = (state, dispatch, view) => {
  let { $head, empty: empty2 } = state.selection, $cut = $head;
  if (!empty2)
    return false;
  if ($head.parent.isTextblock) {
    if (view ? !view.endOfTextblock("backward", state) : $head.parentOffset > 0)
      return false;
    $cut = findCutBefore($head);
  }
  let node = $cut && $cut.nodeBefore;
  if (!node || !NodeSelection.isSelectable(node))
    return false;
  if (dispatch)
    dispatch(state.tr.setSelection(NodeSelection.create(state.doc, $cut.pos - node.nodeSize)).scrollIntoView());
  return true;
};
function findCutBefore($pos) {
  if (!$pos.parent.type.spec.isolating)
    for (let i = $pos.depth - 1; i >= 0; i--) {
      if ($pos.index(i) > 0)
        return $pos.doc.resolve($pos.before(i + 1));
      if ($pos.node(i).type.spec.isolating)
        break;
    }
  return null;
}
function atBlockEnd(state, view) {
  let { $cursor } = state.selection;
  if (!$cursor || (view ? !view.endOfTextblock("forward", state) : $cursor.parentOffset < $cursor.parent.content.size))
    return null;
  return $cursor;
}
var joinForward = (state, dispatch, view) => {
  let $cursor = atBlockEnd(state, view);
  if (!$cursor)
    return false;
  let $cut = findCutAfter($cursor);
  if (!$cut)
    return false;
  let after = $cut.nodeAfter;
  if (deleteBarrier(state, $cut, dispatch, 1))
    return true;
  if ($cursor.parent.content.size == 0 && (textblockAt(after, "start") || NodeSelection.isSelectable(after))) {
    let delStep = replaceStep(state.doc, $cursor.before(), $cursor.after(), Slice.empty);
    if (delStep && delStep.slice.size < delStep.to - delStep.from) {
      if (dispatch) {
        let tr2 = state.tr.step(delStep);
        tr2.setSelection(textblockAt(after, "start") ? Selection.findFrom(tr2.doc.resolve(tr2.mapping.map($cut.pos)), 1) : NodeSelection.create(tr2.doc, tr2.mapping.map($cut.pos)));
        dispatch(tr2.scrollIntoView());
      }
      return true;
    }
  }
  if (after.isAtom && $cut.depth == $cursor.depth - 1) {
    if (dispatch)
      dispatch(state.tr.delete($cut.pos, $cut.pos + after.nodeSize).scrollIntoView());
    return true;
  }
  return false;
};
var selectNodeForward = (state, dispatch, view) => {
  let { $head, empty: empty2 } = state.selection, $cut = $head;
  if (!empty2)
    return false;
  if ($head.parent.isTextblock) {
    if (view ? !view.endOfTextblock("forward", state) : $head.parentOffset < $head.parent.content.size)
      return false;
    $cut = findCutAfter($head);
  }
  let node = $cut && $cut.nodeAfter;
  if (!node || !NodeSelection.isSelectable(node))
    return false;
  if (dispatch)
    dispatch(state.tr.setSelection(NodeSelection.create(state.doc, $cut.pos)).scrollIntoView());
  return true;
};
function findCutAfter($pos) {
  if (!$pos.parent.type.spec.isolating)
    for (let i = $pos.depth - 1; i >= 0; i--) {
      let parent = $pos.node(i);
      if ($pos.index(i) + 1 < parent.childCount)
        return $pos.doc.resolve($pos.after(i + 1));
      if (parent.type.spec.isolating)
        break;
    }
  return null;
}
var joinUp = (state, dispatch) => {
  let sel = state.selection, nodeSel = sel instanceof NodeSelection, point;
  if (nodeSel) {
    if (sel.node.isTextblock || !canJoin(state.doc, sel.from))
      return false;
    point = sel.from;
  } else {
    point = joinPoint(state.doc, sel.from, -1);
    if (point == null)
      return false;
  }
  if (dispatch) {
    let tr2 = state.tr.join(point);
    if (nodeSel)
      tr2.setSelection(NodeSelection.create(tr2.doc, point - state.doc.resolve(point).nodeBefore.nodeSize));
    dispatch(tr2.scrollIntoView());
  }
  return true;
};
var joinDown = (state, dispatch) => {
  let sel = state.selection, point;
  if (sel instanceof NodeSelection) {
    if (sel.node.isTextblock || !canJoin(state.doc, sel.to))
      return false;
    point = sel.to;
  } else {
    point = joinPoint(state.doc, sel.to, 1);
    if (point == null)
      return false;
  }
  if (dispatch)
    dispatch(state.tr.join(point).scrollIntoView());
  return true;
};
var lift2 = (state, dispatch) => {
  let { $from, $to } = state.selection;
  let range = $from.blockRange($to), target2 = range && liftTarget(range);
  if (target2 == null)
    return false;
  if (dispatch)
    dispatch(state.tr.lift(range, target2).scrollIntoView());
  return true;
};
var newlineInCode = (state, dispatch) => {
  let { $head, $anchor } = state.selection;
  if (!$head.parent.type.spec.code || !$head.sameParent($anchor))
    return false;
  if (dispatch)
    dispatch(state.tr.insertText("\n").scrollIntoView());
  return true;
};
function defaultBlockAt(match) {
  for (let i = 0; i < match.edgeCount; i++) {
    let { type } = match.edge(i);
    if (type.isTextblock && !type.hasRequiredAttrs())
      return type;
  }
  return null;
}
var exitCode = (state, dispatch) => {
  let { $head, $anchor } = state.selection;
  if (!$head.parent.type.spec.code || !$head.sameParent($anchor))
    return false;
  let above = $head.node(-1), after = $head.indexAfter(-1), type = defaultBlockAt(above.contentMatchAt(after));
  if (!type || !above.canReplaceWith(after, after, type))
    return false;
  if (dispatch) {
    let pos = $head.after(), tr2 = state.tr.replaceWith(pos, pos, type.createAndFill());
    tr2.setSelection(Selection.near(tr2.doc.resolve(pos), 1));
    dispatch(tr2.scrollIntoView());
  }
  return true;
};
var createParagraphNear = (state, dispatch) => {
  let sel = state.selection, { $from, $to } = sel;
  if (sel instanceof AllSelection || $from.parent.inlineContent || $to.parent.inlineContent)
    return false;
  let type = defaultBlockAt($to.parent.contentMatchAt($to.indexAfter()));
  if (!type || !type.isTextblock)
    return false;
  if (dispatch) {
    let side = (!$from.parentOffset && $to.index() < $to.parent.childCount ? $from : $to).pos;
    let tr2 = state.tr.insert(side, type.createAndFill());
    tr2.setSelection(TextSelection.create(tr2.doc, side + 1));
    dispatch(tr2.scrollIntoView());
  }
  return true;
};
var liftEmptyBlock = (state, dispatch) => {
  let { $cursor } = state.selection;
  if (!$cursor || $cursor.parent.content.size)
    return false;
  if ($cursor.depth > 1 && $cursor.after() != $cursor.end(-1)) {
    let before = $cursor.before();
    if (canSplit(state.doc, before)) {
      if (dispatch)
        dispatch(state.tr.split(before).scrollIntoView());
      return true;
    }
  }
  let range = $cursor.blockRange(), target2 = range && liftTarget(range);
  if (target2 == null)
    return false;
  if (dispatch)
    dispatch(state.tr.lift(range, target2).scrollIntoView());
  return true;
};
function splitBlockAs(splitNode) {
  return (state, dispatch) => {
    let { $from, $to } = state.selection;
    if (state.selection instanceof NodeSelection && state.selection.node.isBlock) {
      if (!$from.parentOffset || !canSplit(state.doc, $from.pos))
        return false;
      if (dispatch)
        dispatch(state.tr.split($from.pos).scrollIntoView());
      return true;
    }
    if (!$from.depth)
      return false;
    let types = [];
    let splitDepth, deflt3, atEnd = false, atStart = false;
    for (let d2 = $from.depth; ; d2--) {
      let node = $from.node(d2);
      if (node.isBlock) {
        atEnd = $from.end(d2) == $from.pos + ($from.depth - d2);
        atStart = $from.start(d2) == $from.pos - ($from.depth - d2);
        deflt3 = defaultBlockAt($from.node(d2 - 1).contentMatchAt($from.indexAfter(d2 - 1)));
        let splitType = splitNode && splitNode($to.parent, atEnd, $from);
        types.unshift(splitType || (atEnd && deflt3 ? { type: deflt3 } : null));
        splitDepth = d2;
        break;
      } else {
        if (d2 == 1)
          return false;
        types.unshift(null);
      }
    }
    let tr2 = state.tr;
    if (state.selection instanceof TextSelection || state.selection instanceof AllSelection)
      tr2.deleteSelection();
    let splitPos = tr2.mapping.map($from.pos);
    let can = canSplit(tr2.doc, splitPos, types.length, types);
    if (!can) {
      types[0] = deflt3 ? { type: deflt3 } : null;
      can = canSplit(tr2.doc, splitPos, types.length, types);
    }
    if (!can)
      return false;
    tr2.split(splitPos, types.length, types);
    if (!atEnd && atStart && $from.node(splitDepth).type != deflt3) {
      let first2 = tr2.mapping.map($from.before(splitDepth)), $first = tr2.doc.resolve(first2);
      if (deflt3 && $from.node(splitDepth - 1).canReplaceWith($first.index(), $first.index() + 1, deflt3))
        tr2.setNodeMarkup(tr2.mapping.map($from.before(splitDepth)), deflt3);
    }
    if (dispatch)
      dispatch(tr2.scrollIntoView());
    return true;
  };
}
var splitBlock = splitBlockAs();
var selectParentNode = (state, dispatch) => {
  let { $from, to } = state.selection, pos;
  let same = $from.sharedDepth(to);
  if (same == 0)
    return false;
  pos = $from.before(same);
  if (dispatch)
    dispatch(state.tr.setSelection(NodeSelection.create(state.doc, pos)));
  return true;
};
var selectAll = (state, dispatch) => {
  if (dispatch)
    dispatch(state.tr.setSelection(new AllSelection(state.doc)));
  return true;
};
function joinMaybeClear(state, $pos, dispatch) {
  let before = $pos.nodeBefore, after = $pos.nodeAfter, index = $pos.index();
  if (!before || !after || !before.type.compatibleContent(after.type))
    return false;
  if (!before.content.size && $pos.parent.canReplace(index - 1, index)) {
    if (dispatch)
      dispatch(state.tr.delete($pos.pos - before.nodeSize, $pos.pos).scrollIntoView());
    return true;
  }
  if (!$pos.parent.canReplace(index, index + 1) || !(after.isTextblock || canJoin(state.doc, $pos.pos)))
    return false;
  if (dispatch)
    dispatch(state.tr.join($pos.pos).scrollIntoView());
  return true;
}
function deleteBarrier(state, $cut, dispatch, dir) {
  let before = $cut.nodeBefore, after = $cut.nodeAfter, conn, match;
  let isolated = before.type.spec.isolating || after.type.spec.isolating;
  if (!isolated && joinMaybeClear(state, $cut, dispatch))
    return true;
  let canDelAfter = !isolated && $cut.parent.canReplace($cut.index(), $cut.index() + 1);
  if (canDelAfter && (conn = (match = before.contentMatchAt(before.childCount)).findWrapping(after.type)) && match.matchType(conn[0] || after.type).validEnd) {
    if (dispatch) {
      let end = $cut.pos + after.nodeSize, wrap2 = Fragment.empty;
      for (let i = conn.length - 1; i >= 0; i--)
        wrap2 = Fragment.from(conn[i].create(null, wrap2));
      wrap2 = Fragment.from(before.copy(wrap2));
      let tr2 = state.tr.step(new ReplaceAroundStep($cut.pos - 1, end, $cut.pos, end, new Slice(wrap2, 1, 0), conn.length, true));
      let $joinAt = tr2.doc.resolve(end + 2 * conn.length);
      if ($joinAt.nodeAfter && $joinAt.nodeAfter.type == before.type && canJoin(tr2.doc, $joinAt.pos))
        tr2.join($joinAt.pos);
      dispatch(tr2.scrollIntoView());
    }
    return true;
  }
  let selAfter = after.type.spec.isolating || dir > 0 && isolated ? null : Selection.findFrom($cut, 1);
  let range = selAfter && selAfter.$from.blockRange(selAfter.$to), target2 = range && liftTarget(range);
  if (target2 != null && target2 >= $cut.depth) {
    if (dispatch)
      dispatch(state.tr.lift(range, target2).scrollIntoView());
    return true;
  }
  if (canDelAfter && textblockAt(after, "start", true) && textblockAt(before, "end")) {
    let at = before, wrap2 = [];
    for (; ; ) {
      wrap2.push(at);
      if (at.isTextblock)
        break;
      at = at.lastChild;
    }
    let afterText = after, afterDepth = 1;
    for (; !afterText.isTextblock; afterText = afterText.firstChild)
      afterDepth++;
    if (at.canReplace(at.childCount, at.childCount, afterText.content)) {
      if (dispatch) {
        let end = Fragment.empty;
        for (let i = wrap2.length - 1; i >= 0; i--)
          end = Fragment.from(wrap2[i].copy(end));
        let tr2 = state.tr.step(new ReplaceAroundStep($cut.pos - wrap2.length, $cut.pos + after.nodeSize, $cut.pos + afterDepth, $cut.pos + after.nodeSize - afterDepth, new Slice(end, wrap2.length, 0), 0, true));
        dispatch(tr2.scrollIntoView());
      }
      return true;
    }
  }
  return false;
}
function selectTextblockSide(side) {
  return function(state, dispatch) {
    let sel = state.selection, $pos = side < 0 ? sel.$from : sel.$to;
    let depth = $pos.depth;
    while ($pos.node(depth).isInline) {
      if (!depth)
        return false;
      depth--;
    }
    if (!$pos.node(depth).isTextblock)
      return false;
    if (dispatch)
      dispatch(state.tr.setSelection(TextSelection.create(state.doc, side < 0 ? $pos.start(depth) : $pos.end(depth))));
    return true;
  };
}
var selectTextblockStart = selectTextblockSide(-1);
var selectTextblockEnd = selectTextblockSide(1);
function wrapIn(nodeType, attrs = null) {
  return function(state, dispatch) {
    let { $from, $to } = state.selection;
    let range = $from.blockRange($to), wrapping = range && findWrapping(range, nodeType, attrs);
    if (!wrapping)
      return false;
    if (dispatch)
      dispatch(state.tr.wrap(range, wrapping).scrollIntoView());
    return true;
  };
}
function setBlockType2(nodeType, attrs = null) {
  return function(state, dispatch) {
    let applicable = false;
    for (let i = 0; i < state.selection.ranges.length && !applicable; i++) {
      let { $from: { pos: from2 }, $to: { pos: to } } = state.selection.ranges[i];
      state.doc.nodesBetween(from2, to, (node, pos) => {
        if (applicable)
          return false;
        if (!node.isTextblock || node.hasMarkup(nodeType, attrs))
          return;
        if (node.type == nodeType) {
          applicable = true;
        } else {
          let $pos = state.doc.resolve(pos), index = $pos.index();
          applicable = $pos.parent.canReplaceWith(index, index + 1, nodeType);
        }
      });
    }
    if (!applicable)
      return false;
    if (dispatch) {
      let tr2 = state.tr;
      for (let i = 0; i < state.selection.ranges.length; i++) {
        let { $from: { pos: from2 }, $to: { pos: to } } = state.selection.ranges[i];
        tr2.setBlockType(from2, to, nodeType, attrs);
      }
      dispatch(tr2.scrollIntoView());
    }
    return true;
  };
}
function chainCommands(...commands) {
  return function(state, dispatch, view) {
    for (let i = 0; i < commands.length; i++)
      if (commands[i](state, dispatch, view))
        return true;
    return false;
  };
}
var backspace = chainCommands(deleteSelection, joinBackward, selectNodeBackward);
var del = chainCommands(deleteSelection, joinForward, selectNodeForward);
var pcBaseKeymap = {
  "Enter": chainCommands(newlineInCode, createParagraphNear, liftEmptyBlock, splitBlock),
  "Mod-Enter": exitCode,
  "Backspace": backspace,
  "Mod-Backspace": backspace,
  "Shift-Backspace": backspace,
  "Delete": del,
  "Mod-Delete": del,
  "Mod-a": selectAll
};
var macBaseKeymap = {
  "Ctrl-h": pcBaseKeymap["Backspace"],
  "Alt-Backspace": pcBaseKeymap["Mod-Backspace"],
  "Ctrl-d": pcBaseKeymap["Delete"],
  "Ctrl-Alt-Backspace": pcBaseKeymap["Mod-Delete"],
  "Alt-Delete": pcBaseKeymap["Mod-Delete"],
  "Alt-d": pcBaseKeymap["Mod-Delete"],
  "Ctrl-a": selectTextblockStart,
  "Ctrl-e": selectTextblockEnd
};
for (let key in pcBaseKeymap)
  macBaseKeymap[key] = pcBaseKeymap[key];
var mac = typeof navigator != "undefined" ? /Mac|iP(hone|[oa]d)/.test(navigator.platform) : typeof os != "undefined" && os.platform ? os.platform() == "darwin" : false;

// ../../node_modules/.pnpm/prosemirror-schema-list@1.5.1/node_modules/prosemirror-schema-list/dist/index.js
function wrapInList(listType, attrs = null) {
  return function(state, dispatch) {
    let { $from, $to } = state.selection;
    let range = $from.blockRange($to);
    if (!range)
      return false;
    let tr2 = dispatch ? state.tr : null;
    if (!wrapRangeInList(tr2, range, listType, attrs))
      return false;
    if (dispatch)
      dispatch(tr2.scrollIntoView());
    return true;
  };
}
function wrapRangeInList(tr2, range, listType, attrs = null) {
  let doJoin = false, outerRange = range, doc3 = range.$from.doc;
  if (range.depth >= 2 && range.$from.node(range.depth - 1).type.compatibleContent(listType) && range.startIndex == 0) {
    if (range.$from.index(range.depth - 1) == 0)
      return false;
    let $insert = doc3.resolve(range.start - 2);
    outerRange = new NodeRange($insert, $insert, range.depth);
    if (range.endIndex < range.parent.childCount)
      range = new NodeRange(range.$from, doc3.resolve(range.$to.end(range.depth)), range.depth);
    doJoin = true;
  }
  let wrap2 = findWrapping(outerRange, listType, attrs, range);
  if (!wrap2)
    return false;
  if (tr2)
    doWrapInList(tr2, range, wrap2, doJoin, listType);
  return true;
}
function doWrapInList(tr2, range, wrappers, joinBefore, listType) {
  let content = Fragment.empty;
  for (let i = wrappers.length - 1; i >= 0; i--)
    content = Fragment.from(wrappers[i].type.create(wrappers[i].attrs, content));
  tr2.step(new ReplaceAroundStep(range.start - (joinBefore ? 2 : 0), range.end, range.start, range.end, new Slice(content, 0, 0), wrappers.length, true));
  let found2 = 0;
  for (let i = 0; i < wrappers.length; i++)
    if (wrappers[i].type == listType)
      found2 = i + 1;
  let splitDepth = wrappers.length - found2;
  let splitPos = range.start + wrappers.length - (joinBefore ? 2 : 0), parent = range.parent;
  for (let i = range.startIndex, e = range.endIndex, first2 = true; i < e; i++, first2 = false) {
    if (!first2 && canSplit(tr2.doc, splitPos, splitDepth)) {
      tr2.split(splitPos, splitDepth);
      splitPos += 2 * splitDepth;
    }
    splitPos += parent.child(i).nodeSize;
  }
  return tr2;
}
function liftListItem(itemType) {
  return function(state, dispatch) {
    let { $from, $to } = state.selection;
    let range = $from.blockRange($to, (node) => node.childCount > 0 && node.firstChild.type == itemType);
    if (!range)
      return false;
    if (!dispatch)
      return true;
    if ($from.node(range.depth - 1).type == itemType)
      return liftToOuterList(state, dispatch, itemType, range);
    else
      return liftOutOfList(state, dispatch, range);
  };
}
function liftToOuterList(state, dispatch, itemType, range) {
  let tr2 = state.tr, end = range.end, endOfList = range.$to.end(range.depth);
  if (end < endOfList) {
    tr2.step(new ReplaceAroundStep(end - 1, endOfList, end, endOfList, new Slice(Fragment.from(itemType.create(null, range.parent.copy())), 1, 0), 1, true));
    range = new NodeRange(tr2.doc.resolve(range.$from.pos), tr2.doc.resolve(endOfList), range.depth);
  }
  const target2 = liftTarget(range);
  if (target2 == null)
    return false;
  tr2.lift(range, target2);
  let $after = tr2.doc.resolve(tr2.mapping.map(end, -1) - 1);
  if (canJoin(tr2.doc, $after.pos) && $after.nodeBefore.type == $after.nodeAfter.type)
    tr2.join($after.pos);
  dispatch(tr2.scrollIntoView());
  return true;
}
function liftOutOfList(state, dispatch, range) {
  let tr2 = state.tr, list = range.parent;
  for (let pos = range.end, i = range.endIndex - 1, e = range.startIndex; i > e; i--) {
    pos -= list.child(i).nodeSize;
    tr2.delete(pos - 1, pos + 1);
  }
  let $start = tr2.doc.resolve(range.start), item = $start.nodeAfter;
  if (tr2.mapping.map(range.end) != range.start + $start.nodeAfter.nodeSize)
    return false;
  let atStart = range.startIndex == 0, atEnd = range.endIndex == list.childCount;
  let parent = $start.node(-1), indexBefore = $start.index(-1);
  if (!parent.canReplace(indexBefore + (atStart ? 0 : 1), indexBefore + 1, item.content.append(atEnd ? Fragment.empty : Fragment.from(list))))
    return false;
  let start = $start.pos, end = start + item.nodeSize;
  tr2.step(new ReplaceAroundStep(start - (atStart ? 1 : 0), end + (atEnd ? 1 : 0), start + 1, end - 1, new Slice((atStart ? Fragment.empty : Fragment.from(list.copy(Fragment.empty))).append(atEnd ? Fragment.empty : Fragment.from(list.copy(Fragment.empty))), atStart ? 0 : 1, atEnd ? 0 : 1), atStart ? 0 : 1));
  dispatch(tr2.scrollIntoView());
  return true;
}
function sinkListItem(itemType) {
  return function(state, dispatch) {
    let { $from, $to } = state.selection;
    let range = $from.blockRange($to, (node) => node.childCount > 0 && node.firstChild.type == itemType);
    if (!range)
      return false;
    let startIndex = range.startIndex;
    if (startIndex == 0)
      return false;
    let parent = range.parent, nodeBefore = parent.child(startIndex - 1);
    if (nodeBefore.type != itemType)
      return false;
    if (dispatch) {
      let nestedBefore = nodeBefore.lastChild && nodeBefore.lastChild.type == parent.type;
      let inner2 = Fragment.from(nestedBefore ? itemType.create() : null);
      let slice2 = new Slice(Fragment.from(itemType.create(null, Fragment.from(parent.type.create(null, inner2)))), nestedBefore ? 3 : 1, 0);
      let before = range.start, after = range.end;
      dispatch(state.tr.step(new ReplaceAroundStep(before - (nestedBefore ? 3 : 1), after, before, after, slice2, 1, true)).scrollIntoView());
    }
    return true;
  };
}

// ../../node_modules/.pnpm/prosemirror-view@1.41.5/node_modules/prosemirror-view/dist/index.js
var domIndex = function(node) {
  for (var index = 0; ; index++) {
    node = node.previousSibling;
    if (!node)
      return index;
  }
};
var parentNode = function(node) {
  let parent = node.assignedSlot || node.parentNode;
  return parent && parent.nodeType == 11 ? parent.host : parent;
};
var reusedRange = null;
var textRange = function(node, from2, to) {
  let range = reusedRange || (reusedRange = document.createRange());
  range.setEnd(node, to == null ? node.nodeValue.length : to);
  range.setStart(node, from2 || 0);
  return range;
};
var clearReusedRange = function() {
  reusedRange = null;
};
var isEquivalentPosition = function(node, off, targetNode, targetOff) {
  return targetNode && (scanFor(node, off, targetNode, targetOff, -1) || scanFor(node, off, targetNode, targetOff, 1));
};
var atomElements = /^(img|br|input|textarea|hr)$/i;
function scanFor(node, off, targetNode, targetOff, dir) {
  var _a;
  for (; ; ) {
    if (node == targetNode && off == targetOff)
      return true;
    if (off == (dir < 0 ? 0 : nodeSize(node))) {
      let parent = node.parentNode;
      if (!parent || parent.nodeType != 1 || hasBlockDesc(node) || atomElements.test(node.nodeName) || node.contentEditable == "false")
        return false;
      off = domIndex(node) + (dir < 0 ? 0 : 1);
      node = parent;
    } else if (node.nodeType == 1) {
      let child = node.childNodes[off + (dir < 0 ? -1 : 0)];
      if (child.nodeType == 1 && child.contentEditable == "false") {
        if ((_a = child.pmViewDesc) === null || _a === void 0 ? void 0 : _a.ignoreForSelection)
          off += dir;
        else
          return false;
      } else {
        node = child;
        off = dir < 0 ? nodeSize(node) : 0;
      }
    } else {
      return false;
    }
  }
}
function nodeSize(node) {
  return node.nodeType == 3 ? node.nodeValue.length : node.childNodes.length;
}
function textNodeBefore$1(node, offset) {
  for (; ; ) {
    if (node.nodeType == 3 && offset)
      return node;
    if (node.nodeType == 1 && offset > 0) {
      if (node.contentEditable == "false")
        return null;
      node = node.childNodes[offset - 1];
      offset = nodeSize(node);
    } else if (node.parentNode && !hasBlockDesc(node)) {
      offset = domIndex(node);
      node = node.parentNode;
    } else {
      return null;
    }
  }
}
function textNodeAfter$1(node, offset) {
  for (; ; ) {
    if (node.nodeType == 3 && offset < node.nodeValue.length)
      return node;
    if (node.nodeType == 1 && offset < node.childNodes.length) {
      if (node.contentEditable == "false")
        return null;
      node = node.childNodes[offset];
      offset = 0;
    } else if (node.parentNode && !hasBlockDesc(node)) {
      offset = domIndex(node) + 1;
      node = node.parentNode;
    } else {
      return null;
    }
  }
}
function isOnEdge(node, offset, parent) {
  for (let atStart = offset == 0, atEnd = offset == nodeSize(node); atStart || atEnd; ) {
    if (node == parent)
      return true;
    let index = domIndex(node);
    node = node.parentNode;
    if (!node)
      return false;
    atStart = atStart && index == 0;
    atEnd = atEnd && index == nodeSize(node);
  }
}
function hasBlockDesc(dom) {
  let desc;
  for (let cur = dom; cur; cur = cur.parentNode)
    if (desc = cur.pmViewDesc)
      break;
  return desc && desc.node && desc.node.isBlock && (desc.dom == dom || desc.contentDOM == dom);
}
var selectionCollapsed = function(domSel) {
  return domSel.focusNode && isEquivalentPosition(domSel.focusNode, domSel.focusOffset, domSel.anchorNode, domSel.anchorOffset);
};
function keyEvent(keyCode, key) {
  let event = document.createEvent("Event");
  event.initEvent("keydown", true, true);
  event.keyCode = keyCode;
  event.key = event.code = key;
  return event;
}
function deepActiveElement(doc3) {
  let elt = doc3.activeElement;
  while (elt && elt.shadowRoot)
    elt = elt.shadowRoot.activeElement;
  return elt;
}
function caretFromPoint(doc3, x5, y) {
  if (doc3.caretPositionFromPoint) {
    try {
      let pos = doc3.caretPositionFromPoint(x5, y);
      if (pos)
        return { node: pos.offsetNode, offset: Math.min(nodeSize(pos.offsetNode), pos.offset) };
    } catch (_10) {
    }
  }
  if (doc3.caretRangeFromPoint) {
    let range = doc3.caretRangeFromPoint(x5, y);
    if (range)
      return { node: range.startContainer, offset: Math.min(nodeSize(range.startContainer), range.startOffset) };
  }
}
var nav = typeof navigator != "undefined" ? navigator : null;
var doc2 = typeof document != "undefined" ? document : null;
var agent = nav && nav.userAgent || "";
var ie_edge = /Edge\/(\d+)/.exec(agent);
var ie_upto10 = /MSIE \d/.exec(agent);
var ie_11up = /Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(agent);
var ie = !!(ie_upto10 || ie_11up || ie_edge);
var ie_version = ie_upto10 ? document.documentMode : ie_11up ? +ie_11up[1] : ie_edge ? +ie_edge[1] : 0;
var gecko = !ie && /gecko\/(\d+)/i.test(agent);
gecko && +(/Firefox\/(\d+)/.exec(agent) || [0, 0])[1];
var _chrome = !ie && /Chrome\/(\d+)/.exec(agent);
var chrome = !!_chrome;
var chrome_version = _chrome ? +_chrome[1] : 0;
var safari = !ie && !!nav && /Apple Computer/.test(nav.vendor);
var ios = safari && (/Mobile\/\w+/.test(agent) || !!nav && nav.maxTouchPoints > 2);
var mac2 = ios || (nav ? /Mac/.test(nav.platform) : false);
var windows = nav ? /Win/.test(nav.platform) : false;
var android = /Android \d/.test(agent);
var webkit = !!doc2 && "webkitFontSmoothing" in doc2.documentElement.style;
var webkit_version = webkit ? +(/\bAppleWebKit\/(\d+)/.exec(navigator.userAgent) || [0, 0])[1] : 0;
function windowRect(doc3) {
  let vp = doc3.defaultView && doc3.defaultView.visualViewport;
  if (vp)
    return {
      left: 0,
      right: vp.width,
      top: 0,
      bottom: vp.height
    };
  return {
    left: 0,
    right: doc3.documentElement.clientWidth,
    top: 0,
    bottom: doc3.documentElement.clientHeight
  };
}
function getSide(value, side) {
  return typeof value == "number" ? value : value[side];
}
function clientRect(node) {
  let rect = node.getBoundingClientRect();
  let scaleX = rect.width / node.offsetWidth || 1;
  let scaleY = rect.height / node.offsetHeight || 1;
  return {
    left: rect.left,
    right: rect.left + node.clientWidth * scaleX,
    top: rect.top,
    bottom: rect.top + node.clientHeight * scaleY
  };
}
function scrollRectIntoView(view, rect, startDOM) {
  let scrollThreshold = view.someProp("scrollThreshold") || 0, scrollMargin = view.someProp("scrollMargin") || 5;
  let doc3 = view.dom.ownerDocument;
  for (let parent = startDOM || view.dom; ; ) {
    if (!parent)
      break;
    if (parent.nodeType != 1) {
      parent = parentNode(parent);
      continue;
    }
    let elt = parent;
    let atTop = elt == doc3.body;
    let bounding = atTop ? windowRect(doc3) : clientRect(elt);
    let moveX = 0, moveY = 0;
    if (rect.top < bounding.top + getSide(scrollThreshold, "top"))
      moveY = -(bounding.top - rect.top + getSide(scrollMargin, "top"));
    else if (rect.bottom > bounding.bottom - getSide(scrollThreshold, "bottom"))
      moveY = rect.bottom - rect.top > bounding.bottom - bounding.top ? rect.top + getSide(scrollMargin, "top") - bounding.top : rect.bottom - bounding.bottom + getSide(scrollMargin, "bottom");
    if (rect.left < bounding.left + getSide(scrollThreshold, "left"))
      moveX = -(bounding.left - rect.left + getSide(scrollMargin, "left"));
    else if (rect.right > bounding.right - getSide(scrollThreshold, "right"))
      moveX = rect.right - bounding.right + getSide(scrollMargin, "right");
    if (moveX || moveY) {
      if (atTop) {
        doc3.defaultView.scrollBy(moveX, moveY);
      } else {
        let startX = elt.scrollLeft, startY = elt.scrollTop;
        if (moveY)
          elt.scrollTop += moveY;
        if (moveX)
          elt.scrollLeft += moveX;
        let dX = elt.scrollLeft - startX, dY = elt.scrollTop - startY;
        rect = { left: rect.left - dX, top: rect.top - dY, right: rect.right - dX, bottom: rect.bottom - dY };
      }
    }
    let pos = atTop ? "fixed" : getComputedStyle(parent).position;
    if (/^(fixed|sticky)$/.test(pos))
      break;
    parent = pos == "absolute" ? parent.offsetParent : parentNode(parent);
  }
}
function storeScrollPos(view) {
  let rect = view.dom.getBoundingClientRect(), startY = Math.max(0, rect.top);
  let refDOM, refTop;
  for (let x5 = (rect.left + rect.right) / 2, y = startY + 1; y < Math.min(innerHeight, rect.bottom); y += 5) {
    let dom = view.root.elementFromPoint(x5, y);
    if (!dom || dom == view.dom || !view.dom.contains(dom))
      continue;
    let localRect = dom.getBoundingClientRect();
    if (localRect.top >= startY - 20) {
      refDOM = dom;
      refTop = localRect.top;
      break;
    }
  }
  return { refDOM, refTop, stack: scrollStack(view.dom) };
}
function scrollStack(dom) {
  let stack = [], doc3 = dom.ownerDocument;
  for (let cur = dom; cur; cur = parentNode(cur)) {
    stack.push({ dom: cur, top: cur.scrollTop, left: cur.scrollLeft });
    if (dom == doc3)
      break;
  }
  return stack;
}
function resetScrollPos({ refDOM, refTop, stack }) {
  let newRefTop = refDOM ? refDOM.getBoundingClientRect().top : 0;
  restoreScrollStack(stack, newRefTop == 0 ? 0 : newRefTop - refTop);
}
function restoreScrollStack(stack, dTop) {
  for (let i = 0; i < stack.length; i++) {
    let { dom, top, left } = stack[i];
    if (dom.scrollTop != top + dTop)
      dom.scrollTop = top + dTop;
    if (dom.scrollLeft != left)
      dom.scrollLeft = left;
  }
}
var preventScrollSupported = null;
function focusPreventScroll(dom) {
  if (dom.setActive)
    return dom.setActive();
  if (preventScrollSupported)
    return dom.focus(preventScrollSupported);
  let stored = scrollStack(dom);
  dom.focus(preventScrollSupported == null ? {
    get preventScroll() {
      preventScrollSupported = { preventScroll: true };
      return true;
    }
  } : void 0);
  if (!preventScrollSupported) {
    preventScrollSupported = false;
    restoreScrollStack(stored, 0);
  }
}
function findOffsetInNode(node, coords) {
  let closest, dxClosest = 2e8, coordsClosest, offset = 0;
  let rowBot = coords.top, rowTop = coords.top;
  let firstBelow, coordsBelow;
  for (let child = node.firstChild, childIndex = 0; child; child = child.nextSibling, childIndex++) {
    let rects;
    if (child.nodeType == 1)
      rects = child.getClientRects();
    else if (child.nodeType == 3)
      rects = textRange(child).getClientRects();
    else
      continue;
    for (let i = 0; i < rects.length; i++) {
      let rect = rects[i];
      if (rect.top <= rowBot && rect.bottom >= rowTop) {
        rowBot = Math.max(rect.bottom, rowBot);
        rowTop = Math.min(rect.top, rowTop);
        let dx = rect.left > coords.left ? rect.left - coords.left : rect.right < coords.left ? coords.left - rect.right : 0;
        if (dx < dxClosest) {
          closest = child;
          dxClosest = dx;
          coordsClosest = dx && closest.nodeType == 3 ? {
            left: rect.right < coords.left ? rect.right : rect.left,
            top: coords.top
          } : coords;
          if (child.nodeType == 1 && dx)
            offset = childIndex + (coords.left >= (rect.left + rect.right) / 2 ? 1 : 0);
          continue;
        }
      } else if (rect.top > coords.top && !firstBelow && rect.left <= coords.left && rect.right >= coords.left) {
        firstBelow = child;
        coordsBelow = { left: Math.max(rect.left, Math.min(rect.right, coords.left)), top: rect.top };
      }
      if (!closest && (coords.left >= rect.right && coords.top >= rect.top || coords.left >= rect.left && coords.top >= rect.bottom))
        offset = childIndex + 1;
    }
  }
  if (!closest && firstBelow) {
    closest = firstBelow;
    coordsClosest = coordsBelow;
    dxClosest = 0;
  }
  if (closest && closest.nodeType == 3)
    return findOffsetInText(closest, coordsClosest);
  if (!closest || dxClosest && closest.nodeType == 1)
    return { node, offset };
  return findOffsetInNode(closest, coordsClosest);
}
function findOffsetInText(node, coords) {
  let len = node.nodeValue.length;
  let range = document.createRange(), result;
  for (let i = 0; i < len; i++) {
    range.setEnd(node, i + 1);
    range.setStart(node, i);
    let rect = singleRect(range, 1);
    if (rect.top == rect.bottom)
      continue;
    if (inRect(coords, rect)) {
      result = { node, offset: i + (coords.left >= (rect.left + rect.right) / 2 ? 1 : 0) };
      break;
    }
  }
  range.detach();
  return result || { node, offset: 0 };
}
function inRect(coords, rect) {
  return coords.left >= rect.left - 1 && coords.left <= rect.right + 1 && coords.top >= rect.top - 1 && coords.top <= rect.bottom + 1;
}
function targetKludge(dom, coords) {
  let parent = dom.parentNode;
  if (parent && /^li$/i.test(parent.nodeName) && coords.left < dom.getBoundingClientRect().left)
    return parent;
  return dom;
}
function posFromElement(view, elt, coords) {
  let { node, offset } = findOffsetInNode(elt, coords), bias = -1;
  if (node.nodeType == 1 && !node.firstChild) {
    let rect = node.getBoundingClientRect();
    bias = rect.left != rect.right && coords.left > (rect.left + rect.right) / 2 ? 1 : -1;
  }
  return view.docView.posFromDOM(node, offset, bias);
}
function posFromCaret(view, node, offset, coords) {
  let outsideBlock = -1;
  for (let cur = node, sawBlock = false; ; ) {
    if (cur == view.dom)
      break;
    let desc = view.docView.nearestDesc(cur, true), rect;
    if (!desc)
      return null;
    if (desc.dom.nodeType == 1 && (desc.node.isBlock && desc.parent || !desc.contentDOM) && // Ignore elements with zero-size bounding rectangles
    ((rect = desc.dom.getBoundingClientRect()).width || rect.height)) {
      if (desc.node.isBlock && desc.parent && !/^T(R|BODY|HEAD|FOOT)$/.test(desc.dom.nodeName)) {
        if (!sawBlock && rect.left > coords.left || rect.top > coords.top)
          outsideBlock = desc.posBefore;
        else if (!sawBlock && rect.right < coords.left || rect.bottom < coords.top)
          outsideBlock = desc.posAfter;
        sawBlock = true;
      }
      if (!desc.contentDOM && outsideBlock < 0 && !desc.node.isText) {
        let before = desc.node.isBlock ? coords.top < (rect.top + rect.bottom) / 2 : coords.left < (rect.left + rect.right) / 2;
        return before ? desc.posBefore : desc.posAfter;
      }
    }
    cur = desc.dom.parentNode;
  }
  return outsideBlock > -1 ? outsideBlock : view.docView.posFromDOM(node, offset, -1);
}
function elementFromPoint(element, coords, box) {
  let len = element.childNodes.length;
  if (len && box.top < box.bottom) {
    for (let startI = Math.max(0, Math.min(len - 1, Math.floor(len * (coords.top - box.top) / (box.bottom - box.top)) - 2)), i = startI; ; ) {
      let child = element.childNodes[i];
      if (child.nodeType == 1) {
        let rects = child.getClientRects();
        for (let j = 0; j < rects.length; j++) {
          let rect = rects[j];
          if (inRect(coords, rect))
            return elementFromPoint(child, coords, rect);
        }
      }
      if ((i = (i + 1) % len) == startI)
        break;
    }
  }
  return element;
}
function posAtCoords(view, coords) {
  let doc3 = view.dom.ownerDocument, node, offset = 0;
  let caret = caretFromPoint(doc3, coords.left, coords.top);
  if (caret)
    ({ node, offset } = caret);
  let elt = (view.root.elementFromPoint ? view.root : doc3).elementFromPoint(coords.left, coords.top);
  let pos;
  if (!elt || !view.dom.contains(elt.nodeType != 1 ? elt.parentNode : elt)) {
    let box = view.dom.getBoundingClientRect();
    if (!inRect(coords, box))
      return null;
    elt = elementFromPoint(view.dom, coords, box);
    if (!elt)
      return null;
  }
  if (safari) {
    for (let p2 = elt; node && p2; p2 = parentNode(p2))
      if (p2.draggable)
        node = void 0;
  }
  elt = targetKludge(elt, coords);
  if (node) {
    if (gecko && node.nodeType == 1) {
      offset = Math.min(offset, node.childNodes.length);
      if (offset < node.childNodes.length) {
        let next = node.childNodes[offset], box;
        if (next.nodeName == "IMG" && (box = next.getBoundingClientRect()).right <= coords.left && box.bottom > coords.top)
          offset++;
      }
    }
    let prev;
    if (webkit && offset && node.nodeType == 1 && (prev = node.childNodes[offset - 1]).nodeType == 1 && prev.contentEditable == "false" && prev.getBoundingClientRect().top >= coords.top)
      offset--;
    if (node == view.dom && offset == node.childNodes.length - 1 && node.lastChild.nodeType == 1 && coords.top > node.lastChild.getBoundingClientRect().bottom)
      pos = view.state.doc.content.size;
    else if (offset == 0 || node.nodeType != 1 || node.childNodes[offset - 1].nodeName != "BR")
      pos = posFromCaret(view, node, offset, coords);
  }
  if (pos == null)
    pos = posFromElement(view, elt, coords);
  let desc = view.docView.nearestDesc(elt, true);
  return { pos, inside: desc ? desc.posAtStart - desc.border : -1 };
}
function nonZero(rect) {
  return rect.top < rect.bottom || rect.left < rect.right;
}
function singleRect(target2, bias) {
  let rects = target2.getClientRects();
  if (rects.length) {
    let first2 = rects[bias < 0 ? 0 : rects.length - 1];
    if (nonZero(first2))
      return first2;
  }
  return Array.prototype.find.call(rects, nonZero) || target2.getBoundingClientRect();
}
var BIDI = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/;
function coordsAtPos(view, pos, side) {
  let { node, offset, atom } = view.docView.domFromPos(pos, side < 0 ? -1 : 1);
  let supportEmptyRange = webkit || gecko;
  if (node.nodeType == 3) {
    if (supportEmptyRange && (BIDI.test(node.nodeValue) || (side < 0 ? !offset : offset == node.nodeValue.length))) {
      let rect = singleRect(textRange(node, offset, offset), side);
      if (gecko && offset && /\s/.test(node.nodeValue[offset - 1]) && offset < node.nodeValue.length) {
        let rectBefore = singleRect(textRange(node, offset - 1, offset - 1), -1);
        if (rectBefore.top == rect.top) {
          let rectAfter = singleRect(textRange(node, offset, offset + 1), -1);
          if (rectAfter.top != rect.top)
            return flattenV(rectAfter, rectAfter.left < rectBefore.left);
        }
      }
      return rect;
    } else {
      let from2 = offset, to = offset, takeSide = side < 0 ? 1 : -1;
      if (side < 0 && !offset) {
        to++;
        takeSide = -1;
      } else if (side >= 0 && offset == node.nodeValue.length) {
        from2--;
        takeSide = 1;
      } else if (side < 0) {
        from2--;
      } else {
        to++;
      }
      return flattenV(singleRect(textRange(node, from2, to), takeSide), takeSide < 0);
    }
  }
  let $dom = view.state.doc.resolve(pos - (atom || 0));
  if (!$dom.parent.inlineContent) {
    if (atom == null && offset && (side < 0 || offset == nodeSize(node))) {
      let before = node.childNodes[offset - 1];
      if (before.nodeType == 1)
        return flattenH(before.getBoundingClientRect(), false);
    }
    if (atom == null && offset < nodeSize(node)) {
      let after = node.childNodes[offset];
      if (after.nodeType == 1)
        return flattenH(after.getBoundingClientRect(), true);
    }
    return flattenH(node.getBoundingClientRect(), side >= 0);
  }
  if (atom == null && offset && (side < 0 || offset == nodeSize(node))) {
    let before = node.childNodes[offset - 1];
    let target2 = before.nodeType == 3 ? textRange(before, nodeSize(before) - (supportEmptyRange ? 0 : 1)) : before.nodeType == 1 && (before.nodeName != "BR" || !before.nextSibling) ? before : null;
    if (target2)
      return flattenV(singleRect(target2, 1), false);
  }
  if (atom == null && offset < nodeSize(node)) {
    let after = node.childNodes[offset];
    while (after.pmViewDesc && after.pmViewDesc.ignoreForCoords)
      after = after.nextSibling;
    let target2 = !after ? null : after.nodeType == 3 ? textRange(after, 0, supportEmptyRange ? 0 : 1) : after.nodeType == 1 ? after : null;
    if (target2)
      return flattenV(singleRect(target2, -1), true);
  }
  return flattenV(singleRect(node.nodeType == 3 ? textRange(node) : node, -side), side >= 0);
}
function flattenV(rect, left) {
  if (rect.width == 0)
    return rect;
  let x5 = left ? rect.left : rect.right;
  return { top: rect.top, bottom: rect.bottom, left: x5, right: x5 };
}
function flattenH(rect, top) {
  if (rect.height == 0)
    return rect;
  let y = top ? rect.top : rect.bottom;
  return { top: y, bottom: y, left: rect.left, right: rect.right };
}
function withFlushedState(view, state, f) {
  let viewState = view.state, active = view.root.activeElement;
  if (viewState != state)
    view.updateState(state);
  if (active != view.dom)
    view.focus();
  try {
    return f();
  } finally {
    if (viewState != state)
      view.updateState(viewState);
    if (active != view.dom && active)
      active.focus();
  }
}
function endOfTextblockVertical(view, state, dir) {
  let sel = state.selection;
  let $pos = dir == "up" ? sel.$from : sel.$to;
  return withFlushedState(view, state, () => {
    let { node: dom } = view.docView.domFromPos($pos.pos, dir == "up" ? -1 : 1);
    for (; ; ) {
      let nearest = view.docView.nearestDesc(dom, true);
      if (!nearest)
        break;
      if (nearest.node.isBlock) {
        dom = nearest.contentDOM || nearest.dom;
        break;
      }
      dom = nearest.dom.parentNode;
    }
    let coords = coordsAtPos(view, $pos.pos, 1);
    for (let child = dom.firstChild; child; child = child.nextSibling) {
      let boxes;
      if (child.nodeType == 1)
        boxes = child.getClientRects();
      else if (child.nodeType == 3)
        boxes = textRange(child, 0, child.nodeValue.length).getClientRects();
      else
        continue;
      for (let i = 0; i < boxes.length; i++) {
        let box = boxes[i];
        if (box.bottom > box.top + 1 && (dir == "up" ? coords.top - box.top > (box.bottom - coords.top) * 2 : box.bottom - coords.bottom > (coords.bottom - box.top) * 2))
          return false;
      }
    }
    return true;
  });
}
var maybeRTL = /[\u0590-\u08ac]/;
function endOfTextblockHorizontal(view, state, dir) {
  let { $head } = state.selection;
  if (!$head.parent.isTextblock)
    return false;
  let offset = $head.parentOffset, atStart = !offset, atEnd = offset == $head.parent.content.size;
  let sel = view.domSelection();
  if (!sel)
    return $head.pos == $head.start() || $head.pos == $head.end();
  if (!maybeRTL.test($head.parent.textContent) || !sel.modify)
    return dir == "left" || dir == "backward" ? atStart : atEnd;
  return withFlushedState(view, state, () => {
    let { focusNode: oldNode, focusOffset: oldOff, anchorNode, anchorOffset } = view.domSelectionRange();
    let oldBidiLevel = sel.caretBidiLevel;
    sel.modify("move", dir, "character");
    let parentDOM = $head.depth ? view.docView.domAfterPos($head.before()) : view.dom;
    let { focusNode: newNode, focusOffset: newOff } = view.domSelectionRange();
    let result = newNode && !parentDOM.contains(newNode.nodeType == 1 ? newNode : newNode.parentNode) || oldNode == newNode && oldOff == newOff;
    try {
      sel.collapse(anchorNode, anchorOffset);
      if (oldNode && (oldNode != anchorNode || oldOff != anchorOffset) && sel.extend)
        sel.extend(oldNode, oldOff);
    } catch (_10) {
    }
    if (oldBidiLevel != null)
      sel.caretBidiLevel = oldBidiLevel;
    return result;
  });
}
var cachedState = null;
var cachedDir = null;
var cachedResult = false;
function endOfTextblock(view, state, dir) {
  if (cachedState == state && cachedDir == dir)
    return cachedResult;
  cachedState = state;
  cachedDir = dir;
  return cachedResult = dir == "up" || dir == "down" ? endOfTextblockVertical(view, state, dir) : endOfTextblockHorizontal(view, state, dir);
}
var NOT_DIRTY = 0;
var CHILD_DIRTY = 1;
var CONTENT_DIRTY = 2;
var NODE_DIRTY = 3;
var ViewDesc = class {
  constructor(parent, children, dom, contentDOM) {
    this.parent = parent;
    this.children = children;
    this.dom = dom;
    this.contentDOM = contentDOM;
    this.dirty = NOT_DIRTY;
    dom.pmViewDesc = this;
  }
  // Used to check whether a given description corresponds to a
  // widget/mark/node.
  matchesWidget(widget) {
    return false;
  }
  matchesMark(mark) {
    return false;
  }
  matchesNode(node, outerDeco, innerDeco) {
    return false;
  }
  matchesHack(nodeName) {
    return false;
  }
  // When parsing in-editor content (in domchange.js), we allow
  // descriptions to determine the parse rules that should be used to
  // parse them.
  parseRule() {
    return null;
  }
  // Used by the editor's event handler to ignore events that come
  // from certain descs.
  stopEvent(event) {
    return false;
  }
  // The size of the content represented by this desc.
  get size() {
    let size = 0;
    for (let i = 0; i < this.children.length; i++)
      size += this.children[i].size;
    return size;
  }
  // For block nodes, this represents the space taken up by their
  // start/end tokens.
  get border() {
    return 0;
  }
  destroy() {
    this.parent = void 0;
    if (this.dom.pmViewDesc == this)
      this.dom.pmViewDesc = void 0;
    for (let i = 0; i < this.children.length; i++)
      this.children[i].destroy();
  }
  posBeforeChild(child) {
    for (let i = 0, pos = this.posAtStart; ; i++) {
      let cur = this.children[i];
      if (cur == child)
        return pos;
      pos += cur.size;
    }
  }
  get posBefore() {
    return this.parent.posBeforeChild(this);
  }
  get posAtStart() {
    return this.parent ? this.parent.posBeforeChild(this) + this.border : 0;
  }
  get posAfter() {
    return this.posBefore + this.size;
  }
  get posAtEnd() {
    return this.posAtStart + this.size - 2 * this.border;
  }
  localPosFromDOM(dom, offset, bias) {
    if (this.contentDOM && this.contentDOM.contains(dom.nodeType == 1 ? dom : dom.parentNode)) {
      if (bias < 0) {
        let domBefore, desc;
        if (dom == this.contentDOM) {
          domBefore = dom.childNodes[offset - 1];
        } else {
          while (dom.parentNode != this.contentDOM)
            dom = dom.parentNode;
          domBefore = dom.previousSibling;
        }
        while (domBefore && !((desc = domBefore.pmViewDesc) && desc.parent == this))
          domBefore = domBefore.previousSibling;
        return domBefore ? this.posBeforeChild(desc) + desc.size : this.posAtStart;
      } else {
        let domAfter, desc;
        if (dom == this.contentDOM) {
          domAfter = dom.childNodes[offset];
        } else {
          while (dom.parentNode != this.contentDOM)
            dom = dom.parentNode;
          domAfter = dom.nextSibling;
        }
        while (domAfter && !((desc = domAfter.pmViewDesc) && desc.parent == this))
          domAfter = domAfter.nextSibling;
        return domAfter ? this.posBeforeChild(desc) : this.posAtEnd;
      }
    }
    let atEnd;
    if (dom == this.dom && this.contentDOM) {
      atEnd = offset > domIndex(this.contentDOM);
    } else if (this.contentDOM && this.contentDOM != this.dom && this.dom.contains(this.contentDOM)) {
      atEnd = dom.compareDocumentPosition(this.contentDOM) & 2;
    } else if (this.dom.firstChild) {
      if (offset == 0)
        for (let search = dom; ; search = search.parentNode) {
          if (search == this.dom) {
            atEnd = false;
            break;
          }
          if (search.previousSibling)
            break;
        }
      if (atEnd == null && offset == dom.childNodes.length)
        for (let search = dom; ; search = search.parentNode) {
          if (search == this.dom) {
            atEnd = true;
            break;
          }
          if (search.nextSibling)
            break;
        }
    }
    return (atEnd == null ? bias > 0 : atEnd) ? this.posAtEnd : this.posAtStart;
  }
  nearestDesc(dom, onlyNodes = false) {
    for (let first2 = true, cur = dom; cur; cur = cur.parentNode) {
      let desc = this.getDesc(cur), nodeDOM;
      if (desc && (!onlyNodes || desc.node)) {
        if (first2 && (nodeDOM = desc.nodeDOM) && !(nodeDOM.nodeType == 1 ? nodeDOM.contains(dom.nodeType == 1 ? dom : dom.parentNode) : nodeDOM == dom))
          first2 = false;
        else
          return desc;
      }
    }
  }
  getDesc(dom) {
    let desc = dom.pmViewDesc;
    for (let cur = desc; cur; cur = cur.parent)
      if (cur == this)
        return desc;
  }
  posFromDOM(dom, offset, bias) {
    for (let scan = dom; scan; scan = scan.parentNode) {
      let desc = this.getDesc(scan);
      if (desc)
        return desc.localPosFromDOM(dom, offset, bias);
    }
    return -1;
  }
  // Find the desc for the node after the given pos, if any. (When a
  // parent node overrode rendering, there might not be one.)
  descAt(pos) {
    for (let i = 0, offset = 0; i < this.children.length; i++) {
      let child = this.children[i], end = offset + child.size;
      if (offset == pos && end != offset) {
        while (!child.border && child.children.length) {
          for (let i2 = 0; i2 < child.children.length; i2++) {
            let inner2 = child.children[i2];
            if (inner2.size) {
              child = inner2;
              break;
            }
          }
        }
        return child;
      }
      if (pos < end)
        return child.descAt(pos - offset - child.border);
      offset = end;
    }
  }
  domFromPos(pos, side) {
    if (!this.contentDOM)
      return { node: this.dom, offset: 0, atom: pos + 1 };
    let i = 0, offset = 0;
    for (let curPos = 0; i < this.children.length; i++) {
      let child = this.children[i], end = curPos + child.size;
      if (end > pos || child instanceof TrailingHackViewDesc) {
        offset = pos - curPos;
        break;
      }
      curPos = end;
    }
    if (offset)
      return this.children[i].domFromPos(offset - this.children[i].border, side);
    for (let prev; i && !(prev = this.children[i - 1]).size && prev instanceof WidgetViewDesc && prev.side >= 0; i--) {
    }
    if (side <= 0) {
      let prev, enter2 = true;
      for (; ; i--, enter2 = false) {
        prev = i ? this.children[i - 1] : null;
        if (!prev || prev.dom.parentNode == this.contentDOM)
          break;
      }
      if (prev && side && enter2 && !prev.border && !prev.domAtom)
        return prev.domFromPos(prev.size, side);
      return { node: this.contentDOM, offset: prev ? domIndex(prev.dom) + 1 : 0 };
    } else {
      let next, enter2 = true;
      for (; ; i++, enter2 = false) {
        next = i < this.children.length ? this.children[i] : null;
        if (!next || next.dom.parentNode == this.contentDOM)
          break;
      }
      if (next && enter2 && !next.border && !next.domAtom)
        return next.domFromPos(0, side);
      return { node: this.contentDOM, offset: next ? domIndex(next.dom) : this.contentDOM.childNodes.length };
    }
  }
  // Used to find a DOM range in a single parent for a given changed
  // range.
  parseRange(from2, to, base2 = 0) {
    if (this.children.length == 0)
      return { node: this.contentDOM, from: from2, to, fromOffset: 0, toOffset: this.contentDOM.childNodes.length };
    let fromOffset = -1, toOffset = -1;
    for (let offset = base2, i = 0; ; i++) {
      let child = this.children[i], end = offset + child.size;
      if (fromOffset == -1 && from2 <= end) {
        let childBase = offset + child.border;
        if (from2 >= childBase && to <= end - child.border && child.node && child.contentDOM && this.contentDOM.contains(child.contentDOM))
          return child.parseRange(from2, to, childBase);
        from2 = offset;
        for (let j = i; j > 0; j--) {
          let prev = this.children[j - 1];
          if (prev.size && prev.dom.parentNode == this.contentDOM && !prev.emptyChildAt(1)) {
            fromOffset = domIndex(prev.dom) + 1;
            break;
          }
          from2 -= prev.size;
        }
        if (fromOffset == -1)
          fromOffset = 0;
      }
      if (fromOffset > -1 && (end > to || i == this.children.length - 1)) {
        to = end;
        for (let j = i + 1; j < this.children.length; j++) {
          let next = this.children[j];
          if (next.size && next.dom.parentNode == this.contentDOM && !next.emptyChildAt(-1)) {
            toOffset = domIndex(next.dom);
            break;
          }
          to += next.size;
        }
        if (toOffset == -1)
          toOffset = this.contentDOM.childNodes.length;
        break;
      }
      offset = end;
    }
    return { node: this.contentDOM, from: from2, to, fromOffset, toOffset };
  }
  emptyChildAt(side) {
    if (this.border || !this.contentDOM || !this.children.length)
      return false;
    let child = this.children[side < 0 ? 0 : this.children.length - 1];
    return child.size == 0 || child.emptyChildAt(side);
  }
  domAfterPos(pos) {
    let { node, offset } = this.domFromPos(pos, 0);
    if (node.nodeType != 1 || offset == node.childNodes.length)
      throw new RangeError("No node after pos " + pos);
    return node.childNodes[offset];
  }
  // View descs are responsible for setting any selection that falls
  // entirely inside of them, so that custom implementations can do
  // custom things with the selection. Note that this falls apart when
  // a selection starts in such a node and ends in another, in which
  // case we just use whatever domFromPos produces as a best effort.
  setSelection(anchor, head, view, force = false) {
    let from2 = Math.min(anchor, head), to = Math.max(anchor, head);
    for (let i = 0, offset = 0; i < this.children.length; i++) {
      let child = this.children[i], end = offset + child.size;
      if (from2 > offset && to < end)
        return child.setSelection(anchor - offset - child.border, head - offset - child.border, view, force);
      offset = end;
    }
    let anchorDOM = this.domFromPos(anchor, anchor ? -1 : 1);
    let headDOM = head == anchor ? anchorDOM : this.domFromPos(head, head ? -1 : 1);
    let domSel = view.root.getSelection();
    let selRange = view.domSelectionRange();
    let brKludge = false;
    if ((gecko || safari) && anchor == head) {
      let { node, offset } = anchorDOM;
      if (node.nodeType == 3) {
        brKludge = !!(offset && node.nodeValue[offset - 1] == "\n");
        if (brKludge && offset == node.nodeValue.length) {
          for (let scan = node, after; scan; scan = scan.parentNode) {
            if (after = scan.nextSibling) {
              if (after.nodeName == "BR")
                anchorDOM = headDOM = { node: after.parentNode, offset: domIndex(after) + 1 };
              break;
            }
            let desc = scan.pmViewDesc;
            if (desc && desc.node && desc.node.isBlock)
              break;
          }
        }
      } else {
        let prev = node.childNodes[offset - 1];
        brKludge = prev && (prev.nodeName == "BR" || prev.contentEditable == "false");
      }
    }
    if (gecko && selRange.focusNode && selRange.focusNode != headDOM.node && selRange.focusNode.nodeType == 1) {
      let after = selRange.focusNode.childNodes[selRange.focusOffset];
      if (after && after.contentEditable == "false")
        force = true;
    }
    if (!(force || brKludge && safari) && isEquivalentPosition(anchorDOM.node, anchorDOM.offset, selRange.anchorNode, selRange.anchorOffset) && isEquivalentPosition(headDOM.node, headDOM.offset, selRange.focusNode, selRange.focusOffset))
      return;
    let domSelExtended = false;
    if ((domSel.extend || anchor == head) && !(brKludge && gecko)) {
      domSel.collapse(anchorDOM.node, anchorDOM.offset);
      try {
        if (anchor != head)
          domSel.extend(headDOM.node, headDOM.offset);
        domSelExtended = true;
      } catch (_10) {
      }
    }
    if (!domSelExtended) {
      if (anchor > head) {
        let tmp = anchorDOM;
        anchorDOM = headDOM;
        headDOM = tmp;
      }
      let range = document.createRange();
      range.setEnd(headDOM.node, headDOM.offset);
      range.setStart(anchorDOM.node, anchorDOM.offset);
      domSel.removeAllRanges();
      domSel.addRange(range);
    }
  }
  ignoreMutation(mutation) {
    return !this.contentDOM && mutation.type != "selection";
  }
  get contentLost() {
    return this.contentDOM && this.contentDOM != this.dom && !this.dom.contains(this.contentDOM);
  }
  // Remove a subtree of the element tree that has been touched
  // by a DOM change, so that the next update will redraw it.
  markDirty(from2, to) {
    for (let offset = 0, i = 0; i < this.children.length; i++) {
      let child = this.children[i], end = offset + child.size;
      if (offset == end ? from2 <= end && to >= offset : from2 < end && to > offset) {
        let startInside = offset + child.border, endInside = end - child.border;
        if (from2 >= startInside && to <= endInside) {
          this.dirty = from2 == offset || to == end ? CONTENT_DIRTY : CHILD_DIRTY;
          if (from2 == startInside && to == endInside && (child.contentLost || child.dom.parentNode != this.contentDOM))
            child.dirty = NODE_DIRTY;
          else
            child.markDirty(from2 - startInside, to - startInside);
          return;
        } else {
          child.dirty = child.dom == child.contentDOM && child.dom.parentNode == this.contentDOM && !child.children.length ? CONTENT_DIRTY : NODE_DIRTY;
        }
      }
      offset = end;
    }
    this.dirty = CONTENT_DIRTY;
  }
  markParentsDirty() {
    let level = 1;
    for (let node = this.parent; node; node = node.parent, level++) {
      let dirty = level == 1 ? CONTENT_DIRTY : CHILD_DIRTY;
      if (node.dirty < dirty)
        node.dirty = dirty;
    }
  }
  get domAtom() {
    return false;
  }
  get ignoreForCoords() {
    return false;
  }
  get ignoreForSelection() {
    return false;
  }
  isText(text5) {
    return false;
  }
};
var WidgetViewDesc = class extends ViewDesc {
  constructor(parent, widget, view, pos) {
    let self, dom = widget.type.toDOM;
    if (typeof dom == "function")
      dom = dom(view, () => {
        if (!self)
          return pos;
        if (self.parent)
          return self.parent.posBeforeChild(self);
      });
    if (!widget.type.spec.raw) {
      if (dom.nodeType != 1) {
        let wrap2 = document.createElement("span");
        wrap2.appendChild(dom);
        dom = wrap2;
      }
      dom.contentEditable = "false";
      dom.classList.add("ProseMirror-widget");
    }
    super(parent, [], dom, null);
    this.widget = widget;
    this.widget = widget;
    self = this;
  }
  matchesWidget(widget) {
    return this.dirty == NOT_DIRTY && widget.type.eq(this.widget.type);
  }
  parseRule() {
    return { ignore: true };
  }
  stopEvent(event) {
    let stop = this.widget.spec.stopEvent;
    return stop ? stop(event) : false;
  }
  ignoreMutation(mutation) {
    return mutation.type != "selection" || this.widget.spec.ignoreSelection;
  }
  destroy() {
    this.widget.type.destroy(this.dom);
    super.destroy();
  }
  get domAtom() {
    return true;
  }
  get ignoreForSelection() {
    return !!this.widget.type.spec.relaxedSide;
  }
  get side() {
    return this.widget.type.side;
  }
};
var CompositionViewDesc = class extends ViewDesc {
  constructor(parent, dom, textDOM, text5) {
    super(parent, [], dom, null);
    this.textDOM = textDOM;
    this.text = text5;
  }
  get size() {
    return this.text.length;
  }
  localPosFromDOM(dom, offset) {
    if (dom != this.textDOM)
      return this.posAtStart + (offset ? this.size : 0);
    return this.posAtStart + offset;
  }
  domFromPos(pos) {
    return { node: this.textDOM, offset: pos };
  }
  ignoreMutation(mut) {
    return mut.type === "characterData" && mut.target.nodeValue == mut.oldValue;
  }
};
var MarkViewDesc = class _MarkViewDesc extends ViewDesc {
  constructor(parent, mark, dom, contentDOM, spec) {
    super(parent, [], dom, contentDOM);
    this.mark = mark;
    this.spec = spec;
  }
  static create(parent, mark, inline, view) {
    let custom = view.nodeViews[mark.type.name];
    let spec = custom && custom(mark, view, inline);
    if (!spec || !spec.dom)
      spec = DOMSerializer.renderSpec(document, mark.type.spec.toDOM(mark, inline), null, mark.attrs);
    return new _MarkViewDesc(parent, mark, spec.dom, spec.contentDOM || spec.dom, spec);
  }
  parseRule() {
    if (this.dirty & NODE_DIRTY || this.mark.type.spec.reparseInView)
      return null;
    return { mark: this.mark.type.name, attrs: this.mark.attrs, contentElement: this.contentDOM };
  }
  matchesMark(mark) {
    return this.dirty != NODE_DIRTY && this.mark.eq(mark);
  }
  markDirty(from2, to) {
    super.markDirty(from2, to);
    if (this.dirty != NOT_DIRTY) {
      let parent = this.parent;
      while (!parent.node)
        parent = parent.parent;
      if (parent.dirty < this.dirty)
        parent.dirty = this.dirty;
      this.dirty = NOT_DIRTY;
    }
  }
  slice(from2, to, view) {
    let copy3 = _MarkViewDesc.create(this.parent, this.mark, true, view);
    let nodes = this.children, size = this.size;
    if (to < size)
      nodes = replaceNodes(nodes, to, size, view);
    if (from2 > 0)
      nodes = replaceNodes(nodes, 0, from2, view);
    for (let i = 0; i < nodes.length; i++)
      nodes[i].parent = copy3;
    copy3.children = nodes;
    return copy3;
  }
  ignoreMutation(mutation) {
    return this.spec.ignoreMutation ? this.spec.ignoreMutation(mutation) : super.ignoreMutation(mutation);
  }
  destroy() {
    if (this.spec.destroy)
      this.spec.destroy();
    super.destroy();
  }
};
var NodeViewDesc = class _NodeViewDesc extends ViewDesc {
  constructor(parent, node, outerDeco, innerDeco, dom, contentDOM, nodeDOM, view, pos) {
    super(parent, [], dom, contentDOM);
    this.node = node;
    this.outerDeco = outerDeco;
    this.innerDeco = innerDeco;
    this.nodeDOM = nodeDOM;
  }
  // By default, a node is rendered using the `toDOM` method from the
  // node type spec. But client code can use the `nodeViews` spec to
  // supply a custom node view, which can influence various aspects of
  // the way the node works.
  //
  // (Using subclassing for this was intentionally decided against,
  // since it'd require exposing a whole slew of finicky
  // implementation details to the user code that they probably will
  // never need.)
  static create(parent, node, outerDeco, innerDeco, view, pos) {
    let custom = view.nodeViews[node.type.name], descObj;
    let spec = custom && custom(node, view, () => {
      if (!descObj)
        return pos;
      if (descObj.parent)
        return descObj.parent.posBeforeChild(descObj);
    }, outerDeco, innerDeco);
    let dom = spec && spec.dom, contentDOM = spec && spec.contentDOM;
    if (node.isText) {
      if (!dom)
        dom = document.createTextNode(node.text);
      else if (dom.nodeType != 3)
        throw new RangeError("Text must be rendered as a DOM text node");
    } else if (!dom) {
      let spec2 = DOMSerializer.renderSpec(document, node.type.spec.toDOM(node), null, node.attrs);
      ({ dom, contentDOM } = spec2);
    }
    if (!contentDOM && !node.isText && dom.nodeName != "BR") {
      if (!dom.hasAttribute("contenteditable"))
        dom.contentEditable = "false";
      if (node.type.spec.draggable)
        dom.draggable = true;
    }
    let nodeDOM = dom;
    dom = applyOuterDeco(dom, outerDeco, node);
    if (spec)
      return descObj = new CustomNodeViewDesc(parent, node, outerDeco, innerDeco, dom, contentDOM || null, nodeDOM, spec, view, pos + 1);
    else if (node.isText)
      return new TextViewDesc(parent, node, outerDeco, innerDeco, dom, nodeDOM, view);
    else
      return new _NodeViewDesc(parent, node, outerDeco, innerDeco, dom, contentDOM || null, nodeDOM, view, pos + 1);
  }
  parseRule() {
    if (this.node.type.spec.reparseInView)
      return null;
    let rule = { node: this.node.type.name, attrs: this.node.attrs };
    if (this.node.type.whitespace == "pre")
      rule.preserveWhitespace = "full";
    if (!this.contentDOM) {
      rule.getContent = () => this.node.content;
    } else if (!this.contentLost) {
      rule.contentElement = this.contentDOM;
    } else {
      for (let i = this.children.length - 1; i >= 0; i--) {
        let child = this.children[i];
        if (this.dom.contains(child.dom.parentNode)) {
          rule.contentElement = child.dom.parentNode;
          break;
        }
      }
      if (!rule.contentElement)
        rule.getContent = () => Fragment.empty;
    }
    return rule;
  }
  matchesNode(node, outerDeco, innerDeco) {
    return this.dirty == NOT_DIRTY && node.eq(this.node) && sameOuterDeco(outerDeco, this.outerDeco) && innerDeco.eq(this.innerDeco);
  }
  get size() {
    return this.node.nodeSize;
  }
  get border() {
    return this.node.isLeaf ? 0 : 1;
  }
  // Syncs `this.children` to match `this.node.content` and the local
  // decorations, possibly introducing nesting for marks. Then, in a
  // separate step, syncs the DOM inside `this.contentDOM` to
  // `this.children`.
  updateChildren(view, pos) {
    let inline = this.node.inlineContent, off = pos;
    let composition = view.composing ? this.localCompositionInfo(view, pos) : null;
    let localComposition = composition && composition.pos > -1 ? composition : null;
    let compositionInChild = composition && composition.pos < 0;
    let updater = new ViewTreeUpdater(this, localComposition && localComposition.node, view);
    iterDeco(this.node, this.innerDeco, (widget, i, insideNode) => {
      if (widget.spec.marks)
        updater.syncToMarks(widget.spec.marks, inline, view, i);
      else if (widget.type.side >= 0 && !insideNode)
        updater.syncToMarks(i == this.node.childCount ? Mark.none : this.node.child(i).marks, inline, view, i);
      updater.placeWidget(widget, view, off);
    }, (child, outerDeco, innerDeco, i) => {
      updater.syncToMarks(child.marks, inline, view, i);
      let compIndex;
      if (updater.findNodeMatch(child, outerDeco, innerDeco, i)) ;
      else if (compositionInChild && view.state.selection.from > off && view.state.selection.to < off + child.nodeSize && (compIndex = updater.findIndexWithChild(composition.node)) > -1 && updater.updateNodeAt(child, outerDeco, innerDeco, compIndex, view)) ;
      else if (updater.updateNextNode(child, outerDeco, innerDeco, view, i, off)) ;
      else {
        updater.addNode(child, outerDeco, innerDeco, view, off);
      }
      off += child.nodeSize;
    });
    updater.syncToMarks([], inline, view, 0);
    if (this.node.isTextblock)
      updater.addTextblockHacks();
    updater.destroyRest();
    if (updater.changed || this.dirty == CONTENT_DIRTY) {
      if (localComposition)
        this.protectLocalComposition(view, localComposition);
      renderDescs(this.contentDOM, this.children, view);
      if (ios)
        iosHacks(this.dom);
    }
  }
  localCompositionInfo(view, pos) {
    let { from: from2, to } = view.state.selection;
    if (!(view.state.selection instanceof TextSelection) || from2 < pos || to > pos + this.node.content.size)
      return null;
    let textNode = view.input.compositionNode;
    if (!textNode || !this.dom.contains(textNode.parentNode))
      return null;
    if (this.node.inlineContent) {
      let text5 = textNode.nodeValue;
      let textPos = findTextInFragment(this.node.content, text5, from2 - pos, to - pos);
      return textPos < 0 ? null : { node: textNode, pos: textPos, text: text5 };
    } else {
      return { node: textNode, pos: -1, text: "" };
    }
  }
  protectLocalComposition(view, { node, pos, text: text5 }) {
    if (this.getDesc(node))
      return;
    let topNode = node;
    for (; ; topNode = topNode.parentNode) {
      if (topNode.parentNode == this.contentDOM)
        break;
      while (topNode.previousSibling)
        topNode.parentNode.removeChild(topNode.previousSibling);
      while (topNode.nextSibling)
        topNode.parentNode.removeChild(topNode.nextSibling);
      if (topNode.pmViewDesc)
        topNode.pmViewDesc = void 0;
    }
    let desc = new CompositionViewDesc(this, topNode, node, text5);
    view.input.compositionNodes.push(desc);
    this.children = replaceNodes(this.children, pos, pos + text5.length, view, desc);
  }
  // If this desc must be updated to match the given node decoration,
  // do so and return true.
  update(node, outerDeco, innerDeco, view) {
    if (this.dirty == NODE_DIRTY || !node.sameMarkup(this.node))
      return false;
    this.updateInner(node, outerDeco, innerDeco, view);
    return true;
  }
  updateInner(node, outerDeco, innerDeco, view) {
    this.updateOuterDeco(outerDeco);
    this.node = node;
    this.innerDeco = innerDeco;
    if (this.contentDOM)
      this.updateChildren(view, this.posAtStart);
    this.dirty = NOT_DIRTY;
  }
  updateOuterDeco(outerDeco) {
    if (sameOuterDeco(outerDeco, this.outerDeco))
      return;
    let needsWrap = this.nodeDOM.nodeType != 1;
    let oldDOM = this.dom;
    this.dom = patchOuterDeco(this.dom, this.nodeDOM, computeOuterDeco(this.outerDeco, this.node, needsWrap), computeOuterDeco(outerDeco, this.node, needsWrap));
    if (this.dom != oldDOM) {
      oldDOM.pmViewDesc = void 0;
      this.dom.pmViewDesc = this;
    }
    this.outerDeco = outerDeco;
  }
  // Mark this node as being the selected node.
  selectNode() {
    if (this.nodeDOM.nodeType == 1) {
      this.nodeDOM.classList.add("ProseMirror-selectednode");
      if (this.contentDOM || !this.node.type.spec.draggable)
        this.nodeDOM.draggable = true;
    }
  }
  // Remove selected node marking from this node.
  deselectNode() {
    if (this.nodeDOM.nodeType == 1) {
      this.nodeDOM.classList.remove("ProseMirror-selectednode");
      if (this.contentDOM || !this.node.type.spec.draggable)
        this.nodeDOM.removeAttribute("draggable");
    }
  }
  get domAtom() {
    return this.node.isAtom;
  }
};
function docViewDesc(doc3, outerDeco, innerDeco, dom, view) {
  applyOuterDeco(dom, outerDeco, doc3);
  let docView = new NodeViewDesc(void 0, doc3, outerDeco, innerDeco, dom, dom, dom, view, 0);
  if (docView.contentDOM)
    docView.updateChildren(view, 0);
  return docView;
}
var TextViewDesc = class _TextViewDesc extends NodeViewDesc {
  constructor(parent, node, outerDeco, innerDeco, dom, nodeDOM, view) {
    super(parent, node, outerDeco, innerDeco, dom, null, nodeDOM, view, 0);
  }
  parseRule() {
    let skip = this.nodeDOM.parentNode;
    while (skip && skip != this.dom && !skip.pmIsDeco)
      skip = skip.parentNode;
    return { skip: skip || true };
  }
  update(node, outerDeco, innerDeco, view) {
    if (this.dirty == NODE_DIRTY || this.dirty != NOT_DIRTY && !this.inParent() || !node.sameMarkup(this.node))
      return false;
    this.updateOuterDeco(outerDeco);
    if ((this.dirty != NOT_DIRTY || node.text != this.node.text) && node.text != this.nodeDOM.nodeValue) {
      this.nodeDOM.nodeValue = node.text;
      if (view.trackWrites == this.nodeDOM)
        view.trackWrites = null;
    }
    this.node = node;
    this.dirty = NOT_DIRTY;
    return true;
  }
  inParent() {
    let parentDOM = this.parent.contentDOM;
    for (let n = this.nodeDOM; n; n = n.parentNode)
      if (n == parentDOM)
        return true;
    return false;
  }
  domFromPos(pos) {
    return { node: this.nodeDOM, offset: pos };
  }
  localPosFromDOM(dom, offset, bias) {
    if (dom == this.nodeDOM)
      return this.posAtStart + Math.min(offset, this.node.text.length);
    return super.localPosFromDOM(dom, offset, bias);
  }
  ignoreMutation(mutation) {
    return mutation.type != "characterData" && mutation.type != "selection";
  }
  slice(from2, to, view) {
    let node = this.node.cut(from2, to), dom = document.createTextNode(node.text);
    return new _TextViewDesc(this.parent, node, this.outerDeco, this.innerDeco, dom, dom, view);
  }
  markDirty(from2, to) {
    super.markDirty(from2, to);
    if (this.dom != this.nodeDOM && (from2 == 0 || to == this.nodeDOM.nodeValue.length))
      this.dirty = NODE_DIRTY;
  }
  get domAtom() {
    return false;
  }
  isText(text5) {
    return this.node.text == text5;
  }
};
var TrailingHackViewDesc = class extends ViewDesc {
  parseRule() {
    return { ignore: true };
  }
  matchesHack(nodeName) {
    return this.dirty == NOT_DIRTY && this.dom.nodeName == nodeName;
  }
  get domAtom() {
    return true;
  }
  get ignoreForCoords() {
    return this.dom.nodeName == "IMG";
  }
};
var CustomNodeViewDesc = class extends NodeViewDesc {
  constructor(parent, node, outerDeco, innerDeco, dom, contentDOM, nodeDOM, spec, view, pos) {
    super(parent, node, outerDeco, innerDeco, dom, contentDOM, nodeDOM, view, pos);
    this.spec = spec;
  }
  // A custom `update` method gets to decide whether the update goes
  // through. If it does, and there's a `contentDOM` node, our logic
  // updates the children.
  update(node, outerDeco, innerDeco, view) {
    if (this.dirty == NODE_DIRTY)
      return false;
    if (this.spec.update && (this.node.type == node.type || this.spec.multiType)) {
      let result = this.spec.update(node, outerDeco, innerDeco);
      if (result)
        this.updateInner(node, outerDeco, innerDeco, view);
      return result;
    } else if (!this.contentDOM && !node.isLeaf) {
      return false;
    } else {
      return super.update(node, outerDeco, innerDeco, view);
    }
  }
  selectNode() {
    this.spec.selectNode ? this.spec.selectNode() : super.selectNode();
  }
  deselectNode() {
    this.spec.deselectNode ? this.spec.deselectNode() : super.deselectNode();
  }
  setSelection(anchor, head, view, force) {
    this.spec.setSelection ? this.spec.setSelection(anchor, head, view.root) : super.setSelection(anchor, head, view, force);
  }
  destroy() {
    if (this.spec.destroy)
      this.spec.destroy();
    super.destroy();
  }
  stopEvent(event) {
    return this.spec.stopEvent ? this.spec.stopEvent(event) : false;
  }
  ignoreMutation(mutation) {
    return this.spec.ignoreMutation ? this.spec.ignoreMutation(mutation) : super.ignoreMutation(mutation);
  }
};
function renderDescs(parentDOM, descs, view) {
  let dom = parentDOM.firstChild, written = false;
  for (let i = 0; i < descs.length; i++) {
    let desc = descs[i], childDOM = desc.dom;
    if (childDOM.parentNode == parentDOM) {
      while (childDOM != dom) {
        dom = rm(dom);
        written = true;
      }
      dom = dom.nextSibling;
    } else {
      written = true;
      parentDOM.insertBefore(childDOM, dom);
    }
    if (desc instanceof MarkViewDesc) {
      let pos = dom ? dom.previousSibling : parentDOM.lastChild;
      renderDescs(desc.contentDOM, desc.children, view);
      dom = pos ? pos.nextSibling : parentDOM.firstChild;
    }
  }
  while (dom) {
    dom = rm(dom);
    written = true;
  }
  if (written && view.trackWrites == parentDOM)
    view.trackWrites = null;
}
var OuterDecoLevel = function(nodeName) {
  if (nodeName)
    this.nodeName = nodeName;
};
OuterDecoLevel.prototype = /* @__PURE__ */ Object.create(null);
var noDeco = [new OuterDecoLevel()];
function computeOuterDeco(outerDeco, node, needsWrap) {
  if (outerDeco.length == 0)
    return noDeco;
  let top = needsWrap ? noDeco[0] : new OuterDecoLevel(), result = [top];
  for (let i = 0; i < outerDeco.length; i++) {
    let attrs = outerDeco[i].type.attrs;
    if (!attrs)
      continue;
    if (attrs.nodeName)
      result.push(top = new OuterDecoLevel(attrs.nodeName));
    for (let name in attrs) {
      let val = attrs[name];
      if (val == null)
        continue;
      if (needsWrap && result.length == 1)
        result.push(top = new OuterDecoLevel(node.isInline ? "span" : "div"));
      if (name == "class")
        top.class = (top.class ? top.class + " " : "") + val;
      else if (name == "style")
        top.style = (top.style ? top.style + ";" : "") + val;
      else if (name != "nodeName")
        top[name] = val;
    }
  }
  return result;
}
function patchOuterDeco(outerDOM, nodeDOM, prevComputed, curComputed) {
  if (prevComputed == noDeco && curComputed == noDeco)
    return nodeDOM;
  let curDOM = nodeDOM;
  for (let i = 0; i < curComputed.length; i++) {
    let deco = curComputed[i], prev = prevComputed[i];
    if (i) {
      let parent;
      if (prev && prev.nodeName == deco.nodeName && curDOM != outerDOM && (parent = curDOM.parentNode) && parent.nodeName.toLowerCase() == deco.nodeName) {
        curDOM = parent;
      } else {
        parent = document.createElement(deco.nodeName);
        parent.pmIsDeco = true;
        parent.appendChild(curDOM);
        prev = noDeco[0];
        curDOM = parent;
      }
    }
    patchAttributes(curDOM, prev || noDeco[0], deco);
  }
  return curDOM;
}
function patchAttributes(dom, prev, cur) {
  for (let name in prev)
    if (name != "class" && name != "style" && name != "nodeName" && !(name in cur))
      dom.removeAttribute(name);
  for (let name in cur)
    if (name != "class" && name != "style" && name != "nodeName" && cur[name] != prev[name])
      dom.setAttribute(name, cur[name]);
  if (prev.class != cur.class) {
    let prevList = prev.class ? prev.class.split(" ").filter(Boolean) : [];
    let curList = cur.class ? cur.class.split(" ").filter(Boolean) : [];
    for (let i = 0; i < prevList.length; i++)
      if (curList.indexOf(prevList[i]) == -1)
        dom.classList.remove(prevList[i]);
    for (let i = 0; i < curList.length; i++)
      if (prevList.indexOf(curList[i]) == -1)
        dom.classList.add(curList[i]);
    if (dom.classList.length == 0)
      dom.removeAttribute("class");
  }
  if (prev.style != cur.style) {
    if (prev.style) {
      let prop = /\s*([\w\-\xa1-\uffff]+)\s*:(?:"(?:\\.|[^"])*"|'(?:\\.|[^'])*'|\(.*?\)|[^;])*/g, m;
      while (m = prop.exec(prev.style))
        dom.style.removeProperty(m[1]);
    }
    if (cur.style)
      dom.style.cssText += cur.style;
  }
}
function applyOuterDeco(dom, deco, node) {
  return patchOuterDeco(dom, dom, noDeco, computeOuterDeco(deco, node, dom.nodeType != 1));
}
function sameOuterDeco(a2, b2) {
  if (a2.length != b2.length)
    return false;
  for (let i = 0; i < a2.length; i++)
    if (!a2[i].type.eq(b2[i].type))
      return false;
  return true;
}
function rm(dom) {
  let next = dom.nextSibling;
  dom.parentNode.removeChild(dom);
  return next;
}
var ViewTreeUpdater = class {
  constructor(top, lock, view) {
    this.lock = lock;
    this.view = view;
    this.index = 0;
    this.stack = [];
    this.changed = false;
    this.top = top;
    this.preMatch = preMatch(top.node.content, top);
  }
  // Destroy and remove the children between the given indices in
  // `this.top`.
  destroyBetween(start, end) {
    if (start == end)
      return;
    for (let i = start; i < end; i++)
      this.top.children[i].destroy();
    this.top.children.splice(start, end - start);
    this.changed = true;
  }
  // Destroy all remaining children in `this.top`.
  destroyRest() {
    this.destroyBetween(this.index, this.top.children.length);
  }
  // Sync the current stack of mark descs with the given array of
  // marks, reusing existing mark descs when possible.
  syncToMarks(marks, inline, view, parentIndex) {
    let keep = 0, depth = this.stack.length >> 1;
    let maxKeep = Math.min(depth, marks.length);
    while (keep < maxKeep && (keep == depth - 1 ? this.top : this.stack[keep + 1 << 1]).matchesMark(marks[keep]) && marks[keep].type.spec.spanning !== false)
      keep++;
    while (keep < depth) {
      this.destroyRest();
      this.top.dirty = NOT_DIRTY;
      this.index = this.stack.pop();
      this.top = this.stack.pop();
      depth--;
    }
    while (depth < marks.length) {
      this.stack.push(this.top, this.index + 1);
      let found2 = -1, scanTo = this.top.children.length;
      if (parentIndex < this.preMatch.index)
        scanTo = Math.min(this.index + 3, scanTo);
      for (let i = this.index; i < scanTo; i++) {
        let next = this.top.children[i];
        if (next.matchesMark(marks[depth]) && !this.isLocked(next.dom)) {
          found2 = i;
          break;
        }
      }
      if (found2 > -1) {
        if (found2 > this.index) {
          this.changed = true;
          this.destroyBetween(this.index, found2);
        }
        this.top = this.top.children[this.index];
      } else {
        let markDesc = MarkViewDesc.create(this.top, marks[depth], inline, view);
        this.top.children.splice(this.index, 0, markDesc);
        this.top = markDesc;
        this.changed = true;
      }
      this.index = 0;
      depth++;
    }
  }
  // Try to find a node desc matching the given data. Skip over it and
  // return true when successful.
  findNodeMatch(node, outerDeco, innerDeco, index) {
    let found2 = -1, targetDesc;
    if (index >= this.preMatch.index && (targetDesc = this.preMatch.matches[index - this.preMatch.index]).parent == this.top && targetDesc.matchesNode(node, outerDeco, innerDeco)) {
      found2 = this.top.children.indexOf(targetDesc, this.index);
    } else {
      for (let i = this.index, e = Math.min(this.top.children.length, i + 5); i < e; i++) {
        let child = this.top.children[i];
        if (child.matchesNode(node, outerDeco, innerDeco) && !this.preMatch.matched.has(child)) {
          found2 = i;
          break;
        }
      }
    }
    if (found2 < 0)
      return false;
    this.destroyBetween(this.index, found2);
    this.index++;
    return true;
  }
  updateNodeAt(node, outerDeco, innerDeco, index, view) {
    let child = this.top.children[index];
    if (child.dirty == NODE_DIRTY && child.dom == child.contentDOM)
      child.dirty = CONTENT_DIRTY;
    if (!child.update(node, outerDeco, innerDeco, view))
      return false;
    this.destroyBetween(this.index, index);
    this.index++;
    return true;
  }
  findIndexWithChild(domNode) {
    for (; ; ) {
      let parent = domNode.parentNode;
      if (!parent)
        return -1;
      if (parent == this.top.contentDOM) {
        let desc = domNode.pmViewDesc;
        if (desc)
          for (let i = this.index; i < this.top.children.length; i++) {
            if (this.top.children[i] == desc)
              return i;
          }
        return -1;
      }
      domNode = parent;
    }
  }
  // Try to update the next node, if any, to the given data. Checks
  // pre-matches to avoid overwriting nodes that could still be used.
  updateNextNode(node, outerDeco, innerDeco, view, index, pos) {
    for (let i = this.index; i < this.top.children.length; i++) {
      let next = this.top.children[i];
      if (next instanceof NodeViewDesc) {
        let preMatch2 = this.preMatch.matched.get(next);
        if (preMatch2 != null && preMatch2 != index)
          return false;
        let nextDOM = next.dom, updated;
        let locked = this.isLocked(nextDOM) && !(node.isText && next.node && next.node.isText && next.nodeDOM.nodeValue == node.text && next.dirty != NODE_DIRTY && sameOuterDeco(outerDeco, next.outerDeco));
        if (!locked && next.update(node, outerDeco, innerDeco, view)) {
          this.destroyBetween(this.index, i);
          if (next.dom != nextDOM)
            this.changed = true;
          this.index++;
          return true;
        } else if (!locked && (updated = this.recreateWrapper(next, node, outerDeco, innerDeco, view, pos))) {
          this.destroyBetween(this.index, i);
          this.top.children[this.index] = updated;
          if (updated.contentDOM) {
            updated.dirty = CONTENT_DIRTY;
            updated.updateChildren(view, pos + 1);
            updated.dirty = NOT_DIRTY;
          }
          this.changed = true;
          this.index++;
          return true;
        }
        break;
      }
    }
    return false;
  }
  // When a node with content is replaced by a different node with
  // identical content, move over its children.
  recreateWrapper(next, node, outerDeco, innerDeco, view, pos) {
    if (next.dirty || node.isAtom || !next.children.length || !next.node.content.eq(node.content) || !sameOuterDeco(outerDeco, next.outerDeco) || !innerDeco.eq(next.innerDeco))
      return null;
    let wrapper = NodeViewDesc.create(this.top, node, outerDeco, innerDeco, view, pos);
    if (wrapper.contentDOM) {
      wrapper.children = next.children;
      next.children = [];
      for (let ch of wrapper.children)
        ch.parent = wrapper;
    }
    next.destroy();
    return wrapper;
  }
  // Insert the node as a newly created node desc.
  addNode(node, outerDeco, innerDeco, view, pos) {
    let desc = NodeViewDesc.create(this.top, node, outerDeco, innerDeco, view, pos);
    if (desc.contentDOM)
      desc.updateChildren(view, pos + 1);
    this.top.children.splice(this.index++, 0, desc);
    this.changed = true;
  }
  placeWidget(widget, view, pos) {
    let next = this.index < this.top.children.length ? this.top.children[this.index] : null;
    if (next && next.matchesWidget(widget) && (widget == next.widget || !next.widget.type.toDOM.parentNode)) {
      this.index++;
    } else {
      let desc = new WidgetViewDesc(this.top, widget, view, pos);
      this.top.children.splice(this.index++, 0, desc);
      this.changed = true;
    }
  }
  // Make sure a textblock looks and behaves correctly in
  // contentEditable.
  addTextblockHacks() {
    let lastChild = this.top.children[this.index - 1], parent = this.top;
    while (lastChild instanceof MarkViewDesc) {
      parent = lastChild;
      lastChild = parent.children[parent.children.length - 1];
    }
    if (!lastChild || // Empty textblock
    !(lastChild instanceof TextViewDesc) || /\n$/.test(lastChild.node.text) || this.view.requiresGeckoHackNode && /\s$/.test(lastChild.node.text)) {
      if ((safari || chrome) && lastChild && lastChild.dom.contentEditable == "false")
        this.addHackNode("IMG", parent);
      this.addHackNode("BR", this.top);
    }
  }
  addHackNode(nodeName, parent) {
    if (parent == this.top && this.index < parent.children.length && parent.children[this.index].matchesHack(nodeName)) {
      this.index++;
    } else {
      let dom = document.createElement(nodeName);
      if (nodeName == "IMG") {
        dom.className = "ProseMirror-separator";
        dom.alt = "";
      }
      if (nodeName == "BR")
        dom.className = "ProseMirror-trailingBreak";
      let hack = new TrailingHackViewDesc(this.top, [], dom, null);
      if (parent != this.top)
        parent.children.push(hack);
      else
        parent.children.splice(this.index++, 0, hack);
      this.changed = true;
    }
  }
  isLocked(node) {
    return this.lock && (node == this.lock || node.nodeType == 1 && node.contains(this.lock.parentNode));
  }
};
function preMatch(frag, parentDesc) {
  let curDesc = parentDesc, descI = curDesc.children.length;
  let fI = frag.childCount, matched = /* @__PURE__ */ new Map(), matches2 = [];
  outer: while (fI > 0) {
    let desc;
    for (; ; ) {
      if (descI) {
        let next = curDesc.children[descI - 1];
        if (next instanceof MarkViewDesc) {
          curDesc = next;
          descI = next.children.length;
        } else {
          desc = next;
          descI--;
          break;
        }
      } else if (curDesc == parentDesc) {
        break outer;
      } else {
        descI = curDesc.parent.children.indexOf(curDesc);
        curDesc = curDesc.parent;
      }
    }
    let node = desc.node;
    if (!node)
      continue;
    if (node != frag.child(fI - 1))
      break;
    --fI;
    matched.set(desc, fI);
    matches2.push(desc);
  }
  return { index: fI, matched, matches: matches2.reverse() };
}
function compareSide(a2, b2) {
  return a2.type.side - b2.type.side;
}
function iterDeco(parent, deco, onWidget, onNode) {
  let locals = deco.locals(parent), offset = 0;
  if (locals.length == 0) {
    for (let i = 0; i < parent.childCount; i++) {
      let child = parent.child(i);
      onNode(child, locals, deco.forChild(offset, child), i);
      offset += child.nodeSize;
    }
    return;
  }
  let decoIndex = 0, active = [], restNode = null;
  for (let parentIndex = 0; ; ) {
    let widget, widgets;
    while (decoIndex < locals.length && locals[decoIndex].to == offset) {
      let next = locals[decoIndex++];
      if (next.widget) {
        if (!widget)
          widget = next;
        else
          (widgets || (widgets = [widget])).push(next);
      }
    }
    if (widget) {
      if (widgets) {
        widgets.sort(compareSide);
        for (let i = 0; i < widgets.length; i++)
          onWidget(widgets[i], parentIndex, !!restNode);
      } else {
        onWidget(widget, parentIndex, !!restNode);
      }
    }
    let child, index;
    if (restNode) {
      index = -1;
      child = restNode;
      restNode = null;
    } else if (parentIndex < parent.childCount) {
      index = parentIndex;
      child = parent.child(parentIndex++);
    } else {
      break;
    }
    for (let i = 0; i < active.length; i++)
      if (active[i].to <= offset)
        active.splice(i--, 1);
    while (decoIndex < locals.length && locals[decoIndex].from <= offset && locals[decoIndex].to > offset)
      active.push(locals[decoIndex++]);
    let end = offset + child.nodeSize;
    if (child.isText) {
      let cutAt = end;
      if (decoIndex < locals.length && locals[decoIndex].from < cutAt)
        cutAt = locals[decoIndex].from;
      for (let i = 0; i < active.length; i++)
        if (active[i].to < cutAt)
          cutAt = active[i].to;
      if (cutAt < end) {
        restNode = child.cut(cutAt - offset);
        child = child.cut(0, cutAt - offset);
        end = cutAt;
        index = -1;
      }
    } else {
      while (decoIndex < locals.length && locals[decoIndex].to < end)
        decoIndex++;
    }
    let outerDeco = child.isInline && !child.isLeaf ? active.filter((d2) => !d2.inline) : active.slice();
    onNode(child, outerDeco, deco.forChild(offset, child), index);
    offset = end;
  }
}
function iosHacks(dom) {
  if (dom.nodeName == "UL" || dom.nodeName == "OL") {
    let oldCSS = dom.style.cssText;
    dom.style.cssText = oldCSS + "; list-style: square !important";
    window.getComputedStyle(dom).listStyle;
    dom.style.cssText = oldCSS;
  }
}
function findTextInFragment(frag, text5, from2, to) {
  for (let i = 0, pos = 0; i < frag.childCount && pos <= to; ) {
    let child = frag.child(i++), childStart = pos;
    pos += child.nodeSize;
    if (!child.isText)
      continue;
    let str = child.text;
    while (i < frag.childCount) {
      let next = frag.child(i++);
      pos += next.nodeSize;
      if (!next.isText)
        break;
      str += next.text;
    }
    if (pos >= from2) {
      if (pos >= to && str.slice(to - text5.length - childStart, to - childStart) == text5)
        return to - text5.length;
      let found2 = childStart < to ? str.lastIndexOf(text5, to - childStart - 1) : -1;
      if (found2 >= 0 && found2 + text5.length + childStart >= from2)
        return childStart + found2;
      if (from2 == to && str.length >= to + text5.length - childStart && str.slice(to - childStart, to - childStart + text5.length) == text5)
        return to;
    }
  }
  return -1;
}
function replaceNodes(nodes, from2, to, view, replacement) {
  let result = [];
  for (let i = 0, off = 0; i < nodes.length; i++) {
    let child = nodes[i], start = off, end = off += child.size;
    if (start >= to || end <= from2) {
      result.push(child);
    } else {
      if (start < from2)
        result.push(child.slice(0, from2 - start, view));
      if (replacement) {
        result.push(replacement);
        replacement = void 0;
      }
      if (end > to)
        result.push(child.slice(to - start, child.size, view));
    }
  }
  return result;
}
function selectionFromDOM(view, origin = null) {
  let domSel = view.domSelectionRange(), doc3 = view.state.doc;
  if (!domSel.focusNode)
    return null;
  let nearestDesc = view.docView.nearestDesc(domSel.focusNode), inWidget = nearestDesc && nearestDesc.size == 0;
  let head = view.docView.posFromDOM(domSel.focusNode, domSel.focusOffset, 1);
  if (head < 0)
    return null;
  let $head = doc3.resolve(head), anchor, selection;
  if (selectionCollapsed(domSel)) {
    anchor = head;
    while (nearestDesc && !nearestDesc.node)
      nearestDesc = nearestDesc.parent;
    let nearestDescNode = nearestDesc.node;
    if (nearestDesc && nearestDescNode.isAtom && NodeSelection.isSelectable(nearestDescNode) && nearestDesc.parent && !(nearestDescNode.isInline && isOnEdge(domSel.focusNode, domSel.focusOffset, nearestDesc.dom))) {
      let pos = nearestDesc.posBefore;
      selection = new NodeSelection(head == pos ? $head : doc3.resolve(pos));
    }
  } else {
    if (domSel instanceof view.dom.ownerDocument.defaultView.Selection && domSel.rangeCount > 1) {
      let min = head, max = head;
      for (let i = 0; i < domSel.rangeCount; i++) {
        let range = domSel.getRangeAt(i);
        min = Math.min(min, view.docView.posFromDOM(range.startContainer, range.startOffset, 1));
        max = Math.max(max, view.docView.posFromDOM(range.endContainer, range.endOffset, -1));
      }
      if (min < 0)
        return null;
      [anchor, head] = max == view.state.selection.anchor ? [max, min] : [min, max];
      $head = doc3.resolve(head);
    } else {
      anchor = view.docView.posFromDOM(domSel.anchorNode, domSel.anchorOffset, 1);
    }
    if (anchor < 0)
      return null;
  }
  let $anchor = doc3.resolve(anchor);
  if (!selection) {
    let bias = origin == "pointer" || view.state.selection.head < $head.pos && !inWidget ? 1 : -1;
    selection = selectionBetween(view, $anchor, $head, bias);
  }
  return selection;
}
function editorOwnsSelection(view) {
  return view.editable ? view.hasFocus() : hasSelection(view) && document.activeElement && document.activeElement.contains(view.dom);
}
function selectionToDOM(view, force = false) {
  let sel = view.state.selection;
  syncNodeSelection(view, sel);
  if (!editorOwnsSelection(view))
    return;
  if (!force && view.input.mouseDown && view.input.mouseDown.allowDefault && chrome) {
    let domSel = view.domSelectionRange(), curSel = view.domObserver.currentSelection;
    if (domSel.anchorNode && curSel.anchorNode && isEquivalentPosition(domSel.anchorNode, domSel.anchorOffset, curSel.anchorNode, curSel.anchorOffset)) {
      view.input.mouseDown.delayedSelectionSync = true;
      view.domObserver.setCurSelection();
      return;
    }
  }
  view.domObserver.disconnectSelection();
  if (view.cursorWrapper) {
    selectCursorWrapper(view);
  } else {
    let { anchor, head } = sel, resetEditableFrom, resetEditableTo;
    if (brokenSelectBetweenUneditable && !(sel instanceof TextSelection)) {
      if (!sel.$from.parent.inlineContent)
        resetEditableFrom = temporarilyEditableNear(view, sel.from);
      if (!sel.empty && !sel.$from.parent.inlineContent)
        resetEditableTo = temporarilyEditableNear(view, sel.to);
    }
    view.docView.setSelection(anchor, head, view, force);
    if (brokenSelectBetweenUneditable) {
      if (resetEditableFrom)
        resetEditable(resetEditableFrom);
      if (resetEditableTo)
        resetEditable(resetEditableTo);
    }
    if (sel.visible) {
      view.dom.classList.remove("ProseMirror-hideselection");
    } else {
      view.dom.classList.add("ProseMirror-hideselection");
      if ("onselectionchange" in document)
        removeClassOnSelectionChange(view);
    }
  }
  view.domObserver.setCurSelection();
  view.domObserver.connectSelection();
}
var brokenSelectBetweenUneditable = safari || chrome && chrome_version < 63;
function temporarilyEditableNear(view, pos) {
  let { node, offset } = view.docView.domFromPos(pos, 0);
  let after = offset < node.childNodes.length ? node.childNodes[offset] : null;
  let before = offset ? node.childNodes[offset - 1] : null;
  if (safari && after && after.contentEditable == "false")
    return setEditable(after);
  if ((!after || after.contentEditable == "false") && (!before || before.contentEditable == "false")) {
    if (after)
      return setEditable(after);
    else if (before)
      return setEditable(before);
  }
}
function setEditable(element) {
  element.contentEditable = "true";
  if (safari && element.draggable) {
    element.draggable = false;
    element.wasDraggable = true;
  }
  return element;
}
function resetEditable(element) {
  element.contentEditable = "false";
  if (element.wasDraggable) {
    element.draggable = true;
    element.wasDraggable = null;
  }
}
function removeClassOnSelectionChange(view) {
  let doc3 = view.dom.ownerDocument;
  doc3.removeEventListener("selectionchange", view.input.hideSelectionGuard);
  let domSel = view.domSelectionRange();
  let node = domSel.anchorNode, offset = domSel.anchorOffset;
  doc3.addEventListener("selectionchange", view.input.hideSelectionGuard = () => {
    if (domSel.anchorNode != node || domSel.anchorOffset != offset) {
      doc3.removeEventListener("selectionchange", view.input.hideSelectionGuard);
      setTimeout(() => {
        if (!editorOwnsSelection(view) || view.state.selection.visible)
          view.dom.classList.remove("ProseMirror-hideselection");
      }, 20);
    }
  });
}
function selectCursorWrapper(view) {
  let domSel = view.domSelection();
  if (!domSel)
    return;
  let node = view.cursorWrapper.dom, img = node.nodeName == "IMG";
  if (img)
    domSel.collapse(node.parentNode, domIndex(node) + 1);
  else
    domSel.collapse(node, 0);
  if (!img && !view.state.selection.visible && ie && ie_version <= 11) {
    node.disabled = true;
    node.disabled = false;
  }
}
function syncNodeSelection(view, sel) {
  if (sel instanceof NodeSelection) {
    let desc = view.docView.descAt(sel.from);
    if (desc != view.lastSelectedViewDesc) {
      clearNodeSelection(view);
      if (desc)
        desc.selectNode();
      view.lastSelectedViewDesc = desc;
    }
  } else {
    clearNodeSelection(view);
  }
}
function clearNodeSelection(view) {
  if (view.lastSelectedViewDesc) {
    if (view.lastSelectedViewDesc.parent)
      view.lastSelectedViewDesc.deselectNode();
    view.lastSelectedViewDesc = void 0;
  }
}
function selectionBetween(view, $anchor, $head, bias) {
  return view.someProp("createSelectionBetween", (f) => f(view, $anchor, $head)) || TextSelection.between($anchor, $head, bias);
}
function hasFocusAndSelection(view) {
  if (view.editable && !view.hasFocus())
    return false;
  return hasSelection(view);
}
function hasSelection(view) {
  let sel = view.domSelectionRange();
  if (!sel.anchorNode)
    return false;
  try {
    return view.dom.contains(sel.anchorNode.nodeType == 3 ? sel.anchorNode.parentNode : sel.anchorNode) && (view.editable || view.dom.contains(sel.focusNode.nodeType == 3 ? sel.focusNode.parentNode : sel.focusNode));
  } catch (_10) {
    return false;
  }
}
function anchorInRightPlace(view) {
  let anchorDOM = view.docView.domFromPos(view.state.selection.anchor, 0);
  let domSel = view.domSelectionRange();
  return isEquivalentPosition(anchorDOM.node, anchorDOM.offset, domSel.anchorNode, domSel.anchorOffset);
}
function moveSelectionBlock(state, dir) {
  let { $anchor, $head } = state.selection;
  let $side = dir > 0 ? $anchor.max($head) : $anchor.min($head);
  let $start = !$side.parent.inlineContent ? $side : $side.depth ? state.doc.resolve(dir > 0 ? $side.after() : $side.before()) : null;
  return $start && Selection.findFrom($start, dir);
}
function apply(view, sel) {
  view.dispatch(view.state.tr.setSelection(sel).scrollIntoView());
  return true;
}
function selectHorizontally(view, dir, mods) {
  let sel = view.state.selection;
  if (sel instanceof TextSelection) {
    if (mods.indexOf("s") > -1) {
      let { $head } = sel, node = $head.textOffset ? null : dir < 0 ? $head.nodeBefore : $head.nodeAfter;
      if (!node || node.isText || !node.isLeaf)
        return false;
      let $newHead = view.state.doc.resolve($head.pos + node.nodeSize * (dir < 0 ? -1 : 1));
      return apply(view, new TextSelection(sel.$anchor, $newHead));
    } else if (!sel.empty) {
      return false;
    } else if (view.endOfTextblock(dir > 0 ? "forward" : "backward")) {
      let next = moveSelectionBlock(view.state, dir);
      if (next && next instanceof NodeSelection)
        return apply(view, next);
      return false;
    } else if (!(mac2 && mods.indexOf("m") > -1)) {
      let $head = sel.$head, node = $head.textOffset ? null : dir < 0 ? $head.nodeBefore : $head.nodeAfter, desc;
      if (!node || node.isText)
        return false;
      let nodePos = dir < 0 ? $head.pos - node.nodeSize : $head.pos;
      if (!(node.isAtom || (desc = view.docView.descAt(nodePos)) && !desc.contentDOM))
        return false;
      if (NodeSelection.isSelectable(node)) {
        return apply(view, new NodeSelection(dir < 0 ? view.state.doc.resolve($head.pos - node.nodeSize) : $head));
      } else if (webkit) {
        return apply(view, new TextSelection(view.state.doc.resolve(dir < 0 ? nodePos : nodePos + node.nodeSize)));
      } else {
        return false;
      }
    }
  } else if (sel instanceof NodeSelection && sel.node.isInline) {
    return apply(view, new TextSelection(dir > 0 ? sel.$to : sel.$from));
  } else {
    let next = moveSelectionBlock(view.state, dir);
    if (next)
      return apply(view, next);
    return false;
  }
}
function nodeLen(node) {
  return node.nodeType == 3 ? node.nodeValue.length : node.childNodes.length;
}
function isIgnorable(dom, dir) {
  let desc = dom.pmViewDesc;
  return desc && desc.size == 0 && (dir < 0 || dom.nextSibling || dom.nodeName != "BR");
}
function skipIgnoredNodes(view, dir) {
  return dir < 0 ? skipIgnoredNodesBefore(view) : skipIgnoredNodesAfter(view);
}
function skipIgnoredNodesBefore(view) {
  let sel = view.domSelectionRange();
  let node = sel.focusNode, offset = sel.focusOffset;
  if (!node)
    return;
  let moveNode, moveOffset, force = false;
  if (gecko && node.nodeType == 1 && offset < nodeLen(node) && isIgnorable(node.childNodes[offset], -1))
    force = true;
  for (; ; ) {
    if (offset > 0) {
      if (node.nodeType != 1) {
        break;
      } else {
        let before = node.childNodes[offset - 1];
        if (isIgnorable(before, -1)) {
          moveNode = node;
          moveOffset = --offset;
        } else if (before.nodeType == 3) {
          node = before;
          offset = node.nodeValue.length;
        } else
          break;
      }
    } else if (isBlockNode(node)) {
      break;
    } else {
      let prev = node.previousSibling;
      while (prev && isIgnorable(prev, -1)) {
        moveNode = node.parentNode;
        moveOffset = domIndex(prev);
        prev = prev.previousSibling;
      }
      if (!prev) {
        node = node.parentNode;
        if (node == view.dom)
          break;
        offset = 0;
      } else {
        node = prev;
        offset = nodeLen(node);
      }
    }
  }
  if (force)
    setSelFocus(view, node, offset);
  else if (moveNode)
    setSelFocus(view, moveNode, moveOffset);
}
function skipIgnoredNodesAfter(view) {
  let sel = view.domSelectionRange();
  let node = sel.focusNode, offset = sel.focusOffset;
  if (!node)
    return;
  let len = nodeLen(node);
  let moveNode, moveOffset;
  for (; ; ) {
    if (offset < len) {
      if (node.nodeType != 1)
        break;
      let after = node.childNodes[offset];
      if (isIgnorable(after, 1)) {
        moveNode = node;
        moveOffset = ++offset;
      } else
        break;
    } else if (isBlockNode(node)) {
      break;
    } else {
      let next = node.nextSibling;
      while (next && isIgnorable(next, 1)) {
        moveNode = next.parentNode;
        moveOffset = domIndex(next) + 1;
        next = next.nextSibling;
      }
      if (!next) {
        node = node.parentNode;
        if (node == view.dom)
          break;
        offset = len = 0;
      } else {
        node = next;
        offset = 0;
        len = nodeLen(node);
      }
    }
  }
  if (moveNode)
    setSelFocus(view, moveNode, moveOffset);
}
function isBlockNode(dom) {
  let desc = dom.pmViewDesc;
  return desc && desc.node && desc.node.isBlock;
}
function textNodeAfter(node, offset) {
  while (node && offset == node.childNodes.length && !hasBlockDesc(node)) {
    offset = domIndex(node) + 1;
    node = node.parentNode;
  }
  while (node && offset < node.childNodes.length) {
    let next = node.childNodes[offset];
    if (next.nodeType == 3)
      return next;
    if (next.nodeType == 1 && next.contentEditable == "false")
      break;
    node = next;
    offset = 0;
  }
}
function textNodeBefore(node, offset) {
  while (node && !offset && !hasBlockDesc(node)) {
    offset = domIndex(node);
    node = node.parentNode;
  }
  while (node && offset) {
    let next = node.childNodes[offset - 1];
    if (next.nodeType == 3)
      return next;
    if (next.nodeType == 1 && next.contentEditable == "false")
      break;
    node = next;
    offset = node.childNodes.length;
  }
}
function setSelFocus(view, node, offset) {
  if (node.nodeType != 3) {
    let before, after;
    if (after = textNodeAfter(node, offset)) {
      node = after;
      offset = 0;
    } else if (before = textNodeBefore(node, offset)) {
      node = before;
      offset = before.nodeValue.length;
    }
  }
  let sel = view.domSelection();
  if (!sel)
    return;
  if (selectionCollapsed(sel)) {
    let range = document.createRange();
    range.setEnd(node, offset);
    range.setStart(node, offset);
    sel.removeAllRanges();
    sel.addRange(range);
  } else if (sel.extend) {
    sel.extend(node, offset);
  }
  view.domObserver.setCurSelection();
  let { state } = view;
  setTimeout(() => {
    if (view.state == state)
      selectionToDOM(view);
  }, 50);
}
function findDirection(view, pos) {
  let $pos = view.state.doc.resolve(pos);
  if (!(chrome || windows) && $pos.parent.inlineContent) {
    let coords = view.coordsAtPos(pos);
    if (pos > $pos.start()) {
      let before = view.coordsAtPos(pos - 1);
      let mid = (before.top + before.bottom) / 2;
      if (mid > coords.top && mid < coords.bottom && Math.abs(before.left - coords.left) > 1)
        return before.left < coords.left ? "ltr" : "rtl";
    }
    if (pos < $pos.end()) {
      let after = view.coordsAtPos(pos + 1);
      let mid = (after.top + after.bottom) / 2;
      if (mid > coords.top && mid < coords.bottom && Math.abs(after.left - coords.left) > 1)
        return after.left > coords.left ? "ltr" : "rtl";
    }
  }
  let computed = getComputedStyle(view.dom).direction;
  return computed == "rtl" ? "rtl" : "ltr";
}
function selectVertically(view, dir, mods) {
  let sel = view.state.selection;
  if (sel instanceof TextSelection && !sel.empty || mods.indexOf("s") > -1)
    return false;
  if (mac2 && mods.indexOf("m") > -1)
    return false;
  let { $from, $to } = sel;
  if (!$from.parent.inlineContent || view.endOfTextblock(dir < 0 ? "up" : "down")) {
    let next = moveSelectionBlock(view.state, dir);
    if (next && next instanceof NodeSelection)
      return apply(view, next);
  }
  if (!$from.parent.inlineContent) {
    let side = dir < 0 ? $from : $to;
    let beyond = sel instanceof AllSelection ? Selection.near(side, dir) : Selection.findFrom(side, dir);
    return beyond ? apply(view, beyond) : false;
  }
  return false;
}
function stopNativeHorizontalDelete(view, dir) {
  if (!(view.state.selection instanceof TextSelection))
    return true;
  let { $head, $anchor, empty: empty2 } = view.state.selection;
  if (!$head.sameParent($anchor))
    return true;
  if (!empty2)
    return false;
  if (view.endOfTextblock(dir > 0 ? "forward" : "backward"))
    return true;
  let nextNode = !$head.textOffset && (dir < 0 ? $head.nodeBefore : $head.nodeAfter);
  if (nextNode && !nextNode.isText) {
    let tr2 = view.state.tr;
    if (dir < 0)
      tr2.delete($head.pos - nextNode.nodeSize, $head.pos);
    else
      tr2.delete($head.pos, $head.pos + nextNode.nodeSize);
    view.dispatch(tr2);
    return true;
  }
  return false;
}
function switchEditable(view, node, state) {
  view.domObserver.stop();
  node.contentEditable = state;
  view.domObserver.start();
}
function safariDownArrowBug(view) {
  if (!safari || view.state.selection.$head.parentOffset > 0)
    return false;
  let { focusNode, focusOffset } = view.domSelectionRange();
  if (focusNode && focusNode.nodeType == 1 && focusOffset == 0 && focusNode.firstChild && focusNode.firstChild.contentEditable == "false") {
    let child = focusNode.firstChild;
    switchEditable(view, child, "true");
    setTimeout(() => switchEditable(view, child, "false"), 20);
  }
  return false;
}
function getMods(event) {
  let result = "";
  if (event.ctrlKey)
    result += "c";
  if (event.metaKey)
    result += "m";
  if (event.altKey)
    result += "a";
  if (event.shiftKey)
    result += "s";
  return result;
}
function captureKeyDown(view, event) {
  let code = event.keyCode, mods = getMods(event);
  if (code == 8 || mac2 && code == 72 && mods == "c") {
    return stopNativeHorizontalDelete(view, -1) || skipIgnoredNodes(view, -1);
  } else if (code == 46 && !event.shiftKey || mac2 && code == 68 && mods == "c") {
    return stopNativeHorizontalDelete(view, 1) || skipIgnoredNodes(view, 1);
  } else if (code == 13 || code == 27) {
    return true;
  } else if (code == 37 || mac2 && code == 66 && mods == "c") {
    let dir = code == 37 ? findDirection(view, view.state.selection.from) == "ltr" ? -1 : 1 : -1;
    return selectHorizontally(view, dir, mods) || skipIgnoredNodes(view, dir);
  } else if (code == 39 || mac2 && code == 70 && mods == "c") {
    let dir = code == 39 ? findDirection(view, view.state.selection.from) == "ltr" ? 1 : -1 : 1;
    return selectHorizontally(view, dir, mods) || skipIgnoredNodes(view, dir);
  } else if (code == 38 || mac2 && code == 80 && mods == "c") {
    return selectVertically(view, -1, mods) || skipIgnoredNodes(view, -1);
  } else if (code == 40 || mac2 && code == 78 && mods == "c") {
    return safariDownArrowBug(view) || selectVertically(view, 1, mods) || skipIgnoredNodes(view, 1);
  } else if (mods == (mac2 ? "m" : "c") && (code == 66 || code == 73 || code == 89 || code == 90)) {
    return true;
  }
  return false;
}
function serializeForClipboard(view, slice2) {
  view.someProp("transformCopied", (f) => {
    slice2 = f(slice2, view);
  });
  let context = [], { content, openStart, openEnd } = slice2;
  while (openStart > 1 && openEnd > 1 && content.childCount == 1 && content.firstChild.childCount == 1) {
    openStart--;
    openEnd--;
    let node = content.firstChild;
    context.push(node.type.name, node.attrs != node.type.defaultAttrs ? node.attrs : null);
    content = node.content;
  }
  let serializer = view.someProp("clipboardSerializer") || DOMSerializer.fromSchema(view.state.schema);
  let doc3 = detachedDoc(), wrap2 = doc3.createElement("div");
  wrap2.appendChild(serializer.serializeFragment(content, { document: doc3 }));
  let firstChild = wrap2.firstChild, needsWrap, wrappers = 0;
  while (firstChild && firstChild.nodeType == 1 && (needsWrap = wrapMap[firstChild.nodeName.toLowerCase()])) {
    for (let i = needsWrap.length - 1; i >= 0; i--) {
      let wrapper = doc3.createElement(needsWrap[i]);
      while (wrap2.firstChild)
        wrapper.appendChild(wrap2.firstChild);
      wrap2.appendChild(wrapper);
      wrappers++;
    }
    firstChild = wrap2.firstChild;
  }
  if (firstChild && firstChild.nodeType == 1)
    firstChild.setAttribute("data-pm-slice", `${openStart} ${openEnd}${wrappers ? ` -${wrappers}` : ""} ${JSON.stringify(context)}`);
  let text5 = view.someProp("clipboardTextSerializer", (f) => f(slice2, view)) || slice2.content.textBetween(0, slice2.content.size, "\n\n");
  return { dom: wrap2, text: text5, slice: slice2 };
}
function parseFromClipboard(view, text5, html, plainText, $context) {
  let inCode = $context.parent.type.spec.code;
  let dom, slice2;
  if (!html && !text5)
    return null;
  let asText = !!text5 && (plainText || inCode || !html);
  if (asText) {
    view.someProp("transformPastedText", (f) => {
      text5 = f(text5, inCode || plainText, view);
    });
    if (inCode) {
      slice2 = new Slice(Fragment.from(view.state.schema.text(text5.replace(/\r\n?/g, "\n"))), 0, 0);
      view.someProp("transformPasted", (f) => {
        slice2 = f(slice2, view, true);
      });
      return slice2;
    }
    let parsed = view.someProp("clipboardTextParser", (f) => f(text5, $context, plainText, view));
    if (parsed) {
      slice2 = parsed;
    } else {
      let marks = $context.marks();
      let { schema } = view.state, serializer = DOMSerializer.fromSchema(schema);
      dom = document.createElement("div");
      text5.split(/(?:\r\n?|\n)+/).forEach((block) => {
        let p2 = dom.appendChild(document.createElement("p"));
        if (block)
          p2.appendChild(serializer.serializeNode(schema.text(block, marks)));
      });
    }
  } else {
    view.someProp("transformPastedHTML", (f) => {
      html = f(html, view);
    });
    dom = readHTML(html);
    if (webkit)
      restoreReplacedSpaces(dom);
  }
  let contextNode = dom && dom.querySelector("[data-pm-slice]");
  let sliceData = contextNode && /^(\d+) (\d+)(?: -(\d+))? (.*)/.exec(contextNode.getAttribute("data-pm-slice") || "");
  if (sliceData && sliceData[3])
    for (let i = +sliceData[3]; i > 0; i--) {
      let child = dom.firstChild;
      while (child && child.nodeType != 1)
        child = child.nextSibling;
      if (!child)
        break;
      dom = child;
    }
  if (!slice2) {
    let parser = view.someProp("clipboardParser") || view.someProp("domParser") || DOMParser2.fromSchema(view.state.schema);
    slice2 = parser.parseSlice(dom, {
      preserveWhitespace: !!(asText || sliceData),
      context: $context,
      ruleFromNode(dom2) {
        if (dom2.nodeName == "BR" && !dom2.nextSibling && dom2.parentNode && !inlineParents.test(dom2.parentNode.nodeName))
          return { ignore: true };
        return null;
      }
    });
  }
  if (sliceData) {
    slice2 = addContext(closeSlice(slice2, +sliceData[1], +sliceData[2]), sliceData[4]);
  } else {
    slice2 = Slice.maxOpen(normalizeSiblings(slice2.content, $context), true);
    if (slice2.openStart || slice2.openEnd) {
      let openStart = 0, openEnd = 0;
      for (let node = slice2.content.firstChild; openStart < slice2.openStart && !node.type.spec.isolating; openStart++, node = node.firstChild) {
      }
      for (let node = slice2.content.lastChild; openEnd < slice2.openEnd && !node.type.spec.isolating; openEnd++, node = node.lastChild) {
      }
      slice2 = closeSlice(slice2, openStart, openEnd);
    }
  }
  view.someProp("transformPasted", (f) => {
    slice2 = f(slice2, view, asText);
  });
  return slice2;
}
var inlineParents = /^(a|abbr|acronym|b|cite|code|del|em|i|ins|kbd|label|output|q|ruby|s|samp|span|strong|sub|sup|time|u|tt|var)$/i;
function normalizeSiblings(fragment, $context) {
  if (fragment.childCount < 2)
    return fragment;
  for (let d2 = $context.depth; d2 >= 0; d2--) {
    let parent = $context.node(d2);
    let match = parent.contentMatchAt($context.index(d2));
    let lastWrap, result = [];
    fragment.forEach((node) => {
      if (!result)
        return;
      let wrap2 = match.findWrapping(node.type), inLast;
      if (!wrap2)
        return result = null;
      if (inLast = result.length && lastWrap.length && addToSibling(wrap2, lastWrap, node, result[result.length - 1], 0)) {
        result[result.length - 1] = inLast;
      } else {
        if (result.length)
          result[result.length - 1] = closeRight(result[result.length - 1], lastWrap.length);
        let wrapped = withWrappers(node, wrap2);
        result.push(wrapped);
        match = match.matchType(wrapped.type);
        lastWrap = wrap2;
      }
    });
    if (result)
      return Fragment.from(result);
  }
  return fragment;
}
function withWrappers(node, wrap2, from2 = 0) {
  for (let i = wrap2.length - 1; i >= from2; i--)
    node = wrap2[i].create(null, Fragment.from(node));
  return node;
}
function addToSibling(wrap2, lastWrap, node, sibling, depth) {
  if (depth < wrap2.length && depth < lastWrap.length && wrap2[depth] == lastWrap[depth]) {
    let inner2 = addToSibling(wrap2, lastWrap, node, sibling.lastChild, depth + 1);
    if (inner2)
      return sibling.copy(sibling.content.replaceChild(sibling.childCount - 1, inner2));
    let match = sibling.contentMatchAt(sibling.childCount);
    if (match.matchType(depth == wrap2.length - 1 ? node.type : wrap2[depth + 1]))
      return sibling.copy(sibling.content.append(Fragment.from(withWrappers(node, wrap2, depth + 1))));
  }
}
function closeRight(node, depth) {
  if (depth == 0)
    return node;
  let fragment = node.content.replaceChild(node.childCount - 1, closeRight(node.lastChild, depth - 1));
  let fill = node.contentMatchAt(node.childCount).fillBefore(Fragment.empty, true);
  return node.copy(fragment.append(fill));
}
function closeRange(fragment, side, from2, to, depth, openEnd) {
  let node = side < 0 ? fragment.firstChild : fragment.lastChild, inner2 = node.content;
  if (fragment.childCount > 1)
    openEnd = 0;
  if (depth < to - 1)
    inner2 = closeRange(inner2, side, from2, to, depth + 1, openEnd);
  if (depth >= from2)
    inner2 = side < 0 ? node.contentMatchAt(0).fillBefore(inner2, openEnd <= depth).append(inner2) : inner2.append(node.contentMatchAt(node.childCount).fillBefore(Fragment.empty, true));
  return fragment.replaceChild(side < 0 ? 0 : fragment.childCount - 1, node.copy(inner2));
}
function closeSlice(slice2, openStart, openEnd) {
  if (openStart < slice2.openStart)
    slice2 = new Slice(closeRange(slice2.content, -1, openStart, slice2.openStart, 0, slice2.openEnd), openStart, slice2.openEnd);
  if (openEnd < slice2.openEnd)
    slice2 = new Slice(closeRange(slice2.content, 1, openEnd, slice2.openEnd, 0, 0), slice2.openStart, openEnd);
  return slice2;
}
var wrapMap = {
  thead: ["table"],
  tbody: ["table"],
  tfoot: ["table"],
  caption: ["table"],
  colgroup: ["table"],
  col: ["table", "colgroup"],
  tr: ["table", "tbody"],
  td: ["table", "tbody", "tr"],
  th: ["table", "tbody", "tr"]
};
var _detachedDoc = null;
function detachedDoc() {
  return _detachedDoc || (_detachedDoc = document.implementation.createHTMLDocument("title"));
}
var _policy = null;
function maybeWrapTrusted(html) {
  let trustedTypes = window.trustedTypes;
  if (!trustedTypes)
    return html;
  if (!_policy)
    _policy = trustedTypes.defaultPolicy || trustedTypes.createPolicy("ProseMirrorClipboard", { createHTML: (s) => s });
  return _policy.createHTML(html);
}
function readHTML(html) {
  let metas = /^(\s*<meta [^>]*>)*/.exec(html);
  if (metas)
    html = html.slice(metas[0].length);
  let elt = detachedDoc().createElement("div");
  let firstTag = /<([a-z][^>\s]+)/i.exec(html), wrap2;
  if (wrap2 = firstTag && wrapMap[firstTag[1].toLowerCase()])
    html = wrap2.map((n) => "<" + n + ">").join("") + html + wrap2.map((n) => "</" + n + ">").reverse().join("");
  elt.innerHTML = maybeWrapTrusted(html);
  if (wrap2)
    for (let i = 0; i < wrap2.length; i++)
      elt = elt.querySelector(wrap2[i]) || elt;
  return elt;
}
function restoreReplacedSpaces(dom) {
  let nodes = dom.querySelectorAll(chrome ? "span:not([class]):not([style])" : "span.Apple-converted-space");
  for (let i = 0; i < nodes.length; i++) {
    let node = nodes[i];
    if (node.childNodes.length == 1 && node.textContent == "\xA0" && node.parentNode)
      node.parentNode.replaceChild(dom.ownerDocument.createTextNode(" "), node);
  }
}
function addContext(slice2, context) {
  if (!slice2.size)
    return slice2;
  let schema = slice2.content.firstChild.type.schema, array;
  try {
    array = JSON.parse(context);
  } catch (e) {
    return slice2;
  }
  let { content, openStart, openEnd } = slice2;
  for (let i = array.length - 2; i >= 0; i -= 2) {
    let type = schema.nodes[array[i]];
    if (!type || type.hasRequiredAttrs())
      break;
    content = Fragment.from(type.create(array[i + 1], content));
    openStart++;
    openEnd++;
  }
  return new Slice(content, openStart, openEnd);
}
var handlers = {};
var editHandlers = {};
var passiveHandlers = { touchstart: true, touchmove: true };
var InputState = class {
  constructor() {
    this.shiftKey = false;
    this.mouseDown = null;
    this.lastKeyCode = null;
    this.lastKeyCodeTime = 0;
    this.lastClick = { time: 0, x: 0, y: 0, type: "", button: 0 };
    this.lastSelectionOrigin = null;
    this.lastSelectionTime = 0;
    this.lastIOSEnter = 0;
    this.lastIOSEnterFallbackTimeout = -1;
    this.lastFocus = 0;
    this.lastTouch = 0;
    this.lastChromeDelete = 0;
    this.composing = false;
    this.compositionNode = null;
    this.composingTimeout = -1;
    this.compositionNodes = [];
    this.compositionEndedAt = -2e8;
    this.compositionID = 1;
    this.badSafariComposition = false;
    this.compositionPendingChanges = 0;
    this.domChangeCount = 0;
    this.eventHandlers = /* @__PURE__ */ Object.create(null);
    this.hideSelectionGuard = null;
  }
};
function initInput(view) {
  for (let event in handlers) {
    let handler = handlers[event];
    view.dom.addEventListener(event, view.input.eventHandlers[event] = (event2) => {
      if (eventBelongsToView(view, event2) && !runCustomHandler(view, event2) && (view.editable || !(event2.type in editHandlers)))
        handler(view, event2);
    }, passiveHandlers[event] ? { passive: true } : void 0);
  }
  if (safari)
    view.dom.addEventListener("input", () => null);
  ensureListeners(view);
}
function setSelectionOrigin(view, origin) {
  view.input.lastSelectionOrigin = origin;
  view.input.lastSelectionTime = Date.now();
}
function destroyInput(view) {
  view.domObserver.stop();
  for (let type in view.input.eventHandlers)
    view.dom.removeEventListener(type, view.input.eventHandlers[type]);
  clearTimeout(view.input.composingTimeout);
  clearTimeout(view.input.lastIOSEnterFallbackTimeout);
}
function ensureListeners(view) {
  view.someProp("handleDOMEvents", (currentHandlers) => {
    for (let type in currentHandlers)
      if (!view.input.eventHandlers[type])
        view.dom.addEventListener(type, view.input.eventHandlers[type] = (event) => runCustomHandler(view, event));
  });
}
function runCustomHandler(view, event) {
  return view.someProp("handleDOMEvents", (handlers2) => {
    let handler = handlers2[event.type];
    return handler ? handler(view, event) || event.defaultPrevented : false;
  });
}
function eventBelongsToView(view, event) {
  if (!event.bubbles)
    return true;
  if (event.defaultPrevented)
    return false;
  for (let node = event.target; node != view.dom; node = node.parentNode)
    if (!node || node.nodeType == 11 || node.pmViewDesc && node.pmViewDesc.stopEvent(event))
      return false;
  return true;
}
function dispatchEvent(view, event) {
  if (!runCustomHandler(view, event) && handlers[event.type] && (view.editable || !(event.type in editHandlers)))
    handlers[event.type](view, event);
}
editHandlers.keydown = (view, _event) => {
  let event = _event;
  view.input.shiftKey = event.keyCode == 16 || event.shiftKey;
  if (inOrNearComposition(view, event))
    return;
  view.input.lastKeyCode = event.keyCode;
  view.input.lastKeyCodeTime = Date.now();
  if (android && chrome && event.keyCode == 13)
    return;
  if (event.keyCode != 229)
    view.domObserver.forceFlush();
  if (ios && event.keyCode == 13 && !event.ctrlKey && !event.altKey && !event.metaKey) {
    let now = Date.now();
    view.input.lastIOSEnter = now;
    view.input.lastIOSEnterFallbackTimeout = setTimeout(() => {
      if (view.input.lastIOSEnter == now) {
        view.someProp("handleKeyDown", (f) => f(view, keyEvent(13, "Enter")));
        view.input.lastIOSEnter = 0;
      }
    }, 200);
  } else if (view.someProp("handleKeyDown", (f) => f(view, event)) || captureKeyDown(view, event)) {
    event.preventDefault();
  } else {
    setSelectionOrigin(view, "key");
  }
};
editHandlers.keyup = (view, event) => {
  if (event.keyCode == 16)
    view.input.shiftKey = false;
};
editHandlers.keypress = (view, _event) => {
  let event = _event;
  if (inOrNearComposition(view, event) || !event.charCode || event.ctrlKey && !event.altKey || mac2 && event.metaKey)
    return;
  if (view.someProp("handleKeyPress", (f) => f(view, event))) {
    event.preventDefault();
    return;
  }
  let sel = view.state.selection;
  if (!(sel instanceof TextSelection) || !sel.$from.sameParent(sel.$to)) {
    let text5 = String.fromCharCode(event.charCode);
    let deflt3 = () => view.state.tr.insertText(text5).scrollIntoView();
    if (!/[\r\n]/.test(text5) && !view.someProp("handleTextInput", (f) => f(view, sel.$from.pos, sel.$to.pos, text5, deflt3)))
      view.dispatch(deflt3());
    event.preventDefault();
  }
};
function eventCoords(event) {
  return { left: event.clientX, top: event.clientY };
}
function isNear(event, click) {
  let dx = click.x - event.clientX, dy = click.y - event.clientY;
  return dx * dx + dy * dy < 100;
}
function runHandlerOnContext(view, propName, pos, inside, event) {
  if (inside == -1)
    return false;
  let $pos = view.state.doc.resolve(inside);
  for (let i = $pos.depth + 1; i > 0; i--) {
    if (view.someProp(propName, (f) => i > $pos.depth ? f(view, pos, $pos.nodeAfter, $pos.before(i), event, true) : f(view, pos, $pos.node(i), $pos.before(i), event, false)))
      return true;
  }
  return false;
}
function updateSelection(view, selection, origin) {
  if (!view.focused)
    view.focus();
  if (view.state.selection.eq(selection))
    return;
  let tr2 = view.state.tr.setSelection(selection);
  if (origin == "pointer")
    tr2.setMeta("pointer", true);
  view.dispatch(tr2);
}
function selectClickedLeaf(view, inside) {
  if (inside == -1)
    return false;
  let $pos = view.state.doc.resolve(inside), node = $pos.nodeAfter;
  if (node && node.isAtom && NodeSelection.isSelectable(node)) {
    updateSelection(view, new NodeSelection($pos), "pointer");
    return true;
  }
  return false;
}
function selectClickedNode(view, inside) {
  if (inside == -1)
    return false;
  let sel = view.state.selection, selectedNode, selectAt;
  if (sel instanceof NodeSelection)
    selectedNode = sel.node;
  let $pos = view.state.doc.resolve(inside);
  for (let i = $pos.depth + 1; i > 0; i--) {
    let node = i > $pos.depth ? $pos.nodeAfter : $pos.node(i);
    if (NodeSelection.isSelectable(node)) {
      if (selectedNode && sel.$from.depth > 0 && i >= sel.$from.depth && $pos.before(sel.$from.depth + 1) == sel.$from.pos)
        selectAt = $pos.before(sel.$from.depth);
      else
        selectAt = $pos.before(i);
      break;
    }
  }
  if (selectAt != null) {
    updateSelection(view, NodeSelection.create(view.state.doc, selectAt), "pointer");
    return true;
  } else {
    return false;
  }
}
function handleSingleClick(view, pos, inside, event, selectNode) {
  return runHandlerOnContext(view, "handleClickOn", pos, inside, event) || view.someProp("handleClick", (f) => f(view, pos, event)) || (selectNode ? selectClickedNode(view, inside) : selectClickedLeaf(view, inside));
}
function handleDoubleClick(view, pos, inside, event) {
  return runHandlerOnContext(view, "handleDoubleClickOn", pos, inside, event) || view.someProp("handleDoubleClick", (f) => f(view, pos, event));
}
function handleTripleClick(view, pos, inside, event) {
  return runHandlerOnContext(view, "handleTripleClickOn", pos, inside, event) || view.someProp("handleTripleClick", (f) => f(view, pos, event)) || defaultTripleClick(view, inside, event);
}
function defaultTripleClick(view, inside, event) {
  if (event.button != 0)
    return false;
  let doc3 = view.state.doc;
  if (inside == -1) {
    if (doc3.inlineContent) {
      updateSelection(view, TextSelection.create(doc3, 0, doc3.content.size), "pointer");
      return true;
    }
    return false;
  }
  let $pos = doc3.resolve(inside);
  for (let i = $pos.depth + 1; i > 0; i--) {
    let node = i > $pos.depth ? $pos.nodeAfter : $pos.node(i);
    let nodePos = $pos.before(i);
    if (node.inlineContent)
      updateSelection(view, TextSelection.create(doc3, nodePos + 1, nodePos + 1 + node.content.size), "pointer");
    else if (NodeSelection.isSelectable(node))
      updateSelection(view, NodeSelection.create(doc3, nodePos), "pointer");
    else
      continue;
    return true;
  }
}
function forceDOMFlush(view) {
  return endComposition(view);
}
var selectNodeModifier = mac2 ? "metaKey" : "ctrlKey";
handlers.mousedown = (view, _event) => {
  let event = _event;
  view.input.shiftKey = event.shiftKey;
  let flushed = forceDOMFlush(view);
  let now = Date.now(), type = "singleClick";
  if (now - view.input.lastClick.time < 500 && isNear(event, view.input.lastClick) && !event[selectNodeModifier] && view.input.lastClick.button == event.button) {
    if (view.input.lastClick.type == "singleClick")
      type = "doubleClick";
    else if (view.input.lastClick.type == "doubleClick")
      type = "tripleClick";
  }
  view.input.lastClick = { time: now, x: event.clientX, y: event.clientY, type, button: event.button };
  let pos = view.posAtCoords(eventCoords(event));
  if (!pos)
    return;
  if (type == "singleClick") {
    if (view.input.mouseDown)
      view.input.mouseDown.done();
    view.input.mouseDown = new MouseDown(view, pos, event, !!flushed);
  } else if ((type == "doubleClick" ? handleDoubleClick : handleTripleClick)(view, pos.pos, pos.inside, event)) {
    event.preventDefault();
  } else {
    setSelectionOrigin(view, "pointer");
  }
};
var MouseDown = class {
  constructor(view, pos, event, flushed) {
    this.view = view;
    this.pos = pos;
    this.event = event;
    this.flushed = flushed;
    this.delayedSelectionSync = false;
    this.mightDrag = null;
    this.startDoc = view.state.doc;
    this.selectNode = !!event[selectNodeModifier];
    this.allowDefault = event.shiftKey;
    let targetNode, targetPos;
    if (pos.inside > -1) {
      targetNode = view.state.doc.nodeAt(pos.inside);
      targetPos = pos.inside;
    } else {
      let $pos = view.state.doc.resolve(pos.pos);
      targetNode = $pos.parent;
      targetPos = $pos.depth ? $pos.before() : 0;
    }
    const target2 = flushed ? null : event.target;
    const targetDesc = target2 ? view.docView.nearestDesc(target2, true) : null;
    this.target = targetDesc && targetDesc.nodeDOM.nodeType == 1 ? targetDesc.nodeDOM : null;
    let { selection } = view.state;
    if (event.button == 0 && targetNode.type.spec.draggable && targetNode.type.spec.selectable !== false || selection instanceof NodeSelection && selection.from <= targetPos && selection.to > targetPos)
      this.mightDrag = {
        node: targetNode,
        pos: targetPos,
        addAttr: !!(this.target && !this.target.draggable),
        setUneditable: !!(this.target && gecko && !this.target.hasAttribute("contentEditable"))
      };
    if (this.target && this.mightDrag && (this.mightDrag.addAttr || this.mightDrag.setUneditable)) {
      this.view.domObserver.stop();
      if (this.mightDrag.addAttr)
        this.target.draggable = true;
      if (this.mightDrag.setUneditable)
        setTimeout(() => {
          if (this.view.input.mouseDown == this)
            this.target.setAttribute("contentEditable", "false");
        }, 20);
      this.view.domObserver.start();
    }
    view.root.addEventListener("mouseup", this.up = this.up.bind(this));
    view.root.addEventListener("mousemove", this.move = this.move.bind(this));
    setSelectionOrigin(view, "pointer");
  }
  done() {
    this.view.root.removeEventListener("mouseup", this.up);
    this.view.root.removeEventListener("mousemove", this.move);
    if (this.mightDrag && this.target) {
      this.view.domObserver.stop();
      if (this.mightDrag.addAttr)
        this.target.removeAttribute("draggable");
      if (this.mightDrag.setUneditable)
        this.target.removeAttribute("contentEditable");
      this.view.domObserver.start();
    }
    if (this.delayedSelectionSync)
      setTimeout(() => selectionToDOM(this.view));
    this.view.input.mouseDown = null;
  }
  up(event) {
    this.done();
    if (!this.view.dom.contains(event.target))
      return;
    let pos = this.pos;
    if (this.view.state.doc != this.startDoc)
      pos = this.view.posAtCoords(eventCoords(event));
    this.updateAllowDefault(event);
    if (this.allowDefault || !pos) {
      setSelectionOrigin(this.view, "pointer");
    } else if (handleSingleClick(this.view, pos.pos, pos.inside, event, this.selectNode)) {
      event.preventDefault();
    } else if (event.button == 0 && (this.flushed || // Safari ignores clicks on draggable elements
    safari && this.mightDrag && !this.mightDrag.node.isAtom || // Chrome will sometimes treat a node selection as a
    // cursor, but still report that the node is selected
    // when asked through getSelection. You'll then get a
    // situation where clicking at the point where that
    // (hidden) cursor is doesn't change the selection, and
    // thus doesn't get a reaction from ProseMirror. This
    // works around that.
    chrome && !this.view.state.selection.visible && Math.min(Math.abs(pos.pos - this.view.state.selection.from), Math.abs(pos.pos - this.view.state.selection.to)) <= 2)) {
      updateSelection(this.view, Selection.near(this.view.state.doc.resolve(pos.pos)), "pointer");
      event.preventDefault();
    } else {
      setSelectionOrigin(this.view, "pointer");
    }
  }
  move(event) {
    this.updateAllowDefault(event);
    setSelectionOrigin(this.view, "pointer");
    if (event.buttons == 0)
      this.done();
  }
  updateAllowDefault(event) {
    if (!this.allowDefault && (Math.abs(this.event.x - event.clientX) > 4 || Math.abs(this.event.y - event.clientY) > 4))
      this.allowDefault = true;
  }
};
handlers.touchstart = (view) => {
  view.input.lastTouch = Date.now();
  forceDOMFlush(view);
  setSelectionOrigin(view, "pointer");
};
handlers.touchmove = (view) => {
  view.input.lastTouch = Date.now();
  setSelectionOrigin(view, "pointer");
};
handlers.contextmenu = (view) => forceDOMFlush(view);
function inOrNearComposition(view, event) {
  if (view.composing)
    return true;
  if (safari && Math.abs(event.timeStamp - view.input.compositionEndedAt) < 500) {
    view.input.compositionEndedAt = -2e8;
    return true;
  }
  return false;
}
var timeoutComposition = android ? 5e3 : -1;
editHandlers.compositionstart = editHandlers.compositionupdate = (view) => {
  if (!view.composing) {
    view.domObserver.flush();
    let { state } = view, $pos = state.selection.$to;
    if (state.selection instanceof TextSelection && (state.storedMarks || !$pos.textOffset && $pos.parentOffset && $pos.nodeBefore.marks.some((m) => m.type.spec.inclusive === false) || chrome && windows && selectionBeforeUneditable(view))) {
      view.markCursor = view.state.storedMarks || $pos.marks();
      endComposition(view, true);
      view.markCursor = null;
    } else {
      endComposition(view, !state.selection.empty);
      if (gecko && state.selection.empty && $pos.parentOffset && !$pos.textOffset && $pos.nodeBefore.marks.length) {
        let sel = view.domSelectionRange();
        for (let node = sel.focusNode, offset = sel.focusOffset; node && node.nodeType == 1 && offset != 0; ) {
          let before = offset < 0 ? node.lastChild : node.childNodes[offset - 1];
          if (!before)
            break;
          if (before.nodeType == 3) {
            let sel2 = view.domSelection();
            if (sel2)
              sel2.collapse(before, before.nodeValue.length);
            break;
          } else {
            node = before;
            offset = -1;
          }
        }
      }
    }
    view.input.composing = true;
  }
  scheduleComposeEnd(view, timeoutComposition);
};
function selectionBeforeUneditable(view) {
  let { focusNode, focusOffset } = view.domSelectionRange();
  if (!focusNode || focusNode.nodeType != 1 || focusOffset >= focusNode.childNodes.length)
    return false;
  let next = focusNode.childNodes[focusOffset];
  return next.nodeType == 1 && next.contentEditable == "false";
}
editHandlers.compositionend = (view, event) => {
  if (view.composing) {
    view.input.composing = false;
    view.input.compositionEndedAt = event.timeStamp;
    view.input.compositionPendingChanges = view.domObserver.pendingRecords().length ? view.input.compositionID : 0;
    view.input.compositionNode = null;
    if (view.input.badSafariComposition)
      view.domObserver.forceFlush();
    else if (view.input.compositionPendingChanges)
      Promise.resolve().then(() => view.domObserver.flush());
    view.input.compositionID++;
    scheduleComposeEnd(view, 20);
  }
};
function scheduleComposeEnd(view, delay) {
  clearTimeout(view.input.composingTimeout);
  if (delay > -1)
    view.input.composingTimeout = setTimeout(() => endComposition(view), delay);
}
function clearComposition(view) {
  if (view.composing) {
    view.input.composing = false;
    view.input.compositionEndedAt = timestampFromCustomEvent();
  }
  while (view.input.compositionNodes.length > 0)
    view.input.compositionNodes.pop().markParentsDirty();
}
function findCompositionNode(view) {
  let sel = view.domSelectionRange();
  if (!sel.focusNode)
    return null;
  let textBefore = textNodeBefore$1(sel.focusNode, sel.focusOffset);
  let textAfter = textNodeAfter$1(sel.focusNode, sel.focusOffset);
  if (textBefore && textAfter && textBefore != textAfter) {
    let descAfter = textAfter.pmViewDesc, lastChanged = view.domObserver.lastChangedTextNode;
    if (textBefore == lastChanged || textAfter == lastChanged)
      return lastChanged;
    if (!descAfter || !descAfter.isText(textAfter.nodeValue)) {
      return textAfter;
    } else if (view.input.compositionNode == textAfter) {
      let descBefore = textBefore.pmViewDesc;
      if (!(!descBefore || !descBefore.isText(textBefore.nodeValue)))
        return textAfter;
    }
  }
  return textBefore || textAfter;
}
function timestampFromCustomEvent() {
  let event = document.createEvent("Event");
  event.initEvent("event", true, true);
  return event.timeStamp;
}
function endComposition(view, restarting = false) {
  if (android && view.domObserver.flushingSoon >= 0)
    return;
  view.domObserver.forceFlush();
  clearComposition(view);
  if (restarting || view.docView && view.docView.dirty) {
    let sel = selectionFromDOM(view), cur = view.state.selection;
    if (sel && !sel.eq(cur))
      view.dispatch(view.state.tr.setSelection(sel));
    else if ((view.markCursor || restarting) && !cur.$from.node(cur.$from.sharedDepth(cur.to)).inlineContent)
      view.dispatch(view.state.tr.deleteSelection());
    else
      view.updateState(view.state);
    return true;
  }
  return false;
}
function captureCopy(view, dom) {
  if (!view.dom.parentNode)
    return;
  let wrap2 = view.dom.parentNode.appendChild(document.createElement("div"));
  wrap2.appendChild(dom);
  wrap2.style.cssText = "position: fixed; left: -10000px; top: 10px";
  let sel = getSelection(), range = document.createRange();
  range.selectNodeContents(dom);
  view.dom.blur();
  sel.removeAllRanges();
  sel.addRange(range);
  setTimeout(() => {
    if (wrap2.parentNode)
      wrap2.parentNode.removeChild(wrap2);
    view.focus();
  }, 50);
}
var brokenClipboardAPI = ie && ie_version < 15 || ios && webkit_version < 604;
handlers.copy = editHandlers.cut = (view, _event) => {
  let event = _event;
  let sel = view.state.selection, cut2 = event.type == "cut";
  if (sel.empty)
    return;
  let data = brokenClipboardAPI ? null : event.clipboardData;
  let slice2 = sel.content(), { dom, text: text5 } = serializeForClipboard(view, slice2);
  if (data) {
    event.preventDefault();
    data.clearData();
    data.setData("text/html", dom.innerHTML);
    data.setData("text/plain", text5);
  } else {
    captureCopy(view, dom);
  }
  if (cut2)
    view.dispatch(view.state.tr.deleteSelection().scrollIntoView().setMeta("uiEvent", "cut"));
};
function sliceSingleNode(slice2) {
  return slice2.openStart == 0 && slice2.openEnd == 0 && slice2.content.childCount == 1 ? slice2.content.firstChild : null;
}
function capturePaste(view, event) {
  if (!view.dom.parentNode)
    return;
  let plainText = view.input.shiftKey || view.state.selection.$from.parent.type.spec.code;
  let target2 = view.dom.parentNode.appendChild(document.createElement(plainText ? "textarea" : "div"));
  if (!plainText)
    target2.contentEditable = "true";
  target2.style.cssText = "position: fixed; left: -10000px; top: 10px";
  target2.focus();
  let plain = view.input.shiftKey && view.input.lastKeyCode != 45;
  setTimeout(() => {
    view.focus();
    if (target2.parentNode)
      target2.parentNode.removeChild(target2);
    if (plainText)
      doPaste(view, target2.value, null, plain, event);
    else
      doPaste(view, target2.textContent, target2.innerHTML, plain, event);
  }, 50);
}
function doPaste(view, text5, html, preferPlain, event) {
  let slice2 = parseFromClipboard(view, text5, html, preferPlain, view.state.selection.$from);
  if (view.someProp("handlePaste", (f) => f(view, event, slice2 || Slice.empty)))
    return true;
  if (!slice2)
    return false;
  let singleNode = sliceSingleNode(slice2);
  let tr2 = singleNode ? view.state.tr.replaceSelectionWith(singleNode, preferPlain) : view.state.tr.replaceSelection(slice2);
  view.dispatch(tr2.scrollIntoView().setMeta("paste", true).setMeta("uiEvent", "paste"));
  return true;
}
function getText(clipboardData) {
  let text5 = clipboardData.getData("text/plain") || clipboardData.getData("Text");
  if (text5)
    return text5;
  let uris = clipboardData.getData("text/uri-list");
  return uris ? uris.replace(/\r?\n/g, " ") : "";
}
editHandlers.paste = (view, _event) => {
  let event = _event;
  if (view.composing && !android)
    return;
  let data = brokenClipboardAPI ? null : event.clipboardData;
  let plain = view.input.shiftKey && view.input.lastKeyCode != 45;
  if (data && doPaste(view, getText(data), data.getData("text/html"), plain, event))
    event.preventDefault();
  else
    capturePaste(view, event);
};
var Dragging = class {
  constructor(slice2, move, node) {
    this.slice = slice2;
    this.move = move;
    this.node = node;
  }
};
var dragCopyModifier = mac2 ? "altKey" : "ctrlKey";
function dragMoves(view, event) {
  let moves = view.someProp("dragCopies", (test) => !test(event));
  return moves != null ? moves : !event[dragCopyModifier];
}
handlers.dragstart = (view, _event) => {
  let event = _event;
  let mouseDown = view.input.mouseDown;
  if (mouseDown)
    mouseDown.done();
  if (!event.dataTransfer)
    return;
  let sel = view.state.selection;
  let pos = sel.empty ? null : view.posAtCoords(eventCoords(event));
  let node;
  if (pos && pos.pos >= sel.from && pos.pos <= (sel instanceof NodeSelection ? sel.to - 1 : sel.to)) ;
  else if (mouseDown && mouseDown.mightDrag) {
    node = NodeSelection.create(view.state.doc, mouseDown.mightDrag.pos);
  } else if (event.target && event.target.nodeType == 1) {
    let desc = view.docView.nearestDesc(event.target, true);
    if (desc && desc.node.type.spec.draggable && desc != view.docView)
      node = NodeSelection.create(view.state.doc, desc.posBefore);
  }
  let draggedSlice = (node || view.state.selection).content();
  let { dom, text: text5, slice: slice2 } = serializeForClipboard(view, draggedSlice);
  if (!event.dataTransfer.files.length || !chrome || chrome_version > 120)
    event.dataTransfer.clearData();
  event.dataTransfer.setData(brokenClipboardAPI ? "Text" : "text/html", dom.innerHTML);
  event.dataTransfer.effectAllowed = "copyMove";
  if (!brokenClipboardAPI)
    event.dataTransfer.setData("text/plain", text5);
  view.dragging = new Dragging(slice2, dragMoves(view, event), node);
};
handlers.dragend = (view) => {
  let dragging = view.dragging;
  window.setTimeout(() => {
    if (view.dragging == dragging)
      view.dragging = null;
  }, 50);
};
editHandlers.dragover = editHandlers.dragenter = (_10, e) => e.preventDefault();
editHandlers.drop = (view, event) => {
  try {
    handleDrop(view, event, view.dragging);
  } finally {
    view.dragging = null;
  }
};
function handleDrop(view, event, dragging) {
  if (!event.dataTransfer)
    return;
  let eventPos = view.posAtCoords(eventCoords(event));
  if (!eventPos)
    return;
  let $mouse = view.state.doc.resolve(eventPos.pos);
  let slice2 = dragging && dragging.slice;
  if (slice2) {
    view.someProp("transformPasted", (f) => {
      slice2 = f(slice2, view, false);
    });
  } else {
    slice2 = parseFromClipboard(view, getText(event.dataTransfer), brokenClipboardAPI ? null : event.dataTransfer.getData("text/html"), false, $mouse);
  }
  let move = !!(dragging && dragMoves(view, event));
  if (view.someProp("handleDrop", (f) => f(view, event, slice2 || Slice.empty, move))) {
    event.preventDefault();
    return;
  }
  if (!slice2)
    return;
  event.preventDefault();
  let insertPos = slice2 ? dropPoint(view.state.doc, $mouse.pos, slice2) : $mouse.pos;
  if (insertPos == null)
    insertPos = $mouse.pos;
  let tr2 = view.state.tr;
  if (move) {
    let { node } = dragging;
    if (node)
      node.replace(tr2);
    else
      tr2.deleteSelection();
  }
  let pos = tr2.mapping.map(insertPos);
  let isNode = slice2.openStart == 0 && slice2.openEnd == 0 && slice2.content.childCount == 1;
  let beforeInsert = tr2.doc;
  if (isNode)
    tr2.replaceRangeWith(pos, pos, slice2.content.firstChild);
  else
    tr2.replaceRange(pos, pos, slice2);
  if (tr2.doc.eq(beforeInsert))
    return;
  let $pos = tr2.doc.resolve(pos);
  if (isNode && NodeSelection.isSelectable(slice2.content.firstChild) && $pos.nodeAfter && $pos.nodeAfter.sameMarkup(slice2.content.firstChild)) {
    tr2.setSelection(new NodeSelection($pos));
  } else {
    let end = tr2.mapping.map(insertPos);
    tr2.mapping.maps[tr2.mapping.maps.length - 1].forEach((_from, _to, _newFrom, newTo) => end = newTo);
    tr2.setSelection(selectionBetween(view, $pos, tr2.doc.resolve(end)));
  }
  view.focus();
  view.dispatch(tr2.setMeta("uiEvent", "drop"));
}
handlers.focus = (view) => {
  view.input.lastFocus = Date.now();
  if (!view.focused) {
    view.domObserver.stop();
    view.dom.classList.add("ProseMirror-focused");
    view.domObserver.start();
    view.focused = true;
    setTimeout(() => {
      if (view.docView && view.hasFocus() && !view.domObserver.currentSelection.eq(view.domSelectionRange()))
        selectionToDOM(view);
    }, 20);
  }
};
handlers.blur = (view, _event) => {
  let event = _event;
  if (view.focused) {
    view.domObserver.stop();
    view.dom.classList.remove("ProseMirror-focused");
    view.domObserver.start();
    if (event.relatedTarget && view.dom.contains(event.relatedTarget))
      view.domObserver.currentSelection.clear();
    view.focused = false;
  }
};
handlers.beforeinput = (view, _event) => {
  let event = _event;
  if (chrome && android && event.inputType == "deleteContentBackward") {
    view.domObserver.flushSoon();
    let { domChangeCount } = view.input;
    setTimeout(() => {
      if (view.input.domChangeCount != domChangeCount)
        return;
      view.dom.blur();
      view.focus();
      if (view.someProp("handleKeyDown", (f) => f(view, keyEvent(8, "Backspace"))))
        return;
      let { $cursor } = view.state.selection;
      if ($cursor && $cursor.pos > 0)
        view.dispatch(view.state.tr.delete($cursor.pos - 1, $cursor.pos).scrollIntoView());
    }, 50);
  }
};
for (let prop in editHandlers)
  handlers[prop] = editHandlers[prop];
function compareObjs(a2, b2) {
  if (a2 == b2)
    return true;
  for (let p2 in a2)
    if (a2[p2] !== b2[p2])
      return false;
  for (let p2 in b2)
    if (!(p2 in a2))
      return false;
  return true;
}
var WidgetType = class _WidgetType {
  constructor(toDOM, spec) {
    this.toDOM = toDOM;
    this.spec = spec || noSpec;
    this.side = this.spec.side || 0;
  }
  map(mapping, span, offset, oldOffset) {
    let { pos, deleted } = mapping.mapResult(span.from + oldOffset, this.side < 0 ? -1 : 1);
    return deleted ? null : new Decoration(pos - offset, pos - offset, this);
  }
  valid() {
    return true;
  }
  eq(other) {
    return this == other || other instanceof _WidgetType && (this.spec.key && this.spec.key == other.spec.key || this.toDOM == other.toDOM && compareObjs(this.spec, other.spec));
  }
  destroy(node) {
    if (this.spec.destroy)
      this.spec.destroy(node);
  }
};
var InlineType = class _InlineType {
  constructor(attrs, spec) {
    this.attrs = attrs;
    this.spec = spec || noSpec;
  }
  map(mapping, span, offset, oldOffset) {
    let from2 = mapping.map(span.from + oldOffset, this.spec.inclusiveStart ? -1 : 1) - offset;
    let to = mapping.map(span.to + oldOffset, this.spec.inclusiveEnd ? 1 : -1) - offset;
    return from2 >= to ? null : new Decoration(from2, to, this);
  }
  valid(_10, span) {
    return span.from < span.to;
  }
  eq(other) {
    return this == other || other instanceof _InlineType && compareObjs(this.attrs, other.attrs) && compareObjs(this.spec, other.spec);
  }
  static is(span) {
    return span.type instanceof _InlineType;
  }
  destroy() {
  }
};
var NodeType2 = class _NodeType {
  constructor(attrs, spec) {
    this.attrs = attrs;
    this.spec = spec || noSpec;
  }
  map(mapping, span, offset, oldOffset) {
    let from2 = mapping.mapResult(span.from + oldOffset, 1);
    if (from2.deleted)
      return null;
    let to = mapping.mapResult(span.to + oldOffset, -1);
    if (to.deleted || to.pos <= from2.pos)
      return null;
    return new Decoration(from2.pos - offset, to.pos - offset, this);
  }
  valid(node, span) {
    let { index, offset } = node.content.findIndex(span.from), child;
    return offset == span.from && !(child = node.child(index)).isText && offset + child.nodeSize == span.to;
  }
  eq(other) {
    return this == other || other instanceof _NodeType && compareObjs(this.attrs, other.attrs) && compareObjs(this.spec, other.spec);
  }
  destroy() {
  }
};
var Decoration = class _Decoration {
  /**
  @internal
  */
  constructor(from2, to, type) {
    this.from = from2;
    this.to = to;
    this.type = type;
  }
  /**
  @internal
  */
  copy(from2, to) {
    return new _Decoration(from2, to, this.type);
  }
  /**
  @internal
  */
  eq(other, offset = 0) {
    return this.type.eq(other.type) && this.from + offset == other.from && this.to + offset == other.to;
  }
  /**
  @internal
  */
  map(mapping, offset, oldOffset) {
    return this.type.map(mapping, this, offset, oldOffset);
  }
  /**
  Creates a widget decoration, which is a DOM node that's shown in
  the document at the given position. It is recommended that you
  delay rendering the widget by passing a function that will be
  called when the widget is actually drawn in a view, but you can
  also directly pass a DOM node. `getPos` can be used to find the
  widget's current document position.
  */
  static widget(pos, toDOM, spec) {
    return new _Decoration(pos, pos, new WidgetType(toDOM, spec));
  }
  /**
  Creates an inline decoration, which adds the given attributes to
  each inline node between `from` and `to`.
  */
  static inline(from2, to, attrs, spec) {
    return new _Decoration(from2, to, new InlineType(attrs, spec));
  }
  /**
  Creates a node decoration. `from` and `to` should point precisely
  before and after a node in the document. That node, and only that
  node, will receive the given attributes.
  */
  static node(from2, to, attrs, spec) {
    return new _Decoration(from2, to, new NodeType2(attrs, spec));
  }
  /**
  The spec provided when creating this decoration. Can be useful
  if you've stored extra information in that object.
  */
  get spec() {
    return this.type.spec;
  }
  /**
  @internal
  */
  get inline() {
    return this.type instanceof InlineType;
  }
  /**
  @internal
  */
  get widget() {
    return this.type instanceof WidgetType;
  }
};
var none = [];
var noSpec = {};
var DecorationSet = class _DecorationSet {
  /**
  @internal
  */
  constructor(local, children) {
    this.local = local.length ? local : none;
    this.children = children.length ? children : none;
  }
  /**
  Create a set of decorations, using the structure of the given
  document. This will consume (modify) the `decorations` array, so
  you must make a copy if you want need to preserve that.
  */
  static create(doc3, decorations) {
    return decorations.length ? buildTree(decorations, doc3, 0, noSpec) : empty;
  }
  /**
  Find all decorations in this set which touch the given range
  (including decorations that start or end directly at the
  boundaries) and match the given predicate on their spec. When
  `start` and `end` are omitted, all decorations in the set are
  considered. When `predicate` isn't given, all decorations are
  assumed to match.
  */
  find(start, end, predicate) {
    let result = [];
    this.findInner(start == null ? 0 : start, end == null ? 1e9 : end, result, 0, predicate);
    return result;
  }
  findInner(start, end, result, offset, predicate) {
    for (let i = 0; i < this.local.length; i++) {
      let span = this.local[i];
      if (span.from <= end && span.to >= start && (!predicate || predicate(span.spec)))
        result.push(span.copy(span.from + offset, span.to + offset));
    }
    for (let i = 0; i < this.children.length; i += 3) {
      if (this.children[i] < end && this.children[i + 1] > start) {
        let childOff = this.children[i] + 1;
        this.children[i + 2].findInner(start - childOff, end - childOff, result, offset + childOff, predicate);
      }
    }
  }
  /**
  Map the set of decorations in response to a change in the
  document.
  */
  map(mapping, doc3, options) {
    if (this == empty || mapping.maps.length == 0)
      return this;
    return this.mapInner(mapping, doc3, 0, 0, options || noSpec);
  }
  /**
  @internal
  */
  mapInner(mapping, node, offset, oldOffset, options) {
    let newLocal;
    for (let i = 0; i < this.local.length; i++) {
      let mapped = this.local[i].map(mapping, offset, oldOffset);
      if (mapped && mapped.type.valid(node, mapped))
        (newLocal || (newLocal = [])).push(mapped);
      else if (options.onRemove)
        options.onRemove(this.local[i].spec);
    }
    if (this.children.length)
      return mapChildren(this.children, newLocal || [], mapping, node, offset, oldOffset, options);
    else
      return newLocal ? new _DecorationSet(newLocal.sort(byPos), none) : empty;
  }
  /**
  Add the given array of decorations to the ones in the set,
  producing a new set. Consumes the `decorations` array. Needs
  access to the current document to create the appropriate tree
  structure.
  */
  add(doc3, decorations) {
    if (!decorations.length)
      return this;
    if (this == empty)
      return _DecorationSet.create(doc3, decorations);
    return this.addInner(doc3, decorations, 0);
  }
  addInner(doc3, decorations, offset) {
    let children, childIndex = 0;
    doc3.forEach((childNode, childOffset) => {
      let baseOffset = childOffset + offset, found2;
      if (!(found2 = takeSpansForNode(decorations, childNode, baseOffset)))
        return;
      if (!children)
        children = this.children.slice();
      while (childIndex < children.length && children[childIndex] < childOffset)
        childIndex += 3;
      if (children[childIndex] == childOffset)
        children[childIndex + 2] = children[childIndex + 2].addInner(childNode, found2, baseOffset + 1);
      else
        children.splice(childIndex, 0, childOffset, childOffset + childNode.nodeSize, buildTree(found2, childNode, baseOffset + 1, noSpec));
      childIndex += 3;
    });
    let local = moveSpans(childIndex ? withoutNulls(decorations) : decorations, -offset);
    for (let i = 0; i < local.length; i++)
      if (!local[i].type.valid(doc3, local[i]))
        local.splice(i--, 1);
    return new _DecorationSet(local.length ? this.local.concat(local).sort(byPos) : this.local, children || this.children);
  }
  /**
  Create a new set that contains the decorations in this set, minus
  the ones in the given array.
  */
  remove(decorations) {
    if (decorations.length == 0 || this == empty)
      return this;
    return this.removeInner(decorations, 0);
  }
  removeInner(decorations, offset) {
    let children = this.children, local = this.local;
    for (let i = 0; i < children.length; i += 3) {
      let found2;
      let from2 = children[i] + offset, to = children[i + 1] + offset;
      for (let j = 0, span; j < decorations.length; j++)
        if (span = decorations[j]) {
          if (span.from > from2 && span.to < to) {
            decorations[j] = null;
            (found2 || (found2 = [])).push(span);
          }
        }
      if (!found2)
        continue;
      if (children == this.children)
        children = this.children.slice();
      let removed = children[i + 2].removeInner(found2, from2 + 1);
      if (removed != empty) {
        children[i + 2] = removed;
      } else {
        children.splice(i, 3);
        i -= 3;
      }
    }
    if (local.length) {
      for (let i = 0, span; i < decorations.length; i++)
        if (span = decorations[i]) {
          for (let j = 0; j < local.length; j++)
            if (local[j].eq(span, offset)) {
              if (local == this.local)
                local = this.local.slice();
              local.splice(j--, 1);
            }
        }
    }
    if (children == this.children && local == this.local)
      return this;
    return local.length || children.length ? new _DecorationSet(local, children) : empty;
  }
  forChild(offset, node) {
    if (this == empty)
      return this;
    if (node.isLeaf)
      return _DecorationSet.empty;
    let child, local;
    for (let i = 0; i < this.children.length; i += 3)
      if (this.children[i] >= offset) {
        if (this.children[i] == offset)
          child = this.children[i + 2];
        break;
      }
    let start = offset + 1, end = start + node.content.size;
    for (let i = 0; i < this.local.length; i++) {
      let dec = this.local[i];
      if (dec.from < end && dec.to > start && dec.type instanceof InlineType) {
        let from2 = Math.max(start, dec.from) - start, to = Math.min(end, dec.to) - start;
        if (from2 < to)
          (local || (local = [])).push(dec.copy(from2, to));
      }
    }
    if (local) {
      let localSet = new _DecorationSet(local.sort(byPos), none);
      return child ? new DecorationGroup([localSet, child]) : localSet;
    }
    return child || empty;
  }
  /**
  @internal
  */
  eq(other) {
    if (this == other)
      return true;
    if (!(other instanceof _DecorationSet) || this.local.length != other.local.length || this.children.length != other.children.length)
      return false;
    for (let i = 0; i < this.local.length; i++)
      if (!this.local[i].eq(other.local[i]))
        return false;
    for (let i = 0; i < this.children.length; i += 3)
      if (this.children[i] != other.children[i] || this.children[i + 1] != other.children[i + 1] || !this.children[i + 2].eq(other.children[i + 2]))
        return false;
    return true;
  }
  /**
  @internal
  */
  locals(node) {
    return removeOverlap(this.localsInner(node));
  }
  /**
  @internal
  */
  localsInner(node) {
    if (this == empty)
      return none;
    if (node.inlineContent || !this.local.some(InlineType.is))
      return this.local;
    let result = [];
    for (let i = 0; i < this.local.length; i++) {
      if (!(this.local[i].type instanceof InlineType))
        result.push(this.local[i]);
    }
    return result;
  }
  forEachSet(f) {
    f(this);
  }
};
DecorationSet.empty = new DecorationSet([], []);
DecorationSet.removeOverlap = removeOverlap;
var empty = DecorationSet.empty;
var DecorationGroup = class _DecorationGroup {
  constructor(members) {
    this.members = members;
  }
  map(mapping, doc3) {
    const mappedDecos = this.members.map((member) => member.map(mapping, doc3, noSpec));
    return _DecorationGroup.from(mappedDecos);
  }
  forChild(offset, child) {
    if (child.isLeaf)
      return DecorationSet.empty;
    let found2 = [];
    for (let i = 0; i < this.members.length; i++) {
      let result = this.members[i].forChild(offset, child);
      if (result == empty)
        continue;
      if (result instanceof _DecorationGroup)
        found2 = found2.concat(result.members);
      else
        found2.push(result);
    }
    return _DecorationGroup.from(found2);
  }
  eq(other) {
    if (!(other instanceof _DecorationGroup) || other.members.length != this.members.length)
      return false;
    for (let i = 0; i < this.members.length; i++)
      if (!this.members[i].eq(other.members[i]))
        return false;
    return true;
  }
  locals(node) {
    let result, sorted = true;
    for (let i = 0; i < this.members.length; i++) {
      let locals = this.members[i].localsInner(node);
      if (!locals.length)
        continue;
      if (!result) {
        result = locals;
      } else {
        if (sorted) {
          result = result.slice();
          sorted = false;
        }
        for (let j = 0; j < locals.length; j++)
          result.push(locals[j]);
      }
    }
    return result ? removeOverlap(sorted ? result : result.sort(byPos)) : none;
  }
  // Create a group for the given array of decoration sets, or return
  // a single set when possible.
  static from(members) {
    switch (members.length) {
      case 0:
        return empty;
      case 1:
        return members[0];
      default:
        return new _DecorationGroup(members.every((m) => m instanceof DecorationSet) ? members : members.reduce((r2, m) => r2.concat(m instanceof DecorationSet ? m : m.members), []));
    }
  }
  forEachSet(f) {
    for (let i = 0; i < this.members.length; i++)
      this.members[i].forEachSet(f);
  }
};
function mapChildren(oldChildren, newLocal, mapping, node, offset, oldOffset, options) {
  let children = oldChildren.slice();
  for (let i = 0, baseOffset = oldOffset; i < mapping.maps.length; i++) {
    let moved = 0;
    mapping.maps[i].forEach((oldStart, oldEnd, newStart, newEnd) => {
      let dSize = newEnd - newStart - (oldEnd - oldStart);
      for (let i2 = 0; i2 < children.length; i2 += 3) {
        let end = children[i2 + 1];
        if (end < 0 || oldStart > end + baseOffset - moved)
          continue;
        let start = children[i2] + baseOffset - moved;
        if (oldEnd >= start) {
          children[i2 + 1] = oldStart <= start ? -2 : -1;
        } else if (oldStart >= baseOffset && dSize) {
          children[i2] += dSize;
          children[i2 + 1] += dSize;
        }
      }
      moved += dSize;
    });
    baseOffset = mapping.maps[i].map(baseOffset, -1);
  }
  let mustRebuild = false;
  for (let i = 0; i < children.length; i += 3)
    if (children[i + 1] < 0) {
      if (children[i + 1] == -2) {
        mustRebuild = true;
        children[i + 1] = -1;
        continue;
      }
      let from2 = mapping.map(oldChildren[i] + oldOffset), fromLocal = from2 - offset;
      if (fromLocal < 0 || fromLocal >= node.content.size) {
        mustRebuild = true;
        continue;
      }
      let to = mapping.map(oldChildren[i + 1] + oldOffset, -1), toLocal = to - offset;
      let { index, offset: childOffset } = node.content.findIndex(fromLocal);
      let childNode = node.maybeChild(index);
      if (childNode && childOffset == fromLocal && childOffset + childNode.nodeSize == toLocal) {
        let mapped = children[i + 2].mapInner(mapping, childNode, from2 + 1, oldChildren[i] + oldOffset + 1, options);
        if (mapped != empty) {
          children[i] = fromLocal;
          children[i + 1] = toLocal;
          children[i + 2] = mapped;
        } else {
          children[i + 1] = -2;
          mustRebuild = true;
        }
      } else {
        mustRebuild = true;
      }
    }
  if (mustRebuild) {
    let decorations = mapAndGatherRemainingDecorations(children, oldChildren, newLocal, mapping, offset, oldOffset, options);
    let built = buildTree(decorations, node, 0, options);
    newLocal = built.local;
    for (let i = 0; i < children.length; i += 3)
      if (children[i + 1] < 0) {
        children.splice(i, 3);
        i -= 3;
      }
    for (let i = 0, j = 0; i < built.children.length; i += 3) {
      let from2 = built.children[i];
      while (j < children.length && children[j] < from2)
        j += 3;
      children.splice(j, 0, built.children[i], built.children[i + 1], built.children[i + 2]);
    }
  }
  return new DecorationSet(newLocal.sort(byPos), children);
}
function moveSpans(spans, offset) {
  if (!offset || !spans.length)
    return spans;
  let result = [];
  for (let i = 0; i < spans.length; i++) {
    let span = spans[i];
    result.push(new Decoration(span.from + offset, span.to + offset, span.type));
  }
  return result;
}
function mapAndGatherRemainingDecorations(children, oldChildren, decorations, mapping, offset, oldOffset, options) {
  function gather(set, oldOffset2) {
    for (let i = 0; i < set.local.length; i++) {
      let mapped = set.local[i].map(mapping, offset, oldOffset2);
      if (mapped)
        decorations.push(mapped);
      else if (options.onRemove)
        options.onRemove(set.local[i].spec);
    }
    for (let i = 0; i < set.children.length; i += 3)
      gather(set.children[i + 2], set.children[i] + oldOffset2 + 1);
  }
  for (let i = 0; i < children.length; i += 3)
    if (children[i + 1] == -1)
      gather(children[i + 2], oldChildren[i] + oldOffset + 1);
  return decorations;
}
function takeSpansForNode(spans, node, offset) {
  if (node.isLeaf)
    return null;
  let end = offset + node.nodeSize, found2 = null;
  for (let i = 0, span; i < spans.length; i++) {
    if ((span = spans[i]) && span.from > offset && span.to < end) {
      (found2 || (found2 = [])).push(span);
      spans[i] = null;
    }
  }
  return found2;
}
function withoutNulls(array) {
  let result = [];
  for (let i = 0; i < array.length; i++)
    if (array[i] != null)
      result.push(array[i]);
  return result;
}
function buildTree(spans, node, offset, options) {
  let children = [], hasNulls = false;
  node.forEach((childNode, localStart) => {
    let found2 = takeSpansForNode(spans, childNode, localStart + offset);
    if (found2) {
      hasNulls = true;
      let subtree = buildTree(found2, childNode, offset + localStart + 1, options);
      if (subtree != empty)
        children.push(localStart, localStart + childNode.nodeSize, subtree);
    }
  });
  let locals = moveSpans(hasNulls ? withoutNulls(spans) : spans, -offset).sort(byPos);
  for (let i = 0; i < locals.length; i++)
    if (!locals[i].type.valid(node, locals[i])) {
      if (options.onRemove)
        options.onRemove(locals[i].spec);
      locals.splice(i--, 1);
    }
  return locals.length || children.length ? new DecorationSet(locals, children) : empty;
}
function byPos(a2, b2) {
  return a2.from - b2.from || a2.to - b2.to;
}
function removeOverlap(spans) {
  let working = spans;
  for (let i = 0; i < working.length - 1; i++) {
    let span = working[i];
    if (span.from != span.to)
      for (let j = i + 1; j < working.length; j++) {
        let next = working[j];
        if (next.from == span.from) {
          if (next.to != span.to) {
            if (working == spans)
              working = spans.slice();
            working[j] = next.copy(next.from, span.to);
            insertAhead(working, j + 1, next.copy(span.to, next.to));
          }
          continue;
        } else {
          if (next.from < span.to) {
            if (working == spans)
              working = spans.slice();
            working[i] = span.copy(span.from, next.from);
            insertAhead(working, j, span.copy(next.from, span.to));
          }
          break;
        }
      }
  }
  return working;
}
function insertAhead(array, i, deco) {
  while (i < array.length && byPos(deco, array[i]) > 0)
    i++;
  array.splice(i, 0, deco);
}
function viewDecorations(view) {
  let found2 = [];
  view.someProp("decorations", (f) => {
    let result = f(view.state);
    if (result && result != empty)
      found2.push(result);
  });
  if (view.cursorWrapper)
    found2.push(DecorationSet.create(view.state.doc, [view.cursorWrapper.deco]));
  return DecorationGroup.from(found2);
}
var observeOptions = {
  childList: true,
  characterData: true,
  characterDataOldValue: true,
  attributes: true,
  attributeOldValue: true,
  subtree: true
};
var useCharData = ie && ie_version <= 11;
var SelectionState = class {
  constructor() {
    this.anchorNode = null;
    this.anchorOffset = 0;
    this.focusNode = null;
    this.focusOffset = 0;
  }
  set(sel) {
    this.anchorNode = sel.anchorNode;
    this.anchorOffset = sel.anchorOffset;
    this.focusNode = sel.focusNode;
    this.focusOffset = sel.focusOffset;
  }
  clear() {
    this.anchorNode = this.focusNode = null;
  }
  eq(sel) {
    return sel.anchorNode == this.anchorNode && sel.anchorOffset == this.anchorOffset && sel.focusNode == this.focusNode && sel.focusOffset == this.focusOffset;
  }
};
var DOMObserver = class {
  constructor(view, handleDOMChange) {
    this.view = view;
    this.handleDOMChange = handleDOMChange;
    this.queue = [];
    this.flushingSoon = -1;
    this.observer = null;
    this.currentSelection = new SelectionState();
    this.onCharData = null;
    this.suppressingSelectionUpdates = false;
    this.lastChangedTextNode = null;
    this.observer = window.MutationObserver && new window.MutationObserver((mutations) => {
      for (let i = 0; i < mutations.length; i++)
        this.queue.push(mutations[i]);
      if (ie && ie_version <= 11 && mutations.some((m) => m.type == "childList" && m.removedNodes.length || m.type == "characterData" && m.oldValue.length > m.target.nodeValue.length)) {
        this.flushSoon();
      } else if (safari && view.composing && mutations.some((m) => m.type == "childList" && m.target.nodeName == "TR")) {
        view.input.badSafariComposition = true;
        this.flushSoon();
      } else {
        this.flush();
      }
    });
    if (useCharData) {
      this.onCharData = (e) => {
        this.queue.push({ target: e.target, type: "characterData", oldValue: e.prevValue });
        this.flushSoon();
      };
    }
    this.onSelectionChange = this.onSelectionChange.bind(this);
  }
  flushSoon() {
    if (this.flushingSoon < 0)
      this.flushingSoon = window.setTimeout(() => {
        this.flushingSoon = -1;
        this.flush();
      }, 20);
  }
  forceFlush() {
    if (this.flushingSoon > -1) {
      window.clearTimeout(this.flushingSoon);
      this.flushingSoon = -1;
      this.flush();
    }
  }
  start() {
    if (this.observer) {
      this.observer.takeRecords();
      this.observer.observe(this.view.dom, observeOptions);
    }
    if (this.onCharData)
      this.view.dom.addEventListener("DOMCharacterDataModified", this.onCharData);
    this.connectSelection();
  }
  stop() {
    if (this.observer) {
      let take = this.observer.takeRecords();
      if (take.length) {
        for (let i = 0; i < take.length; i++)
          this.queue.push(take[i]);
        window.setTimeout(() => this.flush(), 20);
      }
      this.observer.disconnect();
    }
    if (this.onCharData)
      this.view.dom.removeEventListener("DOMCharacterDataModified", this.onCharData);
    this.disconnectSelection();
  }
  connectSelection() {
    this.view.dom.ownerDocument.addEventListener("selectionchange", this.onSelectionChange);
  }
  disconnectSelection() {
    this.view.dom.ownerDocument.removeEventListener("selectionchange", this.onSelectionChange);
  }
  suppressSelectionUpdates() {
    this.suppressingSelectionUpdates = true;
    setTimeout(() => this.suppressingSelectionUpdates = false, 50);
  }
  onSelectionChange() {
    if (!hasFocusAndSelection(this.view))
      return;
    if (this.suppressingSelectionUpdates)
      return selectionToDOM(this.view);
    if (ie && ie_version <= 11 && !this.view.state.selection.empty) {
      let sel = this.view.domSelectionRange();
      if (sel.focusNode && isEquivalentPosition(sel.focusNode, sel.focusOffset, sel.anchorNode, sel.anchorOffset))
        return this.flushSoon();
    }
    this.flush();
  }
  setCurSelection() {
    this.currentSelection.set(this.view.domSelectionRange());
  }
  ignoreSelectionChange(sel) {
    if (!sel.focusNode)
      return true;
    let ancestors = /* @__PURE__ */ new Set(), container;
    for (let scan = sel.focusNode; scan; scan = parentNode(scan))
      ancestors.add(scan);
    for (let scan = sel.anchorNode; scan; scan = parentNode(scan))
      if (ancestors.has(scan)) {
        container = scan;
        break;
      }
    let desc = container && this.view.docView.nearestDesc(container);
    if (desc && desc.ignoreMutation({
      type: "selection",
      target: container.nodeType == 3 ? container.parentNode : container
    })) {
      this.setCurSelection();
      return true;
    }
  }
  pendingRecords() {
    if (this.observer)
      for (let mut of this.observer.takeRecords())
        this.queue.push(mut);
    return this.queue;
  }
  flush() {
    let { view } = this;
    if (!view.docView || this.flushingSoon > -1)
      return;
    let mutations = this.pendingRecords();
    if (mutations.length)
      this.queue = [];
    let sel = view.domSelectionRange();
    let newSel = !this.suppressingSelectionUpdates && !this.currentSelection.eq(sel) && hasFocusAndSelection(view) && !this.ignoreSelectionChange(sel);
    let from2 = -1, to = -1, typeOver = false, added = [];
    if (view.editable) {
      for (let i = 0; i < mutations.length; i++) {
        let result = this.registerMutation(mutations[i], added);
        if (result) {
          from2 = from2 < 0 ? result.from : Math.min(result.from, from2);
          to = to < 0 ? result.to : Math.max(result.to, to);
          if (result.typeOver)
            typeOver = true;
        }
      }
    }
    if (gecko && added.length) {
      let brs = added.filter((n) => n.nodeName == "BR");
      if (brs.length == 2) {
        let [a2, b2] = brs;
        if (a2.parentNode && a2.parentNode.parentNode == b2.parentNode)
          b2.remove();
        else
          a2.remove();
      } else {
        let { focusNode } = this.currentSelection;
        for (let br of brs) {
          let parent = br.parentNode;
          if (parent && parent.nodeName == "LI" && (!focusNode || blockParent(view, focusNode) != parent))
            br.remove();
        }
      }
    } else if ((chrome || safari) && added.some((n) => n.nodeName == "BR") && (view.input.lastKeyCode == 8 || view.input.lastKeyCode == 46)) {
      for (let node of added)
        if (node.nodeName == "BR" && node.parentNode) {
          let after = node.nextSibling;
          if (after && after.nodeType == 1 && after.contentEditable == "false")
            node.parentNode.removeChild(node);
        }
    }
    let readSel = null;
    if (from2 < 0 && newSel && view.input.lastFocus > Date.now() - 200 && Math.max(view.input.lastTouch, view.input.lastClick.time) < Date.now() - 300 && selectionCollapsed(sel) && (readSel = selectionFromDOM(view)) && readSel.eq(Selection.near(view.state.doc.resolve(0), 1))) {
      view.input.lastFocus = 0;
      selectionToDOM(view);
      this.currentSelection.set(sel);
      view.scrollToSelection();
    } else if (from2 > -1 || newSel) {
      if (from2 > -1) {
        view.docView.markDirty(from2, to);
        checkCSS(view);
      }
      if (view.input.badSafariComposition) {
        view.input.badSafariComposition = false;
        fixUpBadSafariComposition(view, added);
      }
      this.handleDOMChange(from2, to, typeOver, added);
      if (view.docView && view.docView.dirty)
        view.updateState(view.state);
      else if (!this.currentSelection.eq(sel))
        selectionToDOM(view);
      this.currentSelection.set(sel);
    }
  }
  registerMutation(mut, added) {
    if (added.indexOf(mut.target) > -1)
      return null;
    let desc = this.view.docView.nearestDesc(mut.target);
    if (mut.type == "attributes" && (desc == this.view.docView || mut.attributeName == "contenteditable" || // Firefox sometimes fires spurious events for null/empty styles
    mut.attributeName == "style" && !mut.oldValue && !mut.target.getAttribute("style")))
      return null;
    if (!desc || desc.ignoreMutation(mut))
      return null;
    if (mut.type == "childList") {
      for (let i = 0; i < mut.addedNodes.length; i++) {
        let node = mut.addedNodes[i];
        added.push(node);
        if (node.nodeType == 3)
          this.lastChangedTextNode = node;
      }
      if (desc.contentDOM && desc.contentDOM != desc.dom && !desc.contentDOM.contains(mut.target))
        return { from: desc.posBefore, to: desc.posAfter };
      let prev = mut.previousSibling, next = mut.nextSibling;
      if (ie && ie_version <= 11 && mut.addedNodes.length) {
        for (let i = 0; i < mut.addedNodes.length; i++) {
          let { previousSibling, nextSibling } = mut.addedNodes[i];
          if (!previousSibling || Array.prototype.indexOf.call(mut.addedNodes, previousSibling) < 0)
            prev = previousSibling;
          if (!nextSibling || Array.prototype.indexOf.call(mut.addedNodes, nextSibling) < 0)
            next = nextSibling;
        }
      }
      let fromOffset = prev && prev.parentNode == mut.target ? domIndex(prev) + 1 : 0;
      let from2 = desc.localPosFromDOM(mut.target, fromOffset, -1);
      let toOffset = next && next.parentNode == mut.target ? domIndex(next) : mut.target.childNodes.length;
      let to = desc.localPosFromDOM(mut.target, toOffset, 1);
      return { from: from2, to };
    } else if (mut.type == "attributes") {
      return { from: desc.posAtStart - desc.border, to: desc.posAtEnd + desc.border };
    } else {
      this.lastChangedTextNode = mut.target;
      return {
        from: desc.posAtStart,
        to: desc.posAtEnd,
        // An event was generated for a text change that didn't change
        // any text. Mark the dom change to fall back to assuming the
        // selection was typed over with an identical value if it can't
        // find another change.
        typeOver: mut.target.nodeValue == mut.oldValue
      };
    }
  }
};
var cssChecked = /* @__PURE__ */ new WeakMap();
var cssCheckWarned = false;
function checkCSS(view) {
  if (cssChecked.has(view))
    return;
  cssChecked.set(view, null);
  if (["normal", "nowrap", "pre-line"].indexOf(getComputedStyle(view.dom).whiteSpace) !== -1) {
    view.requiresGeckoHackNode = gecko;
    if (cssCheckWarned)
      return;
    console["warn"]("ProseMirror expects the CSS white-space property to be set, preferably to 'pre-wrap'. It is recommended to load style/prosemirror.css from the prosemirror-view package.");
    cssCheckWarned = true;
  }
}
function rangeToSelectionRange(view, range) {
  let anchorNode = range.startContainer, anchorOffset = range.startOffset;
  let focusNode = range.endContainer, focusOffset = range.endOffset;
  let currentAnchor = view.domAtPos(view.state.selection.anchor);
  if (isEquivalentPosition(currentAnchor.node, currentAnchor.offset, focusNode, focusOffset))
    [anchorNode, anchorOffset, focusNode, focusOffset] = [focusNode, focusOffset, anchorNode, anchorOffset];
  return { anchorNode, anchorOffset, focusNode, focusOffset };
}
function safariShadowSelectionRange(view, selection) {
  if (selection.getComposedRanges) {
    let range = selection.getComposedRanges(view.root)[0];
    if (range)
      return rangeToSelectionRange(view, range);
  }
  let found2;
  function read(event) {
    event.preventDefault();
    event.stopImmediatePropagation();
    found2 = event.getTargetRanges()[0];
  }
  view.dom.addEventListener("beforeinput", read, true);
  document.execCommand("indent");
  view.dom.removeEventListener("beforeinput", read, true);
  return found2 ? rangeToSelectionRange(view, found2) : null;
}
function blockParent(view, node) {
  for (let p2 = node.parentNode; p2 && p2 != view.dom; p2 = p2.parentNode) {
    let desc = view.docView.nearestDesc(p2, true);
    if (desc && desc.node.isBlock)
      return p2;
  }
  return null;
}
function fixUpBadSafariComposition(view, addedNodes) {
  var _a;
  let { focusNode, focusOffset } = view.domSelectionRange();
  for (let node of addedNodes) {
    if (((_a = node.parentNode) === null || _a === void 0 ? void 0 : _a.nodeName) == "TR") {
      let nextCell = node.nextSibling;
      while (nextCell && (nextCell.nodeName != "TD" && nextCell.nodeName != "TH"))
        nextCell = nextCell.nextSibling;
      if (nextCell) {
        let parent = nextCell;
        for (; ; ) {
          let first2 = parent.firstChild;
          if (!first2 || first2.nodeType != 1 || first2.contentEditable == "false" || /^(BR|IMG)$/.test(first2.nodeName))
            break;
          parent = first2;
        }
        parent.insertBefore(node, parent.firstChild);
        if (focusNode == node)
          view.domSelection().collapse(node, focusOffset);
      } else {
        node.parentNode.removeChild(node);
      }
    }
  }
}
function parseBetween(view, from_, to_) {
  let { node: parent, fromOffset, toOffset, from: from2, to } = view.docView.parseRange(from_, to_);
  let domSel = view.domSelectionRange();
  let find2;
  let anchor = domSel.anchorNode;
  if (anchor && view.dom.contains(anchor.nodeType == 1 ? anchor : anchor.parentNode)) {
    find2 = [{ node: anchor, offset: domSel.anchorOffset }];
    if (!selectionCollapsed(domSel))
      find2.push({ node: domSel.focusNode, offset: domSel.focusOffset });
  }
  if (chrome && view.input.lastKeyCode === 8) {
    for (let off = toOffset; off > fromOffset; off--) {
      let node = parent.childNodes[off - 1], desc = node.pmViewDesc;
      if (node.nodeName == "BR" && !desc) {
        toOffset = off;
        break;
      }
      if (!desc || desc.size)
        break;
    }
  }
  let startDoc = view.state.doc;
  let parser = view.someProp("domParser") || DOMParser2.fromSchema(view.state.schema);
  let $from = startDoc.resolve(from2);
  let sel = null, doc3 = parser.parse(parent, {
    topNode: $from.parent,
    topMatch: $from.parent.contentMatchAt($from.index()),
    topOpen: true,
    from: fromOffset,
    to: toOffset,
    preserveWhitespace: $from.parent.type.whitespace == "pre" ? "full" : true,
    findPositions: find2,
    ruleFromNode,
    context: $from
  });
  if (find2 && find2[0].pos != null) {
    let anchor2 = find2[0].pos, head = find2[1] && find2[1].pos;
    if (head == null)
      head = anchor2;
    sel = { anchor: anchor2 + from2, head: head + from2 };
  }
  return { doc: doc3, sel, from: from2, to };
}
function ruleFromNode(dom) {
  let desc = dom.pmViewDesc;
  if (desc) {
    return desc.parseRule();
  } else if (dom.nodeName == "BR" && dom.parentNode) {
    if (safari && /^(ul|ol)$/i.test(dom.parentNode.nodeName)) {
      let skip = document.createElement("div");
      skip.appendChild(document.createElement("li"));
      return { skip };
    } else if (dom.parentNode.lastChild == dom || safari && /^(tr|table)$/i.test(dom.parentNode.nodeName)) {
      return { ignore: true };
    }
  } else if (dom.nodeName == "IMG" && dom.getAttribute("mark-placeholder")) {
    return { ignore: true };
  }
  return null;
}
var isInline = /^(a|abbr|acronym|b|bd[io]|big|br|button|cite|code|data(list)?|del|dfn|em|i|img|ins|kbd|label|map|mark|meter|output|q|ruby|s|samp|small|span|strong|su[bp]|time|u|tt|var)$/i;
function readDOMChange(view, from2, to, typeOver, addedNodes) {
  let compositionID = view.input.compositionPendingChanges || (view.composing ? view.input.compositionID : 0);
  view.input.compositionPendingChanges = 0;
  if (from2 < 0) {
    let origin = view.input.lastSelectionTime > Date.now() - 50 ? view.input.lastSelectionOrigin : null;
    let newSel = selectionFromDOM(view, origin);
    if (newSel && !view.state.selection.eq(newSel)) {
      if (chrome && android && view.input.lastKeyCode === 13 && Date.now() - 100 < view.input.lastKeyCodeTime && view.someProp("handleKeyDown", (f) => f(view, keyEvent(13, "Enter"))))
        return;
      let tr2 = view.state.tr.setSelection(newSel);
      if (origin == "pointer")
        tr2.setMeta("pointer", true);
      else if (origin == "key")
        tr2.scrollIntoView();
      if (compositionID)
        tr2.setMeta("composition", compositionID);
      view.dispatch(tr2);
    }
    return;
  }
  let $before = view.state.doc.resolve(from2);
  let shared = $before.sharedDepth(to);
  from2 = $before.before(shared + 1);
  to = view.state.doc.resolve(to).after(shared + 1);
  let sel = view.state.selection;
  let parse = parseBetween(view, from2, to);
  let doc3 = view.state.doc, compare = doc3.slice(parse.from, parse.to);
  let preferredPos, preferredSide;
  if (view.input.lastKeyCode === 8 && Date.now() - 100 < view.input.lastKeyCodeTime) {
    preferredPos = view.state.selection.to;
    preferredSide = "end";
  } else {
    preferredPos = view.state.selection.from;
    preferredSide = "start";
  }
  view.input.lastKeyCode = null;
  let change = findDiff(compare.content, parse.doc.content, parse.from, preferredPos, preferredSide);
  if (change)
    view.input.domChangeCount++;
  if ((ios && view.input.lastIOSEnter > Date.now() - 225 || android) && addedNodes.some((n) => n.nodeType == 1 && !isInline.test(n.nodeName)) && (!change || change.endA >= change.endB) && view.someProp("handleKeyDown", (f) => f(view, keyEvent(13, "Enter")))) {
    view.input.lastIOSEnter = 0;
    return;
  }
  if (!change) {
    if (typeOver && sel instanceof TextSelection && !sel.empty && sel.$head.sameParent(sel.$anchor) && !view.composing && !(parse.sel && parse.sel.anchor != parse.sel.head)) {
      change = { start: sel.from, endA: sel.to, endB: sel.to };
    } else {
      if (parse.sel) {
        let sel2 = resolveSelection(view, view.state.doc, parse.sel);
        if (sel2 && !sel2.eq(view.state.selection)) {
          let tr2 = view.state.tr.setSelection(sel2);
          if (compositionID)
            tr2.setMeta("composition", compositionID);
          view.dispatch(tr2);
        }
      }
      return;
    }
  }
  if (view.state.selection.from < view.state.selection.to && change.start == change.endB && view.state.selection instanceof TextSelection) {
    if (change.start > view.state.selection.from && change.start <= view.state.selection.from + 2 && view.state.selection.from >= parse.from) {
      change.start = view.state.selection.from;
    } else if (change.endA < view.state.selection.to && change.endA >= view.state.selection.to - 2 && view.state.selection.to <= parse.to) {
      change.endB += view.state.selection.to - change.endA;
      change.endA = view.state.selection.to;
    }
  }
  if (ie && ie_version <= 11 && change.endB == change.start + 1 && change.endA == change.start && change.start > parse.from && parse.doc.textBetween(change.start - parse.from - 1, change.start - parse.from + 1) == " \xA0") {
    change.start--;
    change.endA--;
    change.endB--;
  }
  let $from = parse.doc.resolveNoCache(change.start - parse.from);
  let $to = parse.doc.resolveNoCache(change.endB - parse.from);
  let $fromA = doc3.resolve(change.start);
  let inlineChange = $from.sameParent($to) && $from.parent.inlineContent && $fromA.end() >= change.endA;
  if ((ios && view.input.lastIOSEnter > Date.now() - 225 && (!inlineChange || addedNodes.some((n) => n.nodeName == "DIV" || n.nodeName == "P")) || !inlineChange && $from.pos < parse.doc.content.size && (!$from.sameParent($to) || !$from.parent.inlineContent) && $from.pos < $to.pos && !/\S/.test(parse.doc.textBetween($from.pos, $to.pos, "", ""))) && view.someProp("handleKeyDown", (f) => f(view, keyEvent(13, "Enter")))) {
    view.input.lastIOSEnter = 0;
    return;
  }
  if (view.state.selection.anchor > change.start && looksLikeBackspace(doc3, change.start, change.endA, $from, $to) && view.someProp("handleKeyDown", (f) => f(view, keyEvent(8, "Backspace")))) {
    if (android && chrome)
      view.domObserver.suppressSelectionUpdates();
    return;
  }
  if (chrome && change.endB == change.start)
    view.input.lastChromeDelete = Date.now();
  if (android && !inlineChange && $from.start() != $to.start() && $to.parentOffset == 0 && $from.depth == $to.depth && parse.sel && parse.sel.anchor == parse.sel.head && parse.sel.head == change.endA) {
    change.endB -= 2;
    $to = parse.doc.resolveNoCache(change.endB - parse.from);
    setTimeout(() => {
      view.someProp("handleKeyDown", function(f) {
        return f(view, keyEvent(13, "Enter"));
      });
    }, 20);
  }
  let chFrom = change.start, chTo = change.endA;
  let mkTr = (base2) => {
    let tr2 = base2 || view.state.tr.replace(chFrom, chTo, parse.doc.slice(change.start - parse.from, change.endB - parse.from));
    if (parse.sel) {
      let sel2 = resolveSelection(view, tr2.doc, parse.sel);
      if (sel2 && !(chrome && view.composing && sel2.empty && (change.start != change.endB || view.input.lastChromeDelete < Date.now() - 100) && (sel2.head == chFrom || sel2.head == tr2.mapping.map(chTo) - 1) || ie && sel2.empty && sel2.head == chFrom))
        tr2.setSelection(sel2);
    }
    if (compositionID)
      tr2.setMeta("composition", compositionID);
    return tr2.scrollIntoView();
  };
  let markChange;
  if (inlineChange) {
    if ($from.pos == $to.pos) {
      if (ie && ie_version <= 11 && $from.parentOffset == 0) {
        view.domObserver.suppressSelectionUpdates();
        setTimeout(() => selectionToDOM(view), 20);
      }
      let tr2 = mkTr(view.state.tr.delete(chFrom, chTo));
      let marks = doc3.resolve(change.start).marksAcross(doc3.resolve(change.endA));
      if (marks)
        tr2.ensureMarks(marks);
      view.dispatch(tr2);
    } else if (
      // Adding or removing a mark
      change.endA == change.endB && (markChange = isMarkChange($from.parent.content.cut($from.parentOffset, $to.parentOffset), $fromA.parent.content.cut($fromA.parentOffset, change.endA - $fromA.start())))
    ) {
      let tr2 = mkTr(view.state.tr);
      if (markChange.type == "add")
        tr2.addMark(chFrom, chTo, markChange.mark);
      else
        tr2.removeMark(chFrom, chTo, markChange.mark);
      view.dispatch(tr2);
    } else if ($from.parent.child($from.index()).isText && $from.index() == $to.index() - ($to.textOffset ? 0 : 1)) {
      let text5 = $from.parent.textBetween($from.parentOffset, $to.parentOffset);
      let deflt3 = () => mkTr(view.state.tr.insertText(text5, chFrom, chTo));
      if (!view.someProp("handleTextInput", (f) => f(view, chFrom, chTo, text5, deflt3)))
        view.dispatch(deflt3());
    } else {
      view.dispatch(mkTr());
    }
  } else {
    view.dispatch(mkTr());
  }
}
function resolveSelection(view, doc3, parsedSel) {
  if (Math.max(parsedSel.anchor, parsedSel.head) > doc3.content.size)
    return null;
  return selectionBetween(view, doc3.resolve(parsedSel.anchor), doc3.resolve(parsedSel.head));
}
function isMarkChange(cur, prev) {
  let curMarks = cur.firstChild.marks, prevMarks = prev.firstChild.marks;
  let added = curMarks, removed = prevMarks, type, mark, update;
  for (let i = 0; i < prevMarks.length; i++)
    added = prevMarks[i].removeFromSet(added);
  for (let i = 0; i < curMarks.length; i++)
    removed = curMarks[i].removeFromSet(removed);
  if (added.length == 1 && removed.length == 0) {
    mark = added[0];
    type = "add";
    update = (node) => node.mark(mark.addToSet(node.marks));
  } else if (added.length == 0 && removed.length == 1) {
    mark = removed[0];
    type = "remove";
    update = (node) => node.mark(mark.removeFromSet(node.marks));
  } else {
    return null;
  }
  let updated = [];
  for (let i = 0; i < prev.childCount; i++)
    updated.push(update(prev.child(i)));
  if (Fragment.from(updated).eq(cur))
    return { mark, type };
}
function looksLikeBackspace(old, start, end, $newStart, $newEnd) {
  if (
    // The content must have shrunk
    end - start <= $newEnd.pos - $newStart.pos || // newEnd must point directly at or after the end of the block that newStart points into
    skipClosingAndOpening($newStart, true, false) < $newEnd.pos
  )
    return false;
  let $start = old.resolve(start);
  if (!$newStart.parent.isTextblock) {
    let after = $start.nodeAfter;
    return after != null && end == start + after.nodeSize;
  }
  if ($start.parentOffset < $start.parent.content.size || !$start.parent.isTextblock)
    return false;
  let $next = old.resolve(skipClosingAndOpening($start, true, true));
  if (!$next.parent.isTextblock || $next.pos > end || skipClosingAndOpening($next, true, false) < end)
    return false;
  return $newStart.parent.content.cut($newStart.parentOffset).eq($next.parent.content);
}
function skipClosingAndOpening($pos, fromEnd, mayOpen) {
  let depth = $pos.depth, end = fromEnd ? $pos.end() : $pos.pos;
  while (depth > 0 && (fromEnd || $pos.indexAfter(depth) == $pos.node(depth).childCount)) {
    depth--;
    end++;
    fromEnd = false;
  }
  if (mayOpen) {
    let next = $pos.node(depth).maybeChild($pos.indexAfter(depth));
    while (next && !next.isLeaf) {
      next = next.firstChild;
      end++;
    }
  }
  return end;
}
function findDiff(a2, b2, pos, preferredPos, preferredSide) {
  let start = a2.findDiffStart(b2, pos);
  if (start == null)
    return null;
  let { a: endA, b: endB } = a2.findDiffEnd(b2, pos + a2.size, pos + b2.size);
  if (preferredSide == "end") {
    let adjust = Math.max(0, start - Math.min(endA, endB));
    preferredPos -= endA + adjust - start;
  }
  if (endA < start && a2.size < b2.size) {
    let move = preferredPos <= start && preferredPos >= endA ? start - preferredPos : 0;
    start -= move;
    if (start && start < b2.size && isSurrogatePair(b2.textBetween(start - 1, start + 1)))
      start += move ? 1 : -1;
    endB = start + (endB - endA);
    endA = start;
  } else if (endB < start) {
    let move = preferredPos <= start && preferredPos >= endB ? start - preferredPos : 0;
    start -= move;
    if (start && start < a2.size && isSurrogatePair(a2.textBetween(start - 1, start + 1)))
      start += move ? 1 : -1;
    endA = start + (endA - endB);
    endB = start;
  }
  return { start, endA, endB };
}
function isSurrogatePair(str) {
  if (str.length != 2)
    return false;
  let a2 = str.charCodeAt(0), b2 = str.charCodeAt(1);
  return a2 >= 56320 && a2 <= 57343 && b2 >= 55296 && b2 <= 56319;
}
var EditorView = class {
  /**
  Create a view. `place` may be a DOM node that the editor should
  be appended to, a function that will place it into the document,
  or an object whose `mount` property holds the node to use as the
  document container. If it is `null`, the editor will not be
  added to the document.
  */
  constructor(place, props) {
    this._root = null;
    this.focused = false;
    this.trackWrites = null;
    this.mounted = false;
    this.markCursor = null;
    this.cursorWrapper = null;
    this.lastSelectedViewDesc = void 0;
    this.input = new InputState();
    this.prevDirectPlugins = [];
    this.pluginViews = [];
    this.requiresGeckoHackNode = false;
    this.dragging = null;
    this._props = props;
    this.state = props.state;
    this.directPlugins = props.plugins || [];
    this.directPlugins.forEach(checkStateComponent);
    this.dispatch = this.dispatch.bind(this);
    this.dom = place && place.mount || document.createElement("div");
    if (place) {
      if (place.appendChild)
        place.appendChild(this.dom);
      else if (typeof place == "function")
        place(this.dom);
      else if (place.mount)
        this.mounted = true;
    }
    this.editable = getEditable(this);
    updateCursorWrapper(this);
    this.nodeViews = buildNodeViews(this);
    this.docView = docViewDesc(this.state.doc, computeDocDeco(this), viewDecorations(this), this.dom, this);
    this.domObserver = new DOMObserver(this, (from2, to, typeOver, added) => readDOMChange(this, from2, to, typeOver, added));
    this.domObserver.start();
    initInput(this);
    this.updatePluginViews();
  }
  /**
  Holds `true` when a
  [composition](https://w3c.github.io/uievents/#events-compositionevents)
  is active.
  */
  get composing() {
    return this.input.composing;
  }
  /**
  The view's current [props](https://prosemirror.net/docs/ref/#view.EditorProps).
  */
  get props() {
    if (this._props.state != this.state) {
      let prev = this._props;
      this._props = {};
      for (let name in prev)
        this._props[name] = prev[name];
      this._props.state = this.state;
    }
    return this._props;
  }
  /**
  Update the view's props. Will immediately cause an update to
  the DOM.
  */
  update(props) {
    if (props.handleDOMEvents != this._props.handleDOMEvents)
      ensureListeners(this);
    let prevProps = this._props;
    this._props = props;
    if (props.plugins) {
      props.plugins.forEach(checkStateComponent);
      this.directPlugins = props.plugins;
    }
    this.updateStateInner(props.state, prevProps);
  }
  /**
  Update the view by updating existing props object with the object
  given as argument. Equivalent to `view.update(Object.assign({},
  view.props, props))`.
  */
  setProps(props) {
    let updated = {};
    for (let name in this._props)
      updated[name] = this._props[name];
    updated.state = this.state;
    for (let name in props)
      updated[name] = props[name];
    this.update(updated);
  }
  /**
  Update the editor's `state` prop, without touching any of the
  other props.
  */
  updateState(state) {
    this.updateStateInner(state, this._props);
  }
  updateStateInner(state, prevProps) {
    var _a;
    let prev = this.state, redraw = false, updateSel = false;
    if (state.storedMarks && this.composing) {
      clearComposition(this);
      updateSel = true;
    }
    this.state = state;
    let pluginsChanged = prev.plugins != state.plugins || this._props.plugins != prevProps.plugins;
    if (pluginsChanged || this._props.plugins != prevProps.plugins || this._props.nodeViews != prevProps.nodeViews) {
      let nodeViews = buildNodeViews(this);
      if (changedNodeViews(nodeViews, this.nodeViews)) {
        this.nodeViews = nodeViews;
        redraw = true;
      }
    }
    if (pluginsChanged || prevProps.handleDOMEvents != this._props.handleDOMEvents) {
      ensureListeners(this);
    }
    this.editable = getEditable(this);
    updateCursorWrapper(this);
    let innerDeco = viewDecorations(this), outerDeco = computeDocDeco(this);
    let scroll = prev.plugins != state.plugins && !prev.doc.eq(state.doc) ? "reset" : state.scrollToSelection > prev.scrollToSelection ? "to selection" : "preserve";
    let updateDoc = redraw || !this.docView.matchesNode(state.doc, outerDeco, innerDeco);
    if (updateDoc || !state.selection.eq(prev.selection))
      updateSel = true;
    let oldScrollPos = scroll == "preserve" && updateSel && this.dom.style.overflowAnchor == null && storeScrollPos(this);
    if (updateSel) {
      this.domObserver.stop();
      let forceSelUpdate = updateDoc && (ie || chrome) && !this.composing && !prev.selection.empty && !state.selection.empty && selectionContextChanged(prev.selection, state.selection);
      if (updateDoc) {
        let chromeKludge = chrome ? this.trackWrites = this.domSelectionRange().focusNode : null;
        if (this.composing)
          this.input.compositionNode = findCompositionNode(this);
        if (redraw || !this.docView.update(state.doc, outerDeco, innerDeco, this)) {
          this.docView.updateOuterDeco(outerDeco);
          this.docView.destroy();
          this.docView = docViewDesc(state.doc, outerDeco, innerDeco, this.dom, this);
        }
        if (chromeKludge && (!this.trackWrites || !this.dom.contains(this.trackWrites)))
          forceSelUpdate = true;
      }
      if (forceSelUpdate || !(this.input.mouseDown && this.domObserver.currentSelection.eq(this.domSelectionRange()) && anchorInRightPlace(this))) {
        selectionToDOM(this, forceSelUpdate);
      } else {
        syncNodeSelection(this, state.selection);
        this.domObserver.setCurSelection();
      }
      this.domObserver.start();
    }
    this.updatePluginViews(prev);
    if (((_a = this.dragging) === null || _a === void 0 ? void 0 : _a.node) && !prev.doc.eq(state.doc))
      this.updateDraggedNode(this.dragging, prev);
    if (scroll == "reset") {
      this.dom.scrollTop = 0;
    } else if (scroll == "to selection") {
      this.scrollToSelection();
    } else if (oldScrollPos) {
      resetScrollPos(oldScrollPos);
    }
  }
  /**
  @internal
  */
  scrollToSelection() {
    let startDOM = this.domSelectionRange().focusNode;
    if (!startDOM || !this.dom.contains(startDOM.nodeType == 1 ? startDOM : startDOM.parentNode)) ;
    else if (this.someProp("handleScrollToSelection", (f) => f(this))) ;
    else if (this.state.selection instanceof NodeSelection) {
      let target2 = this.docView.domAfterPos(this.state.selection.from);
      if (target2.nodeType == 1)
        scrollRectIntoView(this, target2.getBoundingClientRect(), startDOM);
    } else {
      scrollRectIntoView(this, this.coordsAtPos(this.state.selection.head, 1), startDOM);
    }
  }
  destroyPluginViews() {
    let view;
    while (view = this.pluginViews.pop())
      if (view.destroy)
        view.destroy();
  }
  updatePluginViews(prevState) {
    if (!prevState || prevState.plugins != this.state.plugins || this.directPlugins != this.prevDirectPlugins) {
      this.prevDirectPlugins = this.directPlugins;
      this.destroyPluginViews();
      for (let i = 0; i < this.directPlugins.length; i++) {
        let plugin = this.directPlugins[i];
        if (plugin.spec.view)
          this.pluginViews.push(plugin.spec.view(this));
      }
      for (let i = 0; i < this.state.plugins.length; i++) {
        let plugin = this.state.plugins[i];
        if (plugin.spec.view)
          this.pluginViews.push(plugin.spec.view(this));
      }
    } else {
      for (let i = 0; i < this.pluginViews.length; i++) {
        let pluginView = this.pluginViews[i];
        if (pluginView.update)
          pluginView.update(this, prevState);
      }
    }
  }
  updateDraggedNode(dragging, prev) {
    let sel = dragging.node, found2 = -1;
    if (this.state.doc.nodeAt(sel.from) == sel.node) {
      found2 = sel.from;
    } else {
      let movedPos = sel.from + (this.state.doc.content.size - prev.doc.content.size);
      let moved = movedPos > 0 && this.state.doc.nodeAt(movedPos);
      if (moved == sel.node)
        found2 = movedPos;
    }
    this.dragging = new Dragging(dragging.slice, dragging.move, found2 < 0 ? void 0 : NodeSelection.create(this.state.doc, found2));
  }
  someProp(propName, f) {
    let prop = this._props && this._props[propName], value;
    if (prop != null && (value = f ? f(prop) : prop))
      return value;
    for (let i = 0; i < this.directPlugins.length; i++) {
      let prop2 = this.directPlugins[i].props[propName];
      if (prop2 != null && (value = f ? f(prop2) : prop2))
        return value;
    }
    let plugins = this.state.plugins;
    if (plugins)
      for (let i = 0; i < plugins.length; i++) {
        let prop2 = plugins[i].props[propName];
        if (prop2 != null && (value = f ? f(prop2) : prop2))
          return value;
      }
  }
  /**
  Query whether the view has focus.
  */
  hasFocus() {
    if (ie) {
      let node = this.root.activeElement;
      if (node == this.dom)
        return true;
      if (!node || !this.dom.contains(node))
        return false;
      while (node && this.dom != node && this.dom.contains(node)) {
        if (node.contentEditable == "false")
          return false;
        node = node.parentElement;
      }
      return true;
    }
    return this.root.activeElement == this.dom;
  }
  /**
  Focus the editor.
  */
  focus() {
    this.domObserver.stop();
    if (this.editable)
      focusPreventScroll(this.dom);
    selectionToDOM(this);
    this.domObserver.start();
  }
  /**
  Get the document root in which the editor exists. This will
  usually be the top-level `document`, but might be a [shadow
  DOM](https://developer.mozilla.org/en-US/docs/Web/Web_Components/Shadow_DOM)
  root if the editor is inside one.
  */
  get root() {
    let cached = this._root;
    if (cached == null)
      for (let search = this.dom.parentNode; search; search = search.parentNode) {
        if (search.nodeType == 9 || search.nodeType == 11 && search.host) {
          if (!search.getSelection)
            Object.getPrototypeOf(search).getSelection = () => search.ownerDocument.getSelection();
          return this._root = search;
        }
      }
    return cached || document;
  }
  /**
  When an existing editor view is moved to a new document or
  shadow tree, call this to make it recompute its root.
  */
  updateRoot() {
    this._root = null;
  }
  /**
  Given a pair of viewport coordinates, return the document
  position that corresponds to them. May return null if the given
  coordinates aren't inside of the editor. When an object is
  returned, its `pos` property is the position nearest to the
  coordinates, and its `inside` property holds the position of the
  inner node that the position falls inside of, or -1 if it is at
  the top level, not in any node.
  */
  posAtCoords(coords) {
    return posAtCoords(this, coords);
  }
  /**
  Returns the viewport rectangle at a given document position.
  `left` and `right` will be the same number, as this returns a
  flat cursor-ish rectangle. If the position is between two things
  that aren't directly adjacent, `side` determines which element
  is used. When < 0, the element before the position is used,
  otherwise the element after.
  */
  coordsAtPos(pos, side = 1) {
    return coordsAtPos(this, pos, side);
  }
  /**
  Find the DOM position that corresponds to the given document
  position. When `side` is negative, find the position as close as
  possible to the content before the position. When positive,
  prefer positions close to the content after the position. When
  zero, prefer as shallow a position as possible.
  
  Note that you should **not** mutate the editor's internal DOM,
  only inspect it (and even that is usually not necessary).
  */
  domAtPos(pos, side = 0) {
    return this.docView.domFromPos(pos, side);
  }
  /**
  Find the DOM node that represents the document node after the
  given position. May return `null` when the position doesn't point
  in front of a node or if the node is inside an opaque node view.
  
  This is intended to be able to call things like
  `getBoundingClientRect` on that DOM node. Do **not** mutate the
  editor DOM directly, or add styling this way, since that will be
  immediately overriden by the editor as it redraws the node.
  */
  nodeDOM(pos) {
    let desc = this.docView.descAt(pos);
    return desc ? desc.nodeDOM : null;
  }
  /**
  Find the document position that corresponds to a given DOM
  position. (Whenever possible, it is preferable to inspect the
  document structure directly, rather than poking around in the
  DOM, but sometimes—for example when interpreting an event
  target—you don't have a choice.)
  
  The `bias` parameter can be used to influence which side of a DOM
  node to use when the position is inside a leaf node.
  */
  posAtDOM(node, offset, bias = -1) {
    let pos = this.docView.posFromDOM(node, offset, bias);
    if (pos == null)
      throw new RangeError("DOM position not inside the editor");
    return pos;
  }
  /**
  Find out whether the selection is at the end of a textblock when
  moving in a given direction. When, for example, given `"left"`,
  it will return true if moving left from the current cursor
  position would leave that position's parent textblock. Will apply
  to the view's current state by default, but it is possible to
  pass a different state.
  */
  endOfTextblock(dir, state) {
    return endOfTextblock(this, state || this.state, dir);
  }
  /**
  Run the editor's paste logic with the given HTML string. The
  `event`, if given, will be passed to the
  [`handlePaste`](https://prosemirror.net/docs/ref/#view.EditorProps.handlePaste) hook.
  */
  pasteHTML(html, event) {
    return doPaste(this, "", html, false, event || new ClipboardEvent("paste"));
  }
  /**
  Run the editor's paste logic with the given plain-text input.
  */
  pasteText(text5, event) {
    return doPaste(this, text5, null, true, event || new ClipboardEvent("paste"));
  }
  /**
  Serialize the given slice as it would be if it was copied from
  this editor. Returns a DOM element that contains a
  representation of the slice as its children, a textual
  representation, and the transformed slice (which can be
  different from the given input due to hooks like
  [`transformCopied`](https://prosemirror.net/docs/ref/#view.EditorProps.transformCopied)).
  */
  serializeForClipboard(slice2) {
    return serializeForClipboard(this, slice2);
  }
  /**
  Removes the editor from the DOM and destroys all [node
  views](https://prosemirror.net/docs/ref/#view.NodeView).
  */
  destroy() {
    if (!this.docView)
      return;
    destroyInput(this);
    this.destroyPluginViews();
    if (this.mounted) {
      this.docView.update(this.state.doc, [], viewDecorations(this), this);
      this.dom.textContent = "";
    } else if (this.dom.parentNode) {
      this.dom.parentNode.removeChild(this.dom);
    }
    this.docView.destroy();
    this.docView = null;
    clearReusedRange();
  }
  /**
  This is true when the view has been
  [destroyed](https://prosemirror.net/docs/ref/#view.EditorView.destroy) (and thus should not be
  used anymore).
  */
  get isDestroyed() {
    return this.docView == null;
  }
  /**
  Used for testing.
  */
  dispatchEvent(event) {
    return dispatchEvent(this, event);
  }
  /**
  @internal
  */
  domSelectionRange() {
    let sel = this.domSelection();
    if (!sel)
      return { focusNode: null, focusOffset: 0, anchorNode: null, anchorOffset: 0 };
    return safari && this.root.nodeType === 11 && deepActiveElement(this.dom.ownerDocument) == this.dom && safariShadowSelectionRange(this, sel) || sel;
  }
  /**
  @internal
  */
  domSelection() {
    return this.root.getSelection();
  }
};
EditorView.prototype.dispatch = function(tr2) {
  let dispatchTransaction = this._props.dispatchTransaction;
  if (dispatchTransaction)
    dispatchTransaction.call(this, tr2);
  else
    this.updateState(this.state.apply(tr2));
};
function computeDocDeco(view) {
  let attrs = /* @__PURE__ */ Object.create(null);
  attrs.class = "ProseMirror";
  attrs.contenteditable = String(view.editable);
  view.someProp("attributes", (value) => {
    if (typeof value == "function")
      value = value(view.state);
    if (value)
      for (let attr in value) {
        if (attr == "class")
          attrs.class += " " + value[attr];
        else if (attr == "style")
          attrs.style = (attrs.style ? attrs.style + ";" : "") + value[attr];
        else if (!attrs[attr] && attr != "contenteditable" && attr != "nodeName")
          attrs[attr] = String(value[attr]);
      }
  });
  if (!attrs.translate)
    attrs.translate = "no";
  return [Decoration.node(0, view.state.doc.content.size, attrs)];
}
function updateCursorWrapper(view) {
  if (view.markCursor) {
    let dom = document.createElement("img");
    dom.className = "ProseMirror-separator";
    dom.setAttribute("mark-placeholder", "true");
    dom.setAttribute("alt", "");
    view.cursorWrapper = { dom, deco: Decoration.widget(view.state.selection.from, dom, { raw: true, marks: view.markCursor }) };
  } else {
    view.cursorWrapper = null;
  }
}
function getEditable(view) {
  return !view.someProp("editable", (value) => value(view.state) === false);
}
function selectionContextChanged(sel1, sel2) {
  let depth = Math.min(sel1.$anchor.sharedDepth(sel1.head), sel2.$anchor.sharedDepth(sel2.head));
  return sel1.$anchor.start(depth) != sel2.$anchor.start(depth);
}
function buildNodeViews(view) {
  let result = /* @__PURE__ */ Object.create(null);
  function add(obj) {
    for (let prop in obj)
      if (!Object.prototype.hasOwnProperty.call(result, prop))
        result[prop] = obj[prop];
  }
  view.someProp("nodeViews", add);
  view.someProp("markViews", add);
  return result;
}
function changedNodeViews(a2, b2) {
  let nA = 0, nB = 0;
  for (let prop in a2) {
    if (a2[prop] != b2[prop])
      return true;
    nA++;
  }
  for (let _10 in b2)
    nB++;
  return nA != nB;
}
function checkStateComponent(plugin) {
  if (plugin.spec.state || plugin.spec.filterTransaction || plugin.spec.appendTransaction)
    throw new RangeError("Plugins passed directly to the view must not have a state component");
}

// ../../node_modules/.pnpm/w3c-keyname@2.2.8/node_modules/w3c-keyname/index.js
var base = {
  8: "Backspace",
  9: "Tab",
  10: "Enter",
  12: "NumLock",
  13: "Enter",
  16: "Shift",
  17: "Control",
  18: "Alt",
  20: "CapsLock",
  27: "Escape",
  32: " ",
  33: "PageUp",
  34: "PageDown",
  35: "End",
  36: "Home",
  37: "ArrowLeft",
  38: "ArrowUp",
  39: "ArrowRight",
  40: "ArrowDown",
  44: "PrintScreen",
  45: "Insert",
  46: "Delete",
  59: ";",
  61: "=",
  91: "Meta",
  92: "Meta",
  106: "*",
  107: "+",
  108: ",",
  109: "-",
  110: ".",
  111: "/",
  144: "NumLock",
  145: "ScrollLock",
  160: "Shift",
  161: "Shift",
  162: "Control",
  163: "Control",
  164: "Alt",
  165: "Alt",
  173: "-",
  186: ";",
  187: "=",
  188: ",",
  189: "-",
  190: ".",
  191: "/",
  192: "`",
  219: "[",
  220: "\\",
  221: "]",
  222: "'"
};
var shift = {
  48: ")",
  49: "!",
  50: "@",
  51: "#",
  52: "$",
  53: "%",
  54: "^",
  55: "&",
  56: "*",
  57: "(",
  59: ":",
  61: "+",
  173: "_",
  186: ":",
  187: "+",
  188: "<",
  189: "_",
  190: ">",
  191: "?",
  192: "~",
  219: "{",
  220: "|",
  221: "}",
  222: '"'
};
var mac3 = typeof navigator != "undefined" && /Mac/.test(navigator.platform);
var ie2 = typeof navigator != "undefined" && /MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent);
for (i = 0; i < 10; i++) base[48 + i] = base[96 + i] = String(i);
var i;
for (i = 1; i <= 24; i++) base[i + 111] = "F" + i;
var i;
for (i = 65; i <= 90; i++) {
  base[i] = String.fromCharCode(i + 32);
  shift[i] = String.fromCharCode(i);
}
var i;
for (code in base) if (!shift.hasOwnProperty(code)) shift[code] = base[code];
var code;
function keyName(event) {
  var ignoreKey = mac3 && event.metaKey && event.shiftKey && !event.ctrlKey && !event.altKey || ie2 && event.shiftKey && event.key && event.key.length == 1 || event.key == "Unidentified";
  var name = !ignoreKey && event.key || (event.shiftKey ? shift : base)[event.keyCode] || event.key || "Unidentified";
  if (name == "Esc") name = "Escape";
  if (name == "Del") name = "Delete";
  if (name == "Left") name = "ArrowLeft";
  if (name == "Up") name = "ArrowUp";
  if (name == "Right") name = "ArrowRight";
  if (name == "Down") name = "ArrowDown";
  return name;
}

// ../../node_modules/.pnpm/prosemirror-keymap@1.2.3/node_modules/prosemirror-keymap/dist/index.js
var mac4 = typeof navigator != "undefined" && /Mac|iP(hone|[oa]d)/.test(navigator.platform);
var windows2 = typeof navigator != "undefined" && /Win/.test(navigator.platform);
function normalizeKeyName(name) {
  let parts = name.split(/-(?!$)/), result = parts[parts.length - 1];
  if (result == "Space")
    result = " ";
  let alt, ctrl, shift2, meta;
  for (let i = 0; i < parts.length - 1; i++) {
    let mod = parts[i];
    if (/^(cmd|meta|m)$/i.test(mod))
      meta = true;
    else if (/^a(lt)?$/i.test(mod))
      alt = true;
    else if (/^(c|ctrl|control)$/i.test(mod))
      ctrl = true;
    else if (/^s(hift)?$/i.test(mod))
      shift2 = true;
    else if (/^mod$/i.test(mod)) {
      if (mac4)
        meta = true;
      else
        ctrl = true;
    } else
      throw new Error("Unrecognized modifier name: " + mod);
  }
  if (alt)
    result = "Alt-" + result;
  if (ctrl)
    result = "Ctrl-" + result;
  if (meta)
    result = "Meta-" + result;
  if (shift2)
    result = "Shift-" + result;
  return result;
}
function normalize(map2) {
  let copy3 = /* @__PURE__ */ Object.create(null);
  for (let prop in map2)
    copy3[normalizeKeyName(prop)] = map2[prop];
  return copy3;
}
function modifiers(name, event, shift2 = true) {
  if (event.altKey)
    name = "Alt-" + name;
  if (event.ctrlKey)
    name = "Ctrl-" + name;
  if (event.metaKey)
    name = "Meta-" + name;
  if (shift2 && event.shiftKey)
    name = "Shift-" + name;
  return name;
}
function keymap(bindings) {
  return new Plugin({ props: { handleKeyDown: keydownHandler(bindings) } });
}
function keydownHandler(bindings) {
  let map2 = normalize(bindings);
  return function(view, event) {
    let name = keyName(event), baseName, direct = map2[modifiers(name, event)];
    if (direct && direct(view.state, view.dispatch, view))
      return true;
    if (name.length == 1 && name != " ") {
      if (event.shiftKey) {
        let noShift = map2[modifiers(name, event, false)];
        if (noShift && noShift(view.state, view.dispatch, view))
          return true;
      }
      if ((event.altKey || event.metaKey || event.ctrlKey) && // Ctrl-Alt may be used for AltGr on Windows
      !(windows2 && event.ctrlKey && event.altKey) && (baseName = base[event.keyCode]) && baseName != name) {
        let fromCode = map2[modifiers(baseName, event)];
        if (fromCode && fromCode(view.state, view.dispatch, view))
          return true;
      }
    }
    return false;
  };
}

// ../../node_modules/.pnpm/@tiptap+core@3.15.3_@tiptap+pm@3.15.3/node_modules/@tiptap/core/dist/index.js
var __defProp2 = Object.defineProperty;
var __export = (target2, all) => {
  for (var name in all)
    __defProp2(target2, name, { get: all[name], enumerable: true });
};
function createChainableState(config) {
  const { state, transaction } = config;
  let { selection } = transaction;
  let { doc: doc3 } = transaction;
  let { storedMarks } = transaction;
  return {
    ...state,
    apply: state.apply.bind(state),
    applyTransaction: state.applyTransaction.bind(state),
    plugins: state.plugins,
    schema: state.schema,
    reconfigure: state.reconfigure.bind(state),
    toJSON: state.toJSON.bind(state),
    get storedMarks() {
      return storedMarks;
    },
    get selection() {
      return selection;
    },
    get doc() {
      return doc3;
    },
    get tr() {
      selection = transaction.selection;
      doc3 = transaction.doc;
      storedMarks = transaction.storedMarks;
      return transaction;
    }
  };
}
var CommandManager = class {
  constructor(props) {
    this.editor = props.editor;
    this.rawCommands = this.editor.extensionManager.commands;
    this.customState = props.state;
  }
  get hasCustomState() {
    return !!this.customState;
  }
  get state() {
    return this.customState || this.editor.state;
  }
  get commands() {
    const { rawCommands, editor, state } = this;
    const { view } = editor;
    const { tr: tr2 } = state;
    const props = this.buildProps(tr2);
    return Object.fromEntries(
      Object.entries(rawCommands).map(([name, command2]) => {
        const method = (...args) => {
          const callback = command2(...args)(props);
          if (!tr2.getMeta("preventDispatch") && !this.hasCustomState) {
            view.dispatch(tr2);
          }
          return callback;
        };
        return [name, method];
      })
    );
  }
  get chain() {
    return () => this.createChain();
  }
  get can() {
    return () => this.createCan();
  }
  createChain(startTr, shouldDispatch = true) {
    const { rawCommands, editor, state } = this;
    const { view } = editor;
    const callbacks = [];
    const hasStartTransaction = !!startTr;
    const tr2 = startTr || state.tr;
    const run32 = () => {
      if (!hasStartTransaction && shouldDispatch && !tr2.getMeta("preventDispatch") && !this.hasCustomState) {
        view.dispatch(tr2);
      }
      return callbacks.every((callback) => callback === true);
    };
    const chain = {
      ...Object.fromEntries(
        Object.entries(rawCommands).map(([name, command2]) => {
          const chainedCommand = (...args) => {
            const props = this.buildProps(tr2, shouldDispatch);
            const callback = command2(...args)(props);
            callbacks.push(callback);
            return chain;
          };
          return [name, chainedCommand];
        })
      ),
      run: run32
    };
    return chain;
  }
  createCan(startTr) {
    const { rawCommands, state } = this;
    const dispatch = false;
    const tr2 = startTr || state.tr;
    const props = this.buildProps(tr2, dispatch);
    const formattedCommands = Object.fromEntries(
      Object.entries(rawCommands).map(([name, command2]) => {
        return [name, (...args) => command2(...args)({ ...props, dispatch: void 0 })];
      })
    );
    return {
      ...formattedCommands,
      chain: () => this.createChain(tr2, dispatch)
    };
  }
  buildProps(tr2, shouldDispatch = true) {
    const { rawCommands, editor, state } = this;
    const { view } = editor;
    const props = {
      tr: tr2,
      editor,
      view,
      state: createChainableState({
        state,
        transaction: tr2
      }),
      dispatch: shouldDispatch ? () => void 0 : void 0,
      chain: () => this.createChain(tr2, shouldDispatch),
      can: () => this.createCan(tr2),
      get commands() {
        return Object.fromEntries(
          Object.entries(rawCommands).map(([name, command2]) => {
            return [name, (...args) => command2(...args)(props)];
          })
        );
      }
    };
    return props;
  }
};
var commands_exports = {};
__export(commands_exports, {
  blur: () => blur,
  clearContent: () => clearContent,
  clearNodes: () => clearNodes,
  command: () => command,
  createParagraphNear: () => createParagraphNear2,
  cut: () => cut,
  deleteCurrentNode: () => deleteCurrentNode,
  deleteNode: () => deleteNode,
  deleteRange: () => deleteRange2,
  deleteSelection: () => deleteSelection2,
  enter: () => enter,
  exitCode: () => exitCode2,
  extendMarkRange: () => extendMarkRange,
  first: () => first,
  focus: () => focus,
  forEach: () => forEach,
  insertContent: () => insertContent,
  insertContentAt: () => insertContentAt,
  joinBackward: () => joinBackward2,
  joinDown: () => joinDown2,
  joinForward: () => joinForward2,
  joinItemBackward: () => joinItemBackward,
  joinItemForward: () => joinItemForward,
  joinTextblockBackward: () => joinTextblockBackward2,
  joinTextblockForward: () => joinTextblockForward2,
  joinUp: () => joinUp2,
  keyboardShortcut: () => keyboardShortcut,
  lift: () => lift3,
  liftEmptyBlock: () => liftEmptyBlock2,
  liftListItem: () => liftListItem2,
  newlineInCode: () => newlineInCode2,
  resetAttributes: () => resetAttributes,
  scrollIntoView: () => scrollIntoView,
  selectAll: () => selectAll2,
  selectNodeBackward: () => selectNodeBackward2,
  selectNodeForward: () => selectNodeForward2,
  selectParentNode: () => selectParentNode2,
  selectTextblockEnd: () => selectTextblockEnd2,
  selectTextblockStart: () => selectTextblockStart2,
  setContent: () => setContent,
  setMark: () => setMark,
  setMeta: () => setMeta,
  setNode: () => setNode,
  setNodeSelection: () => setNodeSelection,
  setTextDirection: () => setTextDirection,
  setTextSelection: () => setTextSelection,
  sinkListItem: () => sinkListItem2,
  splitBlock: () => splitBlock2,
  splitListItem: () => splitListItem,
  toggleList: () => toggleList,
  toggleMark: () => toggleMark,
  toggleNode: () => toggleNode,
  toggleWrap: () => toggleWrap,
  undoInputRule: () => undoInputRule,
  unsetAllMarks: () => unsetAllMarks,
  unsetMark: () => unsetMark,
  unsetTextDirection: () => unsetTextDirection,
  updateAttributes: () => updateAttributes,
  wrapIn: () => wrapIn2,
  wrapInList: () => wrapInList2
});
var blur = () => ({ editor, view }) => {
  requestAnimationFrame(() => {
    var _a;
    if (!editor.isDestroyed) {
      ;
      view.dom.blur();
      (_a = window == null ? void 0 : window.getSelection()) == null ? void 0 : _a.removeAllRanges();
    }
  });
  return true;
};
var clearContent = (emitUpdate = true) => ({ commands }) => {
  return commands.setContent("", { emitUpdate });
};
var clearNodes = () => ({ state, tr: tr2, dispatch }) => {
  const { selection } = tr2;
  const { ranges } = selection;
  if (!dispatch) {
    return true;
  }
  ranges.forEach(({ $from, $to }) => {
    state.doc.nodesBetween($from.pos, $to.pos, (node, pos) => {
      if (node.type.isText) {
        return;
      }
      const { doc: doc3, mapping } = tr2;
      const $mappedFrom = doc3.resolve(mapping.map(pos));
      const $mappedTo = doc3.resolve(mapping.map(pos + node.nodeSize));
      const nodeRange = $mappedFrom.blockRange($mappedTo);
      if (!nodeRange) {
        return;
      }
      const targetLiftDepth = liftTarget(nodeRange);
      if (node.type.isTextblock) {
        const { defaultType } = $mappedFrom.parent.contentMatchAt($mappedFrom.index());
        tr2.setNodeMarkup(nodeRange.start, defaultType);
      }
      if (targetLiftDepth || targetLiftDepth === 0) {
        tr2.lift(nodeRange, targetLiftDepth);
      }
    });
  });
  return true;
};
var command = (fn) => (props) => {
  return fn(props);
};
var createParagraphNear2 = () => ({ state, dispatch }) => {
  return createParagraphNear(state, dispatch);
};
var cut = (originRange, targetPos) => ({ editor, tr: tr2 }) => {
  const { state } = editor;
  const contentSlice = state.doc.slice(originRange.from, originRange.to);
  tr2.deleteRange(originRange.from, originRange.to);
  const newPos = tr2.mapping.map(targetPos);
  tr2.insert(newPos, contentSlice.content);
  tr2.setSelection(new TextSelection(tr2.doc.resolve(Math.max(newPos - 1, 0))));
  return true;
};
var deleteCurrentNode = () => ({ tr: tr2, dispatch }) => {
  const { selection } = tr2;
  const currentNode = selection.$anchor.node();
  if (currentNode.content.size > 0) {
    return false;
  }
  const $pos = tr2.selection.$anchor;
  for (let depth = $pos.depth; depth > 0; depth -= 1) {
    const node = $pos.node(depth);
    if (node.type === currentNode.type) {
      if (dispatch) {
        const from2 = $pos.before(depth);
        const to = $pos.after(depth);
        tr2.delete(from2, to).scrollIntoView();
      }
      return true;
    }
  }
  return false;
};
function getNodeType(nameOrType, schema) {
  if (typeof nameOrType === "string") {
    if (!schema.nodes[nameOrType]) {
      throw Error(`There is no node type named '${nameOrType}'. Maybe you forgot to add the extension?`);
    }
    return schema.nodes[nameOrType];
  }
  return nameOrType;
}
var deleteNode = (typeOrName) => ({ tr: tr2, state, dispatch }) => {
  const type = getNodeType(typeOrName, state.schema);
  const $pos = tr2.selection.$anchor;
  for (let depth = $pos.depth; depth > 0; depth -= 1) {
    const node = $pos.node(depth);
    if (node.type === type) {
      if (dispatch) {
        const from2 = $pos.before(depth);
        const to = $pos.after(depth);
        tr2.delete(from2, to).scrollIntoView();
      }
      return true;
    }
  }
  return false;
};
var deleteRange2 = (range) => ({ tr: tr2, dispatch }) => {
  const { from: from2, to } = range;
  if (dispatch) {
    tr2.delete(from2, to);
  }
  return true;
};
var deleteSelection2 = () => ({ state, dispatch }) => {
  return deleteSelection(state, dispatch);
};
var enter = () => ({ commands }) => {
  return commands.keyboardShortcut("Enter");
};
var exitCode2 = () => ({ state, dispatch }) => {
  return exitCode(state, dispatch);
};
function isRegExp(value) {
  return Object.prototype.toString.call(value) === "[object RegExp]";
}
function objectIncludes(object1, object2, options = { strict: true }) {
  const keys3 = Object.keys(object2);
  if (!keys3.length) {
    return true;
  }
  return keys3.every((key) => {
    if (options.strict) {
      return object2[key] === object1[key];
    }
    if (isRegExp(object2[key])) {
      return object2[key].test(object1[key]);
    }
    return object2[key] === object1[key];
  });
}
function findMarkInSet(marks, type, attributes = {}) {
  return marks.find((item) => {
    return item.type === type && objectIncludes(
      // Only check equality for the attributes that are provided
      Object.fromEntries(Object.keys(attributes).map((k) => [k, item.attrs[k]])),
      attributes
    );
  });
}
function isMarkInSet(marks, type, attributes = {}) {
  return !!findMarkInSet(marks, type, attributes);
}
function getMarkRange($pos, type, attributes) {
  var _a;
  if (!$pos || !type) {
    return;
  }
  let start = $pos.parent.childAfter($pos.parentOffset);
  if (!start.node || !start.node.marks.some((mark2) => mark2.type === type)) {
    start = $pos.parent.childBefore($pos.parentOffset);
  }
  if (!start.node || !start.node.marks.some((mark2) => mark2.type === type)) {
    return;
  }
  attributes = attributes || ((_a = start.node.marks[0]) == null ? void 0 : _a.attrs);
  const mark = findMarkInSet([...start.node.marks], type, attributes);
  if (!mark) {
    return;
  }
  let startIndex = start.index;
  let startPos = $pos.start() + start.offset;
  let endIndex = startIndex + 1;
  let endPos = startPos + start.node.nodeSize;
  while (startIndex > 0 && isMarkInSet([...$pos.parent.child(startIndex - 1).marks], type, attributes)) {
    startIndex -= 1;
    startPos -= $pos.parent.child(startIndex).nodeSize;
  }
  while (endIndex < $pos.parent.childCount && isMarkInSet([...$pos.parent.child(endIndex).marks], type, attributes)) {
    endPos += $pos.parent.child(endIndex).nodeSize;
    endIndex += 1;
  }
  return {
    from: startPos,
    to: endPos
  };
}
function getMarkType(nameOrType, schema) {
  if (typeof nameOrType === "string") {
    if (!schema.marks[nameOrType]) {
      throw Error(`There is no mark type named '${nameOrType}'. Maybe you forgot to add the extension?`);
    }
    return schema.marks[nameOrType];
  }
  return nameOrType;
}
var extendMarkRange = (typeOrName, attributes = {}) => ({ tr: tr2, state, dispatch }) => {
  const type = getMarkType(typeOrName, state.schema);
  const { doc: doc3, selection } = tr2;
  const { $from, from: from2, to } = selection;
  if (dispatch) {
    const range = getMarkRange($from, type, attributes);
    if (range && range.from <= from2 && range.to >= to) {
      const newSelection = TextSelection.create(doc3, range.from, range.to);
      tr2.setSelection(newSelection);
    }
  }
  return true;
};
var first = (commands) => (props) => {
  const items = typeof commands === "function" ? commands(props) : commands;
  for (let i = 0; i < items.length; i += 1) {
    if (items[i](props)) {
      return true;
    }
  }
  return false;
};
function isTextSelection(value) {
  return value instanceof TextSelection;
}
function minMax(value = 0, min = 0, max = 0) {
  return Math.min(Math.max(value, min), max);
}
function resolveFocusPosition(doc3, position = null) {
  if (!position) {
    return null;
  }
  const selectionAtStart = Selection.atStart(doc3);
  const selectionAtEnd = Selection.atEnd(doc3);
  if (position === "start" || position === true) {
    return selectionAtStart;
  }
  if (position === "end") {
    return selectionAtEnd;
  }
  const minPos = selectionAtStart.from;
  const maxPos = selectionAtEnd.to;
  if (position === "all") {
    return TextSelection.create(doc3, minMax(0, minPos, maxPos), minMax(doc3.content.size, minPos, maxPos));
  }
  return TextSelection.create(doc3, minMax(position, minPos, maxPos), minMax(position, minPos, maxPos));
}
function isAndroid() {
  return navigator.platform === "Android" || /android/i.test(navigator.userAgent);
}
function isiOS() {
  return ["iPad Simulator", "iPhone Simulator", "iPod Simulator", "iPad", "iPhone", "iPod"].includes(navigator.platform) || // iPad on iOS 13 detection
  navigator.userAgent.includes("Mac") && "ontouchend" in document;
}
function isSafari() {
  return typeof navigator !== "undefined" ? /^((?!chrome|android).)*safari/i.test(navigator.userAgent) : false;
}
var focus = (position = null, options = {}) => ({ editor, view, tr: tr2, dispatch }) => {
  options = {
    scrollIntoView: true,
    ...options
  };
  const delayedFocus = () => {
    if (isiOS() || isAndroid()) {
      ;
      view.dom.focus();
    }
    if (isSafari() && !isiOS() && !isAndroid()) {
      ;
      view.dom.focus({ preventScroll: true });
    }
    requestAnimationFrame(() => {
      if (!editor.isDestroyed) {
        view.focus();
        if (options == null ? void 0 : options.scrollIntoView) {
          editor.commands.scrollIntoView();
        }
      }
    });
  };
  if (view.hasFocus() && position === null || position === false) {
    return true;
  }
  if (dispatch && position === null && !isTextSelection(editor.state.selection)) {
    delayedFocus();
    return true;
  }
  const selection = resolveFocusPosition(tr2.doc, position) || editor.state.selection;
  const isSameSelection2 = editor.state.selection.eq(selection);
  if (dispatch) {
    if (!isSameSelection2) {
      tr2.setSelection(selection);
    }
    if (isSameSelection2 && tr2.storedMarks) {
      tr2.setStoredMarks(tr2.storedMarks);
    }
    delayedFocus();
  }
  return true;
};
var forEach = (items, fn) => (props) => {
  return items.every((item, index) => fn(item, { ...props, index }));
};
var insertContent = (value, options) => ({ tr: tr2, commands }) => {
  return commands.insertContentAt({ from: tr2.selection.from, to: tr2.selection.to }, value, options);
};
var removeWhitespaces = (node) => {
  const children = node.childNodes;
  for (let i = children.length - 1; i >= 0; i -= 1) {
    const child = children[i];
    if (child.nodeType === 3 && child.nodeValue && /^(\n\s\s|\n)$/.test(child.nodeValue)) {
      node.removeChild(child);
    } else if (child.nodeType === 1) {
      removeWhitespaces(child);
    }
  }
  return node;
};
function elementFromString(value) {
  if (typeof window === "undefined") {
    throw new Error("[tiptap error]: there is no window object available, so this function cannot be used");
  }
  const wrappedValue = `<body>${value}</body>`;
  const html = new window.DOMParser().parseFromString(wrappedValue, "text/html").body;
  return removeWhitespaces(html);
}
function createNodeFromContent(content, schema, options) {
  if (content instanceof Node2 || content instanceof Fragment) {
    return content;
  }
  options = {
    slice: true,
    parseOptions: {},
    ...options
  };
  const isJSONContent = typeof content === "object" && content !== null;
  const isTextContent = typeof content === "string";
  if (isJSONContent) {
    try {
      const isArrayContent = Array.isArray(content) && content.length > 0;
      if (isArrayContent) {
        return Fragment.fromArray(content.map((item) => schema.nodeFromJSON(item)));
      }
      const node = schema.nodeFromJSON(content);
      if (options.errorOnInvalidContent) {
        node.check();
      }
      return node;
    } catch (error) {
      if (options.errorOnInvalidContent) {
        throw new Error("[tiptap error]: Invalid JSON content", { cause: error });
      }
      console.warn("[tiptap warn]: Invalid content.", "Passed value:", content, "Error:", error);
      return createNodeFromContent("", schema, options);
    }
  }
  if (isTextContent) {
    if (options.errorOnInvalidContent) {
      let hasInvalidContent = false;
      let invalidContent = "";
      const contentCheckSchema = new Schema({
        topNode: schema.spec.topNode,
        marks: schema.spec.marks,
        // Prosemirror's schemas are executed such that: the last to execute, matches last
        // This means that we can add a catch-all node at the end of the schema to catch any content that we don't know how to handle
        nodes: schema.spec.nodes.append({
          __tiptap__private__unknown__catch__all__node: {
            content: "inline*",
            group: "block",
            parseDOM: [
              {
                tag: "*",
                getAttrs: (e) => {
                  hasInvalidContent = true;
                  invalidContent = typeof e === "string" ? e : e.outerHTML;
                  return null;
                }
              }
            ]
          }
        })
      });
      if (options.slice) {
        DOMParser2.fromSchema(contentCheckSchema).parseSlice(elementFromString(content), options.parseOptions);
      } else {
        DOMParser2.fromSchema(contentCheckSchema).parse(elementFromString(content), options.parseOptions);
      }
      if (options.errorOnInvalidContent && hasInvalidContent) {
        throw new Error("[tiptap error]: Invalid HTML content", {
          cause: new Error(`Invalid element found: ${invalidContent}`)
        });
      }
    }
    const parser = DOMParser2.fromSchema(schema);
    if (options.slice) {
      return parser.parseSlice(elementFromString(content), options.parseOptions).content;
    }
    return parser.parse(elementFromString(content), options.parseOptions);
  }
  return createNodeFromContent("", schema, options);
}
function selectionToInsertionEnd2(tr2, startLen, bias) {
  const last = tr2.steps.length - 1;
  if (last < startLen) {
    return;
  }
  const step = tr2.steps[last];
  if (!(step instanceof ReplaceStep || step instanceof ReplaceAroundStep)) {
    return;
  }
  const map2 = tr2.mapping.maps[last];
  let end = 0;
  map2.forEach((_from, _to, _newFrom, newTo) => {
    if (end === 0) {
      end = newTo;
    }
  });
  tr2.setSelection(Selection.near(tr2.doc.resolve(end), bias));
}
var isFragment = (nodeOrFragment) => {
  return !("type" in nodeOrFragment);
};
var insertContentAt = (position, value, options) => ({ tr: tr2, dispatch, editor }) => {
  var _a;
  if (dispatch) {
    options = {
      parseOptions: editor.options.parseOptions,
      updateSelection: true,
      applyInputRules: false,
      applyPasteRules: false,
      ...options
    };
    let content;
    const emitContentError = (error) => {
      editor.emit("contentError", {
        editor,
        error,
        disableCollaboration: () => {
          if ("collaboration" in editor.storage && typeof editor.storage.collaboration === "object" && editor.storage.collaboration) {
            ;
            editor.storage.collaboration.isDisabled = true;
          }
        }
      });
    };
    const parseOptions = {
      preserveWhitespace: "full",
      ...options.parseOptions
    };
    if (!options.errorOnInvalidContent && !editor.options.enableContentCheck && editor.options.emitContentError) {
      try {
        createNodeFromContent(value, editor.schema, {
          parseOptions,
          errorOnInvalidContent: true
        });
      } catch (e) {
        emitContentError(e);
      }
    }
    try {
      content = createNodeFromContent(value, editor.schema, {
        parseOptions,
        errorOnInvalidContent: (_a = options.errorOnInvalidContent) != null ? _a : editor.options.enableContentCheck
      });
    } catch (e) {
      emitContentError(e);
      return false;
    }
    let { from: from2, to } = typeof position === "number" ? { from: position, to: position } : { from: position.from, to: position.to };
    let isOnlyTextContent = true;
    let isOnlyBlockContent = true;
    const nodes = isFragment(content) ? content : [content];
    nodes.forEach((node) => {
      node.check();
      isOnlyTextContent = isOnlyTextContent ? node.isText && node.marks.length === 0 : false;
      isOnlyBlockContent = isOnlyBlockContent ? node.isBlock : false;
    });
    if (from2 === to && isOnlyBlockContent) {
      const { parent } = tr2.doc.resolve(from2);
      const isEmptyTextBlock = parent.isTextblock && !parent.type.spec.code && !parent.childCount;
      if (isEmptyTextBlock) {
        from2 -= 1;
        to += 1;
      }
    }
    let newContent;
    if (isOnlyTextContent) {
      if (Array.isArray(value)) {
        newContent = value.map((v) => v.text || "").join("");
      } else if (value instanceof Fragment) {
        let text5 = "";
        value.forEach((node) => {
          if (node.text) {
            text5 += node.text;
          }
        });
        newContent = text5;
      } else if (typeof value === "object" && !!value && !!value.text) {
        newContent = value.text;
      } else {
        newContent = value;
      }
      tr2.insertText(newContent, from2, to);
    } else {
      newContent = content;
      const $from = tr2.doc.resolve(from2);
      const $fromNode = $from.node();
      const fromSelectionAtStart = $from.parentOffset === 0;
      const isTextSelection2 = $fromNode.isText || $fromNode.isTextblock;
      const hasContent = $fromNode.content.size > 0;
      if (fromSelectionAtStart && isTextSelection2 && hasContent) {
        from2 = Math.max(0, from2 - 1);
      }
      tr2.replaceWith(from2, to, newContent);
    }
    if (options.updateSelection) {
      selectionToInsertionEnd2(tr2, tr2.steps.length - 1, -1);
    }
    if (options.applyInputRules) {
      tr2.setMeta("applyInputRules", { from: from2, text: newContent });
    }
    if (options.applyPasteRules) {
      tr2.setMeta("applyPasteRules", { from: from2, text: newContent });
    }
  }
  return true;
};
var joinUp2 = () => ({ state, dispatch }) => {
  return joinUp(state, dispatch);
};
var joinDown2 = () => ({ state, dispatch }) => {
  return joinDown(state, dispatch);
};
var joinBackward2 = () => ({ state, dispatch }) => {
  return joinBackward(state, dispatch);
};
var joinForward2 = () => ({ state, dispatch }) => {
  return joinForward(state, dispatch);
};
var joinItemBackward = () => ({ state, dispatch, tr: tr2 }) => {
  try {
    const point = joinPoint(state.doc, state.selection.$from.pos, -1);
    if (point === null || point === void 0) {
      return false;
    }
    tr2.join(point, 2);
    if (dispatch) {
      dispatch(tr2);
    }
    return true;
  } catch {
    return false;
  }
};
var joinItemForward = () => ({ state, dispatch, tr: tr2 }) => {
  try {
    const point = joinPoint(state.doc, state.selection.$from.pos, 1);
    if (point === null || point === void 0) {
      return false;
    }
    tr2.join(point, 2);
    if (dispatch) {
      dispatch(tr2);
    }
    return true;
  } catch {
    return false;
  }
};
var joinTextblockBackward2 = () => ({ state, dispatch }) => {
  return joinTextblockBackward(state, dispatch);
};
var joinTextblockForward2 = () => ({ state, dispatch }) => {
  return joinTextblockForward(state, dispatch);
};
function isMacOS() {
  return typeof navigator !== "undefined" ? /Mac/.test(navigator.platform) : false;
}
function normalizeKeyName2(name) {
  const parts = name.split(/-(?!$)/);
  let result = parts[parts.length - 1];
  if (result === "Space") {
    result = " ";
  }
  let alt;
  let ctrl;
  let shift2;
  let meta;
  for (let i = 0; i < parts.length - 1; i += 1) {
    const mod = parts[i];
    if (/^(cmd|meta|m)$/i.test(mod)) {
      meta = true;
    } else if (/^a(lt)?$/i.test(mod)) {
      alt = true;
    } else if (/^(c|ctrl|control)$/i.test(mod)) {
      ctrl = true;
    } else if (/^s(hift)?$/i.test(mod)) {
      shift2 = true;
    } else if (/^mod$/i.test(mod)) {
      if (isiOS() || isMacOS()) {
        meta = true;
      } else {
        ctrl = true;
      }
    } else {
      throw new Error(`Unrecognized modifier name: ${mod}`);
    }
  }
  if (alt) {
    result = `Alt-${result}`;
  }
  if (ctrl) {
    result = `Ctrl-${result}`;
  }
  if (meta) {
    result = `Meta-${result}`;
  }
  if (shift2) {
    result = `Shift-${result}`;
  }
  return result;
}
var keyboardShortcut = (name) => ({ editor, view, tr: tr2, dispatch }) => {
  const keys3 = normalizeKeyName2(name).split(/-(?!$)/);
  const key = keys3.find((item) => !["Alt", "Ctrl", "Meta", "Shift"].includes(item));
  const event = new KeyboardEvent("keydown", {
    key: key === "Space" ? " " : key,
    altKey: keys3.includes("Alt"),
    ctrlKey: keys3.includes("Ctrl"),
    metaKey: keys3.includes("Meta"),
    shiftKey: keys3.includes("Shift"),
    bubbles: true,
    cancelable: true
  });
  const capturedTransaction = editor.captureTransaction(() => {
    view.someProp("handleKeyDown", (f) => f(view, event));
  });
  capturedTransaction == null ? void 0 : capturedTransaction.steps.forEach((step) => {
    const newStep = step.map(tr2.mapping);
    if (newStep && dispatch) {
      tr2.maybeStep(newStep);
    }
  });
  return true;
};
function isNodeActive(state, typeOrName, attributes = {}) {
  const { from: from2, to, empty: empty2 } = state.selection;
  const type = typeOrName ? getNodeType(typeOrName, state.schema) : null;
  const nodeRanges = [];
  state.doc.nodesBetween(from2, to, (node, pos) => {
    if (node.isText) {
      return;
    }
    const relativeFrom = Math.max(from2, pos);
    const relativeTo = Math.min(to, pos + node.nodeSize);
    nodeRanges.push({
      node,
      from: relativeFrom,
      to: relativeTo
    });
  });
  const selectionRange = to - from2;
  const matchedNodeRanges = nodeRanges.filter((nodeRange) => {
    if (!type) {
      return true;
    }
    return type.name === nodeRange.node.type.name;
  }).filter((nodeRange) => objectIncludes(nodeRange.node.attrs, attributes, { strict: false }));
  if (empty2) {
    return !!matchedNodeRanges.length;
  }
  const range = matchedNodeRanges.reduce((sum, nodeRange) => sum + nodeRange.to - nodeRange.from, 0);
  return range >= selectionRange;
}
var lift3 = (typeOrName, attributes = {}) => ({ state, dispatch }) => {
  const type = getNodeType(typeOrName, state.schema);
  const isActive2 = isNodeActive(state, type, attributes);
  if (!isActive2) {
    return false;
  }
  return lift2(state, dispatch);
};
var liftEmptyBlock2 = () => ({ state, dispatch }) => {
  return liftEmptyBlock(state, dispatch);
};
var liftListItem2 = (typeOrName) => ({ state, dispatch }) => {
  const type = getNodeType(typeOrName, state.schema);
  return liftListItem(type)(state, dispatch);
};
var newlineInCode2 = () => ({ state, dispatch }) => {
  return newlineInCode(state, dispatch);
};
function getSchemaTypeNameByName(name, schema) {
  if (schema.nodes[name]) {
    return "node";
  }
  if (schema.marks[name]) {
    return "mark";
  }
  return null;
}
function deleteProps(obj, propOrProps) {
  const props = typeof propOrProps === "string" ? [propOrProps] : propOrProps;
  return Object.keys(obj).reduce((newObj, prop) => {
    if (!props.includes(prop)) {
      newObj[prop] = obj[prop];
    }
    return newObj;
  }, {});
}
var resetAttributes = (typeOrName, attributes) => ({ tr: tr2, state, dispatch }) => {
  let nodeType = null;
  let markType = null;
  const schemaType = getSchemaTypeNameByName(
    typeof typeOrName === "string" ? typeOrName : typeOrName.name,
    state.schema
  );
  if (!schemaType) {
    return false;
  }
  if (schemaType === "node") {
    nodeType = getNodeType(typeOrName, state.schema);
  }
  if (schemaType === "mark") {
    markType = getMarkType(typeOrName, state.schema);
  }
  let canReset = false;
  tr2.selection.ranges.forEach((range) => {
    state.doc.nodesBetween(range.$from.pos, range.$to.pos, (node, pos) => {
      if (nodeType && nodeType === node.type) {
        canReset = true;
        if (dispatch) {
          tr2.setNodeMarkup(pos, void 0, deleteProps(node.attrs, attributes));
        }
      }
      if (markType && node.marks.length) {
        node.marks.forEach((mark) => {
          if (markType === mark.type) {
            canReset = true;
            if (dispatch) {
              tr2.addMark(pos, pos + node.nodeSize, markType.create(deleteProps(mark.attrs, attributes)));
            }
          }
        });
      }
    });
  });
  return canReset;
};
var scrollIntoView = () => ({ tr: tr2, dispatch }) => {
  if (dispatch) {
    tr2.scrollIntoView();
  }
  return true;
};
var selectAll2 = () => ({ tr: tr2, dispatch }) => {
  if (dispatch) {
    const selection = new AllSelection(tr2.doc);
    tr2.setSelection(selection);
  }
  return true;
};
var selectNodeBackward2 = () => ({ state, dispatch }) => {
  return selectNodeBackward(state, dispatch);
};
var selectNodeForward2 = () => ({ state, dispatch }) => {
  return selectNodeForward(state, dispatch);
};
var selectParentNode2 = () => ({ state, dispatch }) => {
  return selectParentNode(state, dispatch);
};
var selectTextblockEnd2 = () => ({ state, dispatch }) => {
  return selectTextblockEnd(state, dispatch);
};
var selectTextblockStart2 = () => ({ state, dispatch }) => {
  return selectTextblockStart(state, dispatch);
};
function createDocument2(content, schema, parseOptions = {}, options = {}) {
  return createNodeFromContent(content, schema, {
    slice: false,
    parseOptions,
    errorOnInvalidContent: options.errorOnInvalidContent
  });
}
var setContent = (content, { errorOnInvalidContent, emitUpdate = true, parseOptions = {} } = {}) => ({ editor, tr: tr2, dispatch, commands }) => {
  const { doc: doc3 } = tr2;
  if (parseOptions.preserveWhitespace !== "full") {
    const document2 = createDocument2(content, editor.schema, parseOptions, {
      errorOnInvalidContent: errorOnInvalidContent != null ? errorOnInvalidContent : editor.options.enableContentCheck
    });
    if (dispatch) {
      tr2.replaceWith(0, doc3.content.size, document2).setMeta("preventUpdate", !emitUpdate);
    }
    return true;
  }
  if (dispatch) {
    tr2.setMeta("preventUpdate", !emitUpdate);
  }
  return commands.insertContentAt({ from: 0, to: doc3.content.size }, content, {
    parseOptions,
    errorOnInvalidContent: errorOnInvalidContent != null ? errorOnInvalidContent : editor.options.enableContentCheck
  });
};
function getMarkAttributes(state, typeOrName) {
  const type = getMarkType(typeOrName, state.schema);
  const { from: from2, to, empty: empty2 } = state.selection;
  const marks = [];
  if (empty2) {
    if (state.storedMarks) {
      marks.push(...state.storedMarks);
    }
    marks.push(...state.selection.$head.marks());
  } else {
    state.doc.nodesBetween(from2, to, (node) => {
      marks.push(...node.marks);
    });
  }
  const mark = marks.find((markItem) => markItem.type.name === type.name);
  if (!mark) {
    return {};
  }
  return { ...mark.attrs };
}
function combineTransactionSteps(oldDoc, transactions) {
  const transform = new Transform(oldDoc);
  transactions.forEach((transaction) => {
    transaction.steps.forEach((step) => {
      transform.step(step);
    });
  });
  return transform;
}
function defaultBlockAt2(match) {
  for (let i = 0; i < match.edgeCount; i += 1) {
    const { type } = match.edge(i);
    if (type.isTextblock && !type.hasRequiredAttrs()) {
      return type;
    }
  }
  return null;
}
function findChildrenInRange(node, range, predicate) {
  const nodesWithPos = [];
  node.nodesBetween(range.from, range.to, (child, pos) => {
    if (predicate(child)) {
      nodesWithPos.push({
        node: child,
        pos
      });
    }
  });
  return nodesWithPos;
}
function findParentNodeClosestToPos($pos, predicate) {
  for (let i = $pos.depth; i > 0; i -= 1) {
    const node = $pos.node(i);
    if (predicate(node)) {
      return {
        pos: i > 0 ? $pos.before(i) : 0,
        start: $pos.start(i),
        depth: i,
        node
      };
    }
  }
}
function findParentNode(predicate) {
  return (selection) => findParentNodeClosestToPos(selection.$from, predicate);
}
function getExtensionField(extension, field, context) {
  if (extension.config[field] === void 0 && extension.parent) {
    return getExtensionField(extension.parent, field, context);
  }
  if (typeof extension.config[field] === "function") {
    const value = extension.config[field].bind({
      ...context,
      parent: extension.parent ? getExtensionField(extension.parent, field, context) : null
    });
    return value;
  }
  return extension.config[field];
}
function flattenExtensions(extensions) {
  return extensions.map((extension) => {
    const context = {
      name: extension.name,
      options: extension.options,
      storage: extension.storage
    };
    const addExtensions = getExtensionField(extension, "addExtensions", context);
    if (addExtensions) {
      return [extension, ...flattenExtensions(addExtensions())];
    }
    return extension;
  }).flat(10);
}
function getHTMLFromFragment(fragment, schema) {
  const documentFragment = DOMSerializer.fromSchema(schema).serializeFragment(fragment);
  const temporaryDocument = document.implementation.createHTMLDocument();
  const container = temporaryDocument.createElement("div");
  container.appendChild(documentFragment);
  return container.innerHTML;
}
function isFunction(value) {
  return typeof value === "function";
}
function callOrReturn(value, context = void 0, ...props) {
  if (isFunction(value)) {
    if (context) {
      return value.bind(context)(...props);
    }
    return value(...props);
  }
  return value;
}
function isEmptyObject(value = {}) {
  return Object.keys(value).length === 0 && value.constructor === Object;
}
function splitExtensions(extensions) {
  const baseExtensions = extensions.filter((extension) => extension.type === "extension");
  const nodeExtensions = extensions.filter((extension) => extension.type === "node");
  const markExtensions = extensions.filter((extension) => extension.type === "mark");
  return {
    baseExtensions,
    nodeExtensions,
    markExtensions
  };
}
function getAttributesFromExtensions(extensions) {
  const extensionAttributes = [];
  const { nodeExtensions, markExtensions } = splitExtensions(extensions);
  const nodeAndMarkExtensions = [...nodeExtensions, ...markExtensions];
  const defaultAttribute = {
    default: null,
    validate: void 0,
    rendered: true,
    renderHTML: null,
    parseHTML: null,
    keepOnSplit: true,
    isRequired: false
  };
  extensions.forEach((extension) => {
    const context = {
      name: extension.name,
      options: extension.options,
      storage: extension.storage,
      extensions: nodeAndMarkExtensions
    };
    const addGlobalAttributes = getExtensionField(
      extension,
      "addGlobalAttributes",
      context
    );
    if (!addGlobalAttributes) {
      return;
    }
    const globalAttributes = addGlobalAttributes();
    globalAttributes.forEach((globalAttribute) => {
      globalAttribute.types.forEach((type) => {
        Object.entries(globalAttribute.attributes).forEach(([name, attribute]) => {
          extensionAttributes.push({
            type,
            name,
            attribute: {
              ...defaultAttribute,
              ...attribute
            }
          });
        });
      });
    });
  });
  nodeAndMarkExtensions.forEach((extension) => {
    const context = {
      name: extension.name,
      options: extension.options,
      storage: extension.storage
    };
    const addAttributes = getExtensionField(
      extension,
      "addAttributes",
      context
    );
    if (!addAttributes) {
      return;
    }
    const attributes = addAttributes();
    Object.entries(attributes).forEach(([name, attribute]) => {
      const mergedAttr = {
        ...defaultAttribute,
        ...attribute
      };
      if (typeof (mergedAttr == null ? void 0 : mergedAttr.default) === "function") {
        mergedAttr.default = mergedAttr.default();
      }
      if ((mergedAttr == null ? void 0 : mergedAttr.isRequired) && (mergedAttr == null ? void 0 : mergedAttr.default) === void 0) {
        delete mergedAttr.default;
      }
      extensionAttributes.push({
        type: extension.name,
        name,
        attribute: mergedAttr
      });
    });
  });
  return extensionAttributes;
}
function mergeAttributes(...objects) {
  return objects.filter((item) => !!item).reduce((items, item) => {
    const mergedAttributes = { ...items };
    Object.entries(item).forEach(([key, value]) => {
      const exists = mergedAttributes[key];
      if (!exists) {
        mergedAttributes[key] = value;
        return;
      }
      if (key === "class") {
        const valueClasses = value ? String(value).split(" ") : [];
        const existingClasses = mergedAttributes[key] ? mergedAttributes[key].split(" ") : [];
        const insertClasses = valueClasses.filter((valueClass) => !existingClasses.includes(valueClass));
        mergedAttributes[key] = [...existingClasses, ...insertClasses].join(" ");
      } else if (key === "style") {
        const newStyles = value ? value.split(";").map((style2) => style2.trim()).filter(Boolean) : [];
        const existingStyles = mergedAttributes[key] ? mergedAttributes[key].split(";").map((style2) => style2.trim()).filter(Boolean) : [];
        const styleMap2 = /* @__PURE__ */ new Map();
        existingStyles.forEach((style2) => {
          const [property, val] = style2.split(":").map((part) => part.trim());
          styleMap2.set(property, val);
        });
        newStyles.forEach((style2) => {
          const [property, val] = style2.split(":").map((part) => part.trim());
          styleMap2.set(property, val);
        });
        mergedAttributes[key] = Array.from(styleMap2.entries()).map(([property, val]) => `${property}: ${val}`).join("; ");
      } else {
        mergedAttributes[key] = value;
      }
    });
    return mergedAttributes;
  }, {});
}
function getRenderedAttributes(nodeOrMark, extensionAttributes) {
  return extensionAttributes.filter((attribute) => attribute.type === nodeOrMark.type.name).filter((item) => item.attribute.rendered).map((item) => {
    if (!item.attribute.renderHTML) {
      return {
        [item.name]: nodeOrMark.attrs[item.name]
      };
    }
    return item.attribute.renderHTML(nodeOrMark.attrs) || {};
  }).reduce((attributes, attribute) => mergeAttributes(attributes, attribute), {});
}
function fromString(value) {
  if (typeof value !== "string") {
    return value;
  }
  if (value.match(/^[+-]?(?:\d*\.)?\d+$/)) {
    return Number(value);
  }
  if (value === "true") {
    return true;
  }
  if (value === "false") {
    return false;
  }
  return value;
}
function injectExtensionAttributesToParseRule(parseRule, extensionAttributes) {
  if ("style" in parseRule) {
    return parseRule;
  }
  return {
    ...parseRule,
    getAttrs: (node) => {
      const oldAttributes = parseRule.getAttrs ? parseRule.getAttrs(node) : parseRule.attrs;
      if (oldAttributes === false) {
        return false;
      }
      const newAttributes = extensionAttributes.reduce((items, item) => {
        const value = item.attribute.parseHTML ? item.attribute.parseHTML(node) : fromString(node.getAttribute(item.name));
        if (value === null || value === void 0) {
          return items;
        }
        return {
          ...items,
          [item.name]: value
        };
      }, {});
      return { ...oldAttributes, ...newAttributes };
    }
  };
}
function cleanUpSchemaItem(data) {
  return Object.fromEntries(
    // @ts-ignore
    Object.entries(data).filter(([key, value]) => {
      if (key === "attrs" && isEmptyObject(value)) {
        return false;
      }
      return value !== null && value !== void 0;
    })
  );
}
function buildAttributeSpec(extensionAttribute) {
  var _a, _b;
  const spec = {};
  if (!((_a = extensionAttribute == null ? void 0 : extensionAttribute.attribute) == null ? void 0 : _a.isRequired) && "default" in ((extensionAttribute == null ? void 0 : extensionAttribute.attribute) || {})) {
    spec.default = extensionAttribute.attribute.default;
  }
  if (((_b = extensionAttribute == null ? void 0 : extensionAttribute.attribute) == null ? void 0 : _b.validate) !== void 0) {
    spec.validate = extensionAttribute.attribute.validate;
  }
  return [extensionAttribute.name, spec];
}
function getSchemaByResolvedExtensions(extensions, editor) {
  var _a;
  const allAttributes = getAttributesFromExtensions(extensions);
  const { nodeExtensions, markExtensions } = splitExtensions(extensions);
  const topNode = (_a = nodeExtensions.find((extension) => getExtensionField(extension, "topNode"))) == null ? void 0 : _a.name;
  const nodes = Object.fromEntries(
    nodeExtensions.map((extension) => {
      const extensionAttributes = allAttributes.filter((attribute) => attribute.type === extension.name);
      const context = {
        name: extension.name,
        options: extension.options,
        storage: extension.storage,
        editor
      };
      const extraNodeFields = extensions.reduce((fields, e) => {
        const extendNodeSchema = getExtensionField(e, "extendNodeSchema", context);
        return {
          ...fields,
          ...extendNodeSchema ? extendNodeSchema(extension) : {}
        };
      }, {});
      const schema = cleanUpSchemaItem({
        ...extraNodeFields,
        content: callOrReturn(getExtensionField(extension, "content", context)),
        marks: callOrReturn(getExtensionField(extension, "marks", context)),
        group: callOrReturn(getExtensionField(extension, "group", context)),
        inline: callOrReturn(getExtensionField(extension, "inline", context)),
        atom: callOrReturn(getExtensionField(extension, "atom", context)),
        selectable: callOrReturn(getExtensionField(extension, "selectable", context)),
        draggable: callOrReturn(getExtensionField(extension, "draggable", context)),
        code: callOrReturn(getExtensionField(extension, "code", context)),
        whitespace: callOrReturn(getExtensionField(extension, "whitespace", context)),
        linebreakReplacement: callOrReturn(
          getExtensionField(extension, "linebreakReplacement", context)
        ),
        defining: callOrReturn(getExtensionField(extension, "defining", context)),
        isolating: callOrReturn(getExtensionField(extension, "isolating", context)),
        attrs: Object.fromEntries(extensionAttributes.map(buildAttributeSpec))
      });
      const parseHTML = callOrReturn(getExtensionField(extension, "parseHTML", context));
      if (parseHTML) {
        schema.parseDOM = parseHTML.map(
          (parseRule) => injectExtensionAttributesToParseRule(parseRule, extensionAttributes)
        );
      }
      const renderHTML = getExtensionField(extension, "renderHTML", context);
      if (renderHTML) {
        schema.toDOM = (node) => renderHTML({
          node,
          HTMLAttributes: getRenderedAttributes(node, extensionAttributes)
        });
      }
      const renderText = getExtensionField(extension, "renderText", context);
      if (renderText) {
        schema.toText = renderText;
      }
      return [extension.name, schema];
    })
  );
  const marks = Object.fromEntries(
    markExtensions.map((extension) => {
      const extensionAttributes = allAttributes.filter((attribute) => attribute.type === extension.name);
      const context = {
        name: extension.name,
        options: extension.options,
        storage: extension.storage,
        editor
      };
      const extraMarkFields = extensions.reduce((fields, e) => {
        const extendMarkSchema = getExtensionField(e, "extendMarkSchema", context);
        return {
          ...fields,
          ...extendMarkSchema ? extendMarkSchema(extension) : {}
        };
      }, {});
      const schema = cleanUpSchemaItem({
        ...extraMarkFields,
        inclusive: callOrReturn(getExtensionField(extension, "inclusive", context)),
        excludes: callOrReturn(getExtensionField(extension, "excludes", context)),
        group: callOrReturn(getExtensionField(extension, "group", context)),
        spanning: callOrReturn(getExtensionField(extension, "spanning", context)),
        code: callOrReturn(getExtensionField(extension, "code", context)),
        attrs: Object.fromEntries(extensionAttributes.map(buildAttributeSpec))
      });
      const parseHTML = callOrReturn(getExtensionField(extension, "parseHTML", context));
      if (parseHTML) {
        schema.parseDOM = parseHTML.map(
          (parseRule) => injectExtensionAttributesToParseRule(parseRule, extensionAttributes)
        );
      }
      const renderHTML = getExtensionField(extension, "renderHTML", context);
      if (renderHTML) {
        schema.toDOM = (mark) => renderHTML({
          mark,
          HTMLAttributes: getRenderedAttributes(mark, extensionAttributes)
        });
      }
      return [extension.name, schema];
    })
  );
  return new Schema({
    topNode,
    nodes,
    marks
  });
}
function findDuplicates(items) {
  const filtered = items.filter((el, index) => items.indexOf(el) !== index);
  return Array.from(new Set(filtered));
}
function sortExtensions(extensions) {
  const defaultPriority = 100;
  return extensions.sort((a2, b2) => {
    const priorityA = getExtensionField(a2, "priority") || defaultPriority;
    const priorityB = getExtensionField(b2, "priority") || defaultPriority;
    if (priorityA > priorityB) {
      return -1;
    }
    if (priorityA < priorityB) {
      return 1;
    }
    return 0;
  });
}
function resolveExtensions(extensions) {
  const resolvedExtensions = sortExtensions(flattenExtensions(extensions));
  const duplicatedNames = findDuplicates(resolvedExtensions.map((extension) => extension.name));
  if (duplicatedNames.length) {
    console.warn(
      `[tiptap warn]: Duplicate extension names found: [${duplicatedNames.map((item) => `'${item}'`).join(", ")}]. This can lead to issues.`
    );
  }
  return resolvedExtensions;
}
function getSchema(extensions, editor) {
  const resolvedExtensions = resolveExtensions(extensions);
  return getSchemaByResolvedExtensions(resolvedExtensions, editor);
}
function generateHTML(doc3, extensions) {
  const schema = getSchema(extensions);
  const contentNode = Node2.fromJSON(schema, doc3);
  return getHTMLFromFragment(contentNode.content, schema);
}
function getTextBetween(startNode, range, options) {
  const { from: from2, to } = range;
  const { blockSeparator = "\n\n", textSerializers = {} } = options || {};
  let text5 = "";
  startNode.nodesBetween(from2, to, (node, pos, parent, index) => {
    var _a;
    if (node.isBlock && pos > from2) {
      text5 += blockSeparator;
    }
    const textSerializer = textSerializers == null ? void 0 : textSerializers[node.type.name];
    if (textSerializer) {
      if (parent) {
        text5 += textSerializer({
          node,
          pos,
          parent,
          index,
          range
        });
      }
      return false;
    }
    if (node.isText) {
      text5 += (_a = node == null ? void 0 : node.text) == null ? void 0 : _a.slice(Math.max(from2, pos) - pos, to - pos);
    }
  });
  return text5;
}
function getText2(node, options) {
  const range = {
    from: 0,
    to: node.content.size
  };
  return getTextBetween(node, range, options);
}
function getTextSerializersFromSchema(schema) {
  return Object.fromEntries(
    Object.entries(schema.nodes).filter(([, node]) => node.spec.toText).map(([name, node]) => [name, node.spec.toText])
  );
}
function getNodeAttributes(state, typeOrName) {
  const type = getNodeType(typeOrName, state.schema);
  const { from: from2, to } = state.selection;
  const nodes = [];
  state.doc.nodesBetween(from2, to, (node2) => {
    nodes.push(node2);
  });
  const node = nodes.reverse().find((nodeItem) => nodeItem.type.name === type.name);
  if (!node) {
    return {};
  }
  return { ...node.attrs };
}
function getAttributes(state, typeOrName) {
  const schemaType = getSchemaTypeNameByName(
    typeof typeOrName === "string" ? typeOrName : typeOrName.name,
    state.schema
  );
  if (schemaType === "node") {
    return getNodeAttributes(state, typeOrName);
  }
  if (schemaType === "mark") {
    return getMarkAttributes(state, typeOrName);
  }
  return {};
}
function removeDuplicates(array, by = JSON.stringify) {
  const seen = {};
  return array.filter((item) => {
    const key = by(item);
    return Object.prototype.hasOwnProperty.call(seen, key) ? false : seen[key] = true;
  });
}
function simplifyChangedRanges(changes) {
  const uniqueChanges = removeDuplicates(changes);
  return uniqueChanges.length === 1 ? uniqueChanges : uniqueChanges.filter((change, index) => {
    const rest = uniqueChanges.filter((_10, i) => i !== index);
    return !rest.some((otherChange) => {
      return change.oldRange.from >= otherChange.oldRange.from && change.oldRange.to <= otherChange.oldRange.to && change.newRange.from >= otherChange.newRange.from && change.newRange.to <= otherChange.newRange.to;
    });
  });
}
function getChangedRanges(transform) {
  const { mapping, steps } = transform;
  const changes = [];
  mapping.maps.forEach((stepMap, index) => {
    const ranges = [];
    if (!stepMap.ranges.length) {
      const { from: from2, to } = steps[index];
      if (from2 === void 0 || to === void 0) {
        return;
      }
      ranges.push({ from: from2, to });
    } else {
      stepMap.forEach((from2, to) => {
        ranges.push({ from: from2, to });
      });
    }
    ranges.forEach(({ from: from2, to }) => {
      const newStart = mapping.slice(index).map(from2, -1);
      const newEnd = mapping.slice(index).map(to);
      const oldStart = mapping.invert().map(newStart, -1);
      const oldEnd = mapping.invert().map(newEnd);
      changes.push({
        oldRange: {
          from: oldStart,
          to: oldEnd
        },
        newRange: {
          from: newStart,
          to: newEnd
        }
      });
    });
  });
  return simplifyChangedRanges(changes);
}
function getMarksBetween(from2, to, doc3) {
  const marks = [];
  if (from2 === to) {
    doc3.resolve(from2).marks().forEach((mark) => {
      const $pos = doc3.resolve(from2);
      const range = getMarkRange($pos, mark.type);
      if (!range) {
        return;
      }
      marks.push({
        mark,
        ...range
      });
    });
  } else {
    doc3.nodesBetween(from2, to, (node, pos) => {
      if (!node || (node == null ? void 0 : node.nodeSize) === void 0) {
        return;
      }
      marks.push(
        ...node.marks.map((mark) => ({
          from: pos,
          to: pos + node.nodeSize,
          mark
        }))
      );
    });
  }
  return marks;
}
var getNodeAtPosition = (state, typeOrName, pos, maxDepth = 20) => {
  const $pos = state.doc.resolve(pos);
  let currentDepth = maxDepth;
  let node = null;
  while (currentDepth > 0 && node === null) {
    const currentNode = $pos.node(currentDepth);
    if ((currentNode == null ? void 0 : currentNode.type.name) === typeOrName) {
      node = currentNode;
    } else {
      currentDepth -= 1;
    }
  }
  return [node, currentDepth];
};
function getSchemaTypeByName(name, schema) {
  return schema.nodes[name] || schema.marks[name] || null;
}
function getSplittedAttributes(extensionAttributes, typeName, attributes) {
  return Object.fromEntries(
    Object.entries(attributes).filter(([name]) => {
      const extensionAttribute = extensionAttributes.find((item) => {
        return item.type === typeName && item.name === name;
      });
      if (!extensionAttribute) {
        return false;
      }
      return extensionAttribute.attribute.keepOnSplit;
    })
  );
}
var getTextContentFromNodes = ($from, maxMatch = 500) => {
  let textBefore = "";
  const sliceEndPos = $from.parentOffset;
  $from.parent.nodesBetween(Math.max(0, sliceEndPos - maxMatch), sliceEndPos, (node, pos, parent, index) => {
    var _a, _b;
    const chunk = ((_b = (_a = node.type.spec).toText) == null ? void 0 : _b.call(_a, {
      node,
      pos,
      parent,
      index
    })) || node.textContent || "%leaf%";
    textBefore += node.isAtom && !node.isText ? chunk : chunk.slice(0, Math.max(0, sliceEndPos - pos));
  });
  return textBefore;
};
function isMarkActive(state, typeOrName, attributes = {}) {
  const { empty: empty2, ranges } = state.selection;
  const type = typeOrName ? getMarkType(typeOrName, state.schema) : null;
  if (empty2) {
    return !!(state.storedMarks || state.selection.$from.marks()).filter((mark) => {
      if (!type) {
        return true;
      }
      return type.name === mark.type.name;
    }).find((mark) => objectIncludes(mark.attrs, attributes, { strict: false }));
  }
  let selectionRange = 0;
  const markRanges = [];
  ranges.forEach(({ $from, $to }) => {
    const from2 = $from.pos;
    const to = $to.pos;
    state.doc.nodesBetween(from2, to, (node, pos) => {
      if (!node.isText && !node.marks.length) {
        return;
      }
      const relativeFrom = Math.max(from2, pos);
      const relativeTo = Math.min(to, pos + node.nodeSize);
      const range2 = relativeTo - relativeFrom;
      selectionRange += range2;
      markRanges.push(
        ...node.marks.map((mark) => ({
          mark,
          from: relativeFrom,
          to: relativeTo
        }))
      );
    });
  });
  if (selectionRange === 0) {
    return false;
  }
  const matchedRange = markRanges.filter((markRange) => {
    if (!type) {
      return true;
    }
    return type.name === markRange.mark.type.name;
  }).filter((markRange) => objectIncludes(markRange.mark.attrs, attributes, { strict: false })).reduce((sum, markRange) => sum + markRange.to - markRange.from, 0);
  const excludedRange = markRanges.filter((markRange) => {
    if (!type) {
      return true;
    }
    return markRange.mark.type !== type && markRange.mark.type.excludes(type);
  }).reduce((sum, markRange) => sum + markRange.to - markRange.from, 0);
  const range = matchedRange > 0 ? matchedRange + excludedRange : matchedRange;
  return range >= selectionRange;
}
function isActive(state, name, attributes = {}) {
  if (!name) {
    return isNodeActive(state, null, attributes) || isMarkActive(state, null, attributes);
  }
  const schemaType = getSchemaTypeNameByName(name, state.schema);
  if (schemaType === "node") {
    return isNodeActive(state, name, attributes);
  }
  if (schemaType === "mark") {
    return isMarkActive(state, name, attributes);
  }
  return false;
}
var isAtEndOfNode = (state, nodeType) => {
  const { $from, $to, $anchor } = state.selection;
  if (nodeType) {
    const parentNode2 = findParentNode((node) => node.type.name === nodeType)(state.selection);
    if (!parentNode2) {
      return false;
    }
    const $parentPos = state.doc.resolve(parentNode2.pos + 1);
    if ($anchor.pos + 1 === $parentPos.end()) {
      return true;
    }
    return false;
  }
  if ($to.parentOffset < $to.parent.nodeSize - 2 || $from.pos !== $to.pos) {
    return false;
  }
  return true;
};
var isAtStartOfNode = (state) => {
  const { $from, $to } = state.selection;
  if ($from.parentOffset > 0 || $from.pos !== $to.pos) {
    return false;
  }
  return true;
};
function isExtensionRulesEnabled(extension, enabled) {
  if (Array.isArray(enabled)) {
    return enabled.some((enabledExtension) => {
      const name = typeof enabledExtension === "string" ? enabledExtension : enabledExtension.name;
      return name === extension.name;
    });
  }
  return enabled;
}
function isList(name, extensions) {
  const { nodeExtensions } = splitExtensions(extensions);
  const extension = nodeExtensions.find((item) => item.name === name);
  if (!extension) {
    return false;
  }
  const context = {
    name: extension.name,
    options: extension.options,
    storage: extension.storage
  };
  const group = callOrReturn(getExtensionField(extension, "group", context));
  if (typeof group !== "string") {
    return false;
  }
  return group.split(" ").includes("list");
}
function isNodeEmpty(node, {
  checkChildren = true,
  ignoreWhitespace = false
} = {}) {
  var _a;
  if (ignoreWhitespace) {
    if (node.type.name === "hardBreak") {
      return true;
    }
    if (node.isText) {
      return /^\s*$/m.test((_a = node.text) != null ? _a : "");
    }
  }
  if (node.isText) {
    return !node.text;
  }
  if (node.isAtom || node.isLeaf) {
    return false;
  }
  if (node.content.childCount === 0) {
    return true;
  }
  if (checkChildren) {
    let isContentEmpty = true;
    node.content.forEach((childNode) => {
      if (isContentEmpty === false) {
        return;
      }
      if (!isNodeEmpty(childNode, { ignoreWhitespace, checkChildren })) {
        isContentEmpty = false;
      }
    });
    return isContentEmpty;
  }
  return false;
}
function isNodeSelection(value) {
  return value instanceof NodeSelection;
}
var MappablePosition = class _MappablePosition {
  constructor(position) {
    this.position = position;
  }
  /**
   * Creates a MappablePosition from a JSON object.
   */
  static fromJSON(json) {
    return new _MappablePosition(json.position);
  }
  /**
   * Converts the MappablePosition to a JSON object.
   */
  toJSON() {
    return {
      position: this.position
    };
  }
};
function getUpdatedPosition(position, transaction) {
  const mapResult = transaction.mapping.mapResult(position.position);
  return {
    position: new MappablePosition(mapResult.pos),
    mapResult
  };
}
function createMappablePosition(position) {
  return new MappablePosition(position);
}
function canSetMark(state, tr2, newMarkType) {
  var _a;
  const { selection } = tr2;
  let cursor = null;
  if (isTextSelection(selection)) {
    cursor = selection.$cursor;
  }
  if (cursor) {
    const currentMarks = (_a = state.storedMarks) != null ? _a : cursor.marks();
    const parentAllowsMarkType = cursor.parent.type.allowsMarkType(newMarkType);
    return parentAllowsMarkType && (!!newMarkType.isInSet(currentMarks) || !currentMarks.some((mark) => mark.type.excludes(newMarkType)));
  }
  const { ranges } = selection;
  return ranges.some(({ $from, $to }) => {
    let someNodeSupportsMark = $from.depth === 0 ? state.doc.inlineContent && state.doc.type.allowsMarkType(newMarkType) : false;
    state.doc.nodesBetween($from.pos, $to.pos, (node, _pos, parent) => {
      if (someNodeSupportsMark) {
        return false;
      }
      if (node.isInline) {
        const parentAllowsMarkType = !parent || parent.type.allowsMarkType(newMarkType);
        const currentMarksAllowMarkType = !!newMarkType.isInSet(node.marks) || !node.marks.some((otherMark) => otherMark.type.excludes(newMarkType));
        someNodeSupportsMark = parentAllowsMarkType && currentMarksAllowMarkType;
      }
      return !someNodeSupportsMark;
    });
    return someNodeSupportsMark;
  });
}
var setMark = (typeOrName, attributes = {}) => ({ tr: tr2, state, dispatch }) => {
  const { selection } = tr2;
  const { empty: empty2, ranges } = selection;
  const type = getMarkType(typeOrName, state.schema);
  if (dispatch) {
    if (empty2) {
      const oldAttributes = getMarkAttributes(state, type);
      tr2.addStoredMark(
        type.create({
          ...oldAttributes,
          ...attributes
        })
      );
    } else {
      ranges.forEach((range) => {
        const from2 = range.$from.pos;
        const to = range.$to.pos;
        state.doc.nodesBetween(from2, to, (node, pos) => {
          const trimmedFrom = Math.max(pos, from2);
          const trimmedTo = Math.min(pos + node.nodeSize, to);
          const someHasMark = node.marks.find((mark) => mark.type === type);
          if (someHasMark) {
            node.marks.forEach((mark) => {
              if (type === mark.type) {
                tr2.addMark(
                  trimmedFrom,
                  trimmedTo,
                  type.create({
                    ...mark.attrs,
                    ...attributes
                  })
                );
              }
            });
          } else {
            tr2.addMark(trimmedFrom, trimmedTo, type.create(attributes));
          }
        });
      });
    }
  }
  return canSetMark(state, tr2, type);
};
var setMeta = (key, value) => ({ tr: tr2 }) => {
  tr2.setMeta(key, value);
  return true;
};
var setNode = (typeOrName, attributes = {}) => ({ state, dispatch, chain }) => {
  const type = getNodeType(typeOrName, state.schema);
  let attributesToCopy;
  if (state.selection.$anchor.sameParent(state.selection.$head)) {
    attributesToCopy = state.selection.$anchor.parent.attrs;
  }
  if (!type.isTextblock) {
    console.warn('[tiptap warn]: Currently "setNode()" only supports text block nodes.');
    return false;
  }
  return chain().command(({ commands }) => {
    const canSetBlock = setBlockType2(type, { ...attributesToCopy, ...attributes })(state);
    if (canSetBlock) {
      return true;
    }
    return commands.clearNodes();
  }).command(({ state: updatedState }) => {
    return setBlockType2(type, { ...attributesToCopy, ...attributes })(updatedState, dispatch);
  }).run();
};
var setNodeSelection = (position) => ({ tr: tr2, dispatch }) => {
  if (dispatch) {
    const { doc: doc3 } = tr2;
    const from2 = minMax(position, 0, doc3.content.size);
    const selection = NodeSelection.create(doc3, from2);
    tr2.setSelection(selection);
  }
  return true;
};
var setTextDirection = (direction, position) => ({ tr: tr2, state, dispatch }) => {
  const { selection } = state;
  let from2;
  let to;
  if (typeof position === "number") {
    from2 = position;
    to = position;
  } else if (position && "from" in position && "to" in position) {
    from2 = position.from;
    to = position.to;
  } else {
    from2 = selection.from;
    to = selection.to;
  }
  if (dispatch) {
    tr2.doc.nodesBetween(from2, to, (node, pos) => {
      if (node.isText) {
        return;
      }
      tr2.setNodeMarkup(pos, void 0, {
        ...node.attrs,
        dir: direction
      });
    });
  }
  return true;
};
var setTextSelection = (position) => ({ tr: tr2, dispatch }) => {
  if (dispatch) {
    const { doc: doc3 } = tr2;
    const { from: from2, to } = typeof position === "number" ? { from: position, to: position } : position;
    const minPos = TextSelection.atStart(doc3).from;
    const maxPos = TextSelection.atEnd(doc3).to;
    const resolvedFrom = minMax(from2, minPos, maxPos);
    const resolvedEnd = minMax(to, minPos, maxPos);
    const selection = TextSelection.create(doc3, resolvedFrom, resolvedEnd);
    tr2.setSelection(selection);
  }
  return true;
};
var sinkListItem2 = (typeOrName) => ({ state, dispatch }) => {
  const type = getNodeType(typeOrName, state.schema);
  return sinkListItem(type)(state, dispatch);
};
function ensureMarks(state, splittableMarks) {
  const marks = state.storedMarks || state.selection.$to.parentOffset && state.selection.$from.marks();
  if (marks) {
    const filteredMarks = marks.filter((mark) => splittableMarks == null ? void 0 : splittableMarks.includes(mark.type.name));
    state.tr.ensureMarks(filteredMarks);
  }
}
var splitBlock2 = ({ keepMarks = true } = {}) => ({ tr: tr2, state, dispatch, editor }) => {
  const { selection, doc: doc3 } = tr2;
  const { $from, $to } = selection;
  const extensionAttributes = editor.extensionManager.attributes;
  const newAttributes = getSplittedAttributes(extensionAttributes, $from.node().type.name, $from.node().attrs);
  if (selection instanceof NodeSelection && selection.node.isBlock) {
    if (!$from.parentOffset || !canSplit(doc3, $from.pos)) {
      return false;
    }
    if (dispatch) {
      if (keepMarks) {
        ensureMarks(state, editor.extensionManager.splittableMarks);
      }
      tr2.split($from.pos).scrollIntoView();
    }
    return true;
  }
  if (!$from.parent.isBlock) {
    return false;
  }
  const atEnd = $to.parentOffset === $to.parent.content.size;
  const deflt3 = $from.depth === 0 ? void 0 : defaultBlockAt2($from.node(-1).contentMatchAt($from.indexAfter(-1)));
  let types = atEnd && deflt3 ? [
    {
      type: deflt3,
      attrs: newAttributes
    }
  ] : void 0;
  let can = canSplit(tr2.doc, tr2.mapping.map($from.pos), 1, types);
  if (!types && !can && canSplit(tr2.doc, tr2.mapping.map($from.pos), 1, deflt3 ? [{ type: deflt3 }] : void 0)) {
    can = true;
    types = deflt3 ? [
      {
        type: deflt3,
        attrs: newAttributes
      }
    ] : void 0;
  }
  if (dispatch) {
    if (can) {
      if (selection instanceof TextSelection) {
        tr2.deleteSelection();
      }
      tr2.split(tr2.mapping.map($from.pos), 1, types);
      if (deflt3 && !atEnd && !$from.parentOffset && $from.parent.type !== deflt3) {
        const first2 = tr2.mapping.map($from.before());
        const $first = tr2.doc.resolve(first2);
        if ($from.node(-1).canReplaceWith($first.index(), $first.index() + 1, deflt3)) {
          tr2.setNodeMarkup(tr2.mapping.map($from.before()), deflt3);
        }
      }
    }
    if (keepMarks) {
      ensureMarks(state, editor.extensionManager.splittableMarks);
    }
    tr2.scrollIntoView();
  }
  return can;
};
var splitListItem = (typeOrName, overrideAttrs = {}) => ({ tr: tr2, state, dispatch, editor }) => {
  var _a;
  const type = getNodeType(typeOrName, state.schema);
  const { $from, $to } = state.selection;
  const node = state.selection.node;
  if (node && node.isBlock || $from.depth < 2 || !$from.sameParent($to)) {
    return false;
  }
  const grandParent = $from.node(-1);
  if (grandParent.type !== type) {
    return false;
  }
  const extensionAttributes = editor.extensionManager.attributes;
  if ($from.parent.content.size === 0 && $from.node(-1).childCount === $from.indexAfter(-1)) {
    if ($from.depth === 2 || $from.node(-3).type !== type || $from.index(-2) !== $from.node(-2).childCount - 1) {
      return false;
    }
    if (dispatch) {
      let wrap2 = Fragment.empty;
      const depthBefore = $from.index(-1) ? 1 : $from.index(-2) ? 2 : 3;
      for (let d2 = $from.depth - depthBefore; d2 >= $from.depth - 3; d2 -= 1) {
        wrap2 = Fragment.from($from.node(d2).copy(wrap2));
      }
      const depthAfter = (
        // eslint-disable-next-line no-nested-ternary
        $from.indexAfter(-1) < $from.node(-2).childCount ? 1 : $from.indexAfter(-2) < $from.node(-3).childCount ? 2 : 3
      );
      const newNextTypeAttributes2 = {
        ...getSplittedAttributes(extensionAttributes, $from.node().type.name, $from.node().attrs),
        ...overrideAttrs
      };
      const nextType2 = ((_a = type.contentMatch.defaultType) == null ? void 0 : _a.createAndFill(newNextTypeAttributes2)) || void 0;
      wrap2 = wrap2.append(Fragment.from(type.createAndFill(null, nextType2) || void 0));
      const start = $from.before($from.depth - (depthBefore - 1));
      tr2.replace(start, $from.after(-depthAfter), new Slice(wrap2, 4 - depthBefore, 0));
      let sel = -1;
      tr2.doc.nodesBetween(start, tr2.doc.content.size, (n, pos) => {
        if (sel > -1) {
          return false;
        }
        if (n.isTextblock && n.content.size === 0) {
          sel = pos + 1;
        }
      });
      if (sel > -1) {
        tr2.setSelection(TextSelection.near(tr2.doc.resolve(sel)));
      }
      tr2.scrollIntoView();
    }
    return true;
  }
  const nextType = $to.pos === $from.end() ? grandParent.contentMatchAt(0).defaultType : null;
  const newTypeAttributes = {
    ...getSplittedAttributes(extensionAttributes, grandParent.type.name, grandParent.attrs),
    ...overrideAttrs
  };
  const newNextTypeAttributes = {
    ...getSplittedAttributes(extensionAttributes, $from.node().type.name, $from.node().attrs),
    ...overrideAttrs
  };
  tr2.delete($from.pos, $to.pos);
  const types = nextType ? [
    { type, attrs: newTypeAttributes },
    { type: nextType, attrs: newNextTypeAttributes }
  ] : [{ type, attrs: newTypeAttributes }];
  if (!canSplit(tr2.doc, $from.pos, 2)) {
    return false;
  }
  if (dispatch) {
    const { selection, storedMarks } = state;
    const { splittableMarks } = editor.extensionManager;
    const marks = storedMarks || selection.$to.parentOffset && selection.$from.marks();
    tr2.split($from.pos, 2, types).scrollIntoView();
    if (!marks || !dispatch) {
      return true;
    }
    const filteredMarks = marks.filter((mark) => splittableMarks.includes(mark.type.name));
    tr2.ensureMarks(filteredMarks);
  }
  return true;
};
var joinListBackwards = (tr2, listType) => {
  const list = findParentNode((node) => node.type === listType)(tr2.selection);
  if (!list) {
    return true;
  }
  const before = tr2.doc.resolve(Math.max(0, list.pos - 1)).before(list.depth);
  if (before === void 0) {
    return true;
  }
  const nodeBefore = tr2.doc.nodeAt(before);
  const canJoinBackwards = list.node.type === (nodeBefore == null ? void 0 : nodeBefore.type) && canJoin(tr2.doc, list.pos);
  if (!canJoinBackwards) {
    return true;
  }
  tr2.join(list.pos);
  return true;
};
var joinListForwards = (tr2, listType) => {
  const list = findParentNode((node) => node.type === listType)(tr2.selection);
  if (!list) {
    return true;
  }
  const after = tr2.doc.resolve(list.start).after(list.depth);
  if (after === void 0) {
    return true;
  }
  const nodeAfter = tr2.doc.nodeAt(after);
  const canJoinForwards = list.node.type === (nodeAfter == null ? void 0 : nodeAfter.type) && canJoin(tr2.doc, after);
  if (!canJoinForwards) {
    return true;
  }
  tr2.join(after);
  return true;
};
var toggleList = (listTypeOrName, itemTypeOrName, keepMarks, attributes = {}) => ({ editor, tr: tr2, state, dispatch, chain, commands, can }) => {
  const { extensions, splittableMarks } = editor.extensionManager;
  const listType = getNodeType(listTypeOrName, state.schema);
  const itemType = getNodeType(itemTypeOrName, state.schema);
  const { selection, storedMarks } = state;
  const { $from, $to } = selection;
  const range = $from.blockRange($to);
  const marks = storedMarks || selection.$to.parentOffset && selection.$from.marks();
  if (!range) {
    return false;
  }
  const parentList = findParentNode((node) => isList(node.type.name, extensions))(selection);
  if (range.depth >= 1 && parentList && range.depth - parentList.depth <= 1) {
    if (parentList.node.type === listType) {
      return commands.liftListItem(itemType);
    }
    if (isList(parentList.node.type.name, extensions) && listType.validContent(parentList.node.content) && dispatch) {
      return chain().command(() => {
        tr2.setNodeMarkup(parentList.pos, listType);
        return true;
      }).command(() => joinListBackwards(tr2, listType)).command(() => joinListForwards(tr2, listType)).run();
    }
  }
  if (!keepMarks || !marks || !dispatch) {
    return chain().command(() => {
      const canWrapInList = can().wrapInList(listType, attributes);
      if (canWrapInList) {
        return true;
      }
      return commands.clearNodes();
    }).wrapInList(listType, attributes).command(() => joinListBackwards(tr2, listType)).command(() => joinListForwards(tr2, listType)).run();
  }
  return chain().command(() => {
    const canWrapInList = can().wrapInList(listType, attributes);
    const filteredMarks = marks.filter((mark) => splittableMarks.includes(mark.type.name));
    tr2.ensureMarks(filteredMarks);
    if (canWrapInList) {
      return true;
    }
    return commands.clearNodes();
  }).wrapInList(listType, attributes).command(() => joinListBackwards(tr2, listType)).command(() => joinListForwards(tr2, listType)).run();
};
var toggleMark = (typeOrName, attributes = {}, options = {}) => ({ state, commands }) => {
  const { extendEmptyMarkRange = false } = options;
  const type = getMarkType(typeOrName, state.schema);
  const isActive2 = isMarkActive(state, type, attributes);
  if (isActive2) {
    return commands.unsetMark(type, { extendEmptyMarkRange });
  }
  return commands.setMark(type, attributes);
};
var toggleNode = (typeOrName, toggleTypeOrName, attributes = {}) => ({ state, commands }) => {
  const type = getNodeType(typeOrName, state.schema);
  const toggleType = getNodeType(toggleTypeOrName, state.schema);
  const isActive2 = isNodeActive(state, type, attributes);
  let attributesToCopy;
  if (state.selection.$anchor.sameParent(state.selection.$head)) {
    attributesToCopy = state.selection.$anchor.parent.attrs;
  }
  if (isActive2) {
    return commands.setNode(toggleType, attributesToCopy);
  }
  return commands.setNode(type, { ...attributesToCopy, ...attributes });
};
var toggleWrap = (typeOrName, attributes = {}) => ({ state, commands }) => {
  const type = getNodeType(typeOrName, state.schema);
  const isActive2 = isNodeActive(state, type, attributes);
  if (isActive2) {
    return commands.lift(type);
  }
  return commands.wrapIn(type, attributes);
};
var undoInputRule = () => ({ state, dispatch }) => {
  const plugins = state.plugins;
  for (let i = 0; i < plugins.length; i += 1) {
    const plugin = plugins[i];
    let undoable;
    if (plugin.spec.isInputRules && (undoable = plugin.getState(state))) {
      if (dispatch) {
        const tr2 = state.tr;
        const toUndo = undoable.transform;
        for (let j = toUndo.steps.length - 1; j >= 0; j -= 1) {
          tr2.step(toUndo.steps[j].invert(toUndo.docs[j]));
        }
        if (undoable.text) {
          const marks = tr2.doc.resolve(undoable.from).marks();
          tr2.replaceWith(undoable.from, undoable.to, state.schema.text(undoable.text, marks));
        } else {
          tr2.delete(undoable.from, undoable.to);
        }
      }
      return true;
    }
  }
  return false;
};
var unsetAllMarks = () => ({ tr: tr2, dispatch }) => {
  const { selection } = tr2;
  const { empty: empty2, ranges } = selection;
  if (empty2) {
    return true;
  }
  if (dispatch) {
    ranges.forEach((range) => {
      tr2.removeMark(range.$from.pos, range.$to.pos);
    });
  }
  return true;
};
var unsetMark = (typeOrName, options = {}) => ({ tr: tr2, state, dispatch }) => {
  var _a;
  const { extendEmptyMarkRange = false } = options;
  const { selection } = tr2;
  const type = getMarkType(typeOrName, state.schema);
  const { $from, empty: empty2, ranges } = selection;
  if (!dispatch) {
    return true;
  }
  if (empty2 && extendEmptyMarkRange) {
    let { from: from2, to } = selection;
    const attrs = (_a = $from.marks().find((mark) => mark.type === type)) == null ? void 0 : _a.attrs;
    const range = getMarkRange($from, type, attrs);
    if (range) {
      from2 = range.from;
      to = range.to;
    }
    tr2.removeMark(from2, to, type);
  } else {
    ranges.forEach((range) => {
      tr2.removeMark(range.$from.pos, range.$to.pos, type);
    });
  }
  tr2.removeStoredMark(type);
  return true;
};
var unsetTextDirection = (position) => ({ tr: tr2, state, dispatch }) => {
  const { selection } = state;
  let from2;
  let to;
  if (typeof position === "number") {
    from2 = position;
    to = position;
  } else if (position && "from" in position && "to" in position) {
    from2 = position.from;
    to = position.to;
  } else {
    from2 = selection.from;
    to = selection.to;
  }
  if (dispatch) {
    tr2.doc.nodesBetween(from2, to, (node, pos) => {
      if (node.isText) {
        return;
      }
      const newAttrs = { ...node.attrs };
      delete newAttrs.dir;
      tr2.setNodeMarkup(pos, void 0, newAttrs);
    });
  }
  return true;
};
var updateAttributes = (typeOrName, attributes = {}) => ({ tr: tr2, state, dispatch }) => {
  let nodeType = null;
  let markType = null;
  const schemaType = getSchemaTypeNameByName(
    typeof typeOrName === "string" ? typeOrName : typeOrName.name,
    state.schema
  );
  if (!schemaType) {
    return false;
  }
  if (schemaType === "node") {
    nodeType = getNodeType(typeOrName, state.schema);
  }
  if (schemaType === "mark") {
    markType = getMarkType(typeOrName, state.schema);
  }
  let canUpdate = false;
  tr2.selection.ranges.forEach((range) => {
    const from2 = range.$from.pos;
    const to = range.$to.pos;
    let lastPos;
    let lastNode;
    let trimmedFrom;
    let trimmedTo;
    if (tr2.selection.empty) {
      state.doc.nodesBetween(from2, to, (node, pos) => {
        if (nodeType && nodeType === node.type) {
          canUpdate = true;
          trimmedFrom = Math.max(pos, from2);
          trimmedTo = Math.min(pos + node.nodeSize, to);
          lastPos = pos;
          lastNode = node;
        }
      });
    } else {
      state.doc.nodesBetween(from2, to, (node, pos) => {
        if (pos < from2 && nodeType && nodeType === node.type) {
          canUpdate = true;
          trimmedFrom = Math.max(pos, from2);
          trimmedTo = Math.min(pos + node.nodeSize, to);
          lastPos = pos;
          lastNode = node;
        }
        if (pos >= from2 && pos <= to) {
          if (nodeType && nodeType === node.type) {
            canUpdate = true;
            if (dispatch) {
              tr2.setNodeMarkup(pos, void 0, {
                ...node.attrs,
                ...attributes
              });
            }
          }
          if (markType && node.marks.length) {
            node.marks.forEach((mark) => {
              if (markType === mark.type) {
                canUpdate = true;
                if (dispatch) {
                  const trimmedFrom2 = Math.max(pos, from2);
                  const trimmedTo2 = Math.min(pos + node.nodeSize, to);
                  tr2.addMark(
                    trimmedFrom2,
                    trimmedTo2,
                    markType.create({
                      ...mark.attrs,
                      ...attributes
                    })
                  );
                }
              }
            });
          }
        }
      });
    }
    if (lastNode) {
      if (lastPos !== void 0 && dispatch) {
        tr2.setNodeMarkup(lastPos, void 0, {
          ...lastNode.attrs,
          ...attributes
        });
      }
      if (markType && lastNode.marks.length) {
        lastNode.marks.forEach((mark) => {
          if (markType === mark.type && dispatch) {
            tr2.addMark(
              trimmedFrom,
              trimmedTo,
              markType.create({
                ...mark.attrs,
                ...attributes
              })
            );
          }
        });
      }
    }
  });
  return canUpdate;
};
var wrapIn2 = (typeOrName, attributes = {}) => ({ state, dispatch }) => {
  const type = getNodeType(typeOrName, state.schema);
  return wrapIn(type, attributes)(state, dispatch);
};
var wrapInList2 = (typeOrName, attributes = {}) => ({ state, dispatch }) => {
  const type = getNodeType(typeOrName, state.schema);
  return wrapInList(type, attributes)(state, dispatch);
};
var EventEmitter = class {
  constructor() {
    this.callbacks = {};
  }
  on(event, fn) {
    if (!this.callbacks[event]) {
      this.callbacks[event] = [];
    }
    this.callbacks[event].push(fn);
    return this;
  }
  emit(event, ...args) {
    const callbacks = this.callbacks[event];
    if (callbacks) {
      callbacks.forEach((callback) => callback.apply(this, args));
    }
    return this;
  }
  off(event, fn) {
    const callbacks = this.callbacks[event];
    if (callbacks) {
      if (fn) {
        this.callbacks[event] = callbacks.filter((callback) => callback !== fn);
      } else {
        delete this.callbacks[event];
      }
    }
    return this;
  }
  once(event, fn) {
    const onceFn = (...args) => {
      this.off(event, onceFn);
      fn.apply(this, args);
    };
    return this.on(event, onceFn);
  }
  removeAllListeners() {
    this.callbacks = {};
  }
};
var InputRule = class {
  constructor(config) {
    var _a;
    this.find = config.find;
    this.handler = config.handler;
    this.undoable = (_a = config.undoable) != null ? _a : true;
  }
};
var inputRuleMatcherHandler = (text5, find2) => {
  if (isRegExp(find2)) {
    return find2.exec(text5);
  }
  const inputRuleMatch = find2(text5);
  if (!inputRuleMatch) {
    return null;
  }
  const result = [inputRuleMatch.text];
  result.index = inputRuleMatch.index;
  result.input = text5;
  result.data = inputRuleMatch.data;
  if (inputRuleMatch.replaceWith) {
    if (!inputRuleMatch.text.includes(inputRuleMatch.replaceWith)) {
      console.warn('[tiptap warn]: "inputRuleMatch.replaceWith" must be part of "inputRuleMatch.text".');
    }
    result.push(inputRuleMatch.replaceWith);
  }
  return result;
};
function run(config) {
  var _a;
  const { editor, from: from2, to, text: text5, rules, plugin } = config;
  const { view } = editor;
  if (view.composing) {
    return false;
  }
  const $from = view.state.doc.resolve(from2);
  if (
    // check for code node
    $from.parent.type.spec.code || // check for code mark
    !!((_a = $from.nodeBefore || $from.nodeAfter) == null ? void 0 : _a.marks.find((mark) => mark.type.spec.code))
  ) {
    return false;
  }
  let matched = false;
  const textBefore = getTextContentFromNodes($from) + text5;
  rules.forEach((rule) => {
    if (matched) {
      return;
    }
    const match = inputRuleMatcherHandler(textBefore, rule.find);
    if (!match) {
      return;
    }
    const tr2 = view.state.tr;
    const state = createChainableState({
      state: view.state,
      transaction: tr2
    });
    const range = {
      from: from2 - (match[0].length - text5.length),
      to
    };
    const { commands, chain, can } = new CommandManager({
      editor,
      state
    });
    const handler = rule.handler({
      state,
      range,
      match,
      commands,
      chain,
      can
    });
    if (handler === null || !tr2.steps.length) {
      return;
    }
    if (rule.undoable) {
      tr2.setMeta(plugin, {
        transform: tr2,
        from: from2,
        to,
        text: text5
      });
    }
    view.dispatch(tr2);
    matched = true;
  });
  return matched;
}
function inputRulesPlugin(props) {
  const { editor, rules } = props;
  const plugin = new Plugin({
    state: {
      init() {
        return null;
      },
      apply(tr2, prev, state) {
        const stored = tr2.getMeta(plugin);
        if (stored) {
          return stored;
        }
        const simulatedInputMeta = tr2.getMeta("applyInputRules");
        const isSimulatedInput = !!simulatedInputMeta;
        if (isSimulatedInput) {
          setTimeout(() => {
            let { text: text5 } = simulatedInputMeta;
            if (typeof text5 === "string") {
              text5 = text5;
            } else {
              text5 = getHTMLFromFragment(Fragment.from(text5), state.schema);
            }
            const { from: from2 } = simulatedInputMeta;
            const to = from2 + text5.length;
            run({
              editor,
              from: from2,
              to,
              text: text5,
              rules,
              plugin
            });
          });
        }
        return tr2.selectionSet || tr2.docChanged ? null : prev;
      }
    },
    props: {
      handleTextInput(view, from2, to, text5) {
        return run({
          editor,
          from: from2,
          to,
          text: text5,
          rules,
          plugin
        });
      },
      handleDOMEvents: {
        compositionend: (view) => {
          setTimeout(() => {
            const { $cursor } = view.state.selection;
            if ($cursor) {
              run({
                editor,
                from: $cursor.pos,
                to: $cursor.pos,
                text: "",
                rules,
                plugin
              });
            }
          });
          return false;
        }
      },
      // add support for input rules to trigger on enter
      // this is useful for example for code blocks
      handleKeyDown(view, event) {
        if (event.key !== "Enter") {
          return false;
        }
        const { $cursor } = view.state.selection;
        if ($cursor) {
          return run({
            editor,
            from: $cursor.pos,
            to: $cursor.pos,
            text: "\n",
            rules,
            plugin
          });
        }
        return false;
      }
    },
    // @ts-ignore
    isInputRules: true
  });
  return plugin;
}
function getType(value) {
  return Object.prototype.toString.call(value).slice(8, -1);
}
function isPlainObject(value) {
  if (getType(value) !== "Object") {
    return false;
  }
  return value.constructor === Object && Object.getPrototypeOf(value) === Object.prototype;
}
function mergeDeep(target2, source) {
  const output7 = { ...target2 };
  if (isPlainObject(target2) && isPlainObject(source)) {
    Object.keys(source).forEach((key) => {
      if (isPlainObject(source[key]) && isPlainObject(target2[key])) {
        output7[key] = mergeDeep(target2[key], source[key]);
      } else {
        output7[key] = source[key];
      }
    });
  }
  return output7;
}
var Extendable = class {
  constructor(config = {}) {
    this.type = "extendable";
    this.parent = null;
    this.child = null;
    this.name = "";
    this.config = {
      name: this.name
    };
    this.config = {
      ...this.config,
      ...config
    };
    this.name = this.config.name;
  }
  get options() {
    return {
      ...callOrReturn(
        getExtensionField(this, "addOptions", {
          name: this.name
        })
      ) || {}
    };
  }
  get storage() {
    return {
      ...callOrReturn(
        getExtensionField(this, "addStorage", {
          name: this.name,
          options: this.options
        })
      ) || {}
    };
  }
  configure(options = {}) {
    const extension = this.extend({
      ...this.config,
      addOptions: () => {
        return mergeDeep(this.options, options);
      }
    });
    extension.name = this.name;
    extension.parent = this.parent;
    return extension;
  }
  extend(extendedConfig = {}) {
    const extension = new this.constructor({ ...this.config, ...extendedConfig });
    extension.parent = this;
    this.child = extension;
    extension.name = "name" in extendedConfig ? extendedConfig.name : extension.parent.name;
    return extension;
  }
};
var Mark2 = class _Mark extends Extendable {
  constructor() {
    super(...arguments);
    this.type = "mark";
  }
  /**
   * Create a new Mark instance
   * @param config - Mark configuration object or a function that returns a configuration object
   */
  static create(config = {}) {
    const resolvedConfig = typeof config === "function" ? config() : config;
    return new _Mark(resolvedConfig);
  }
  static handleExit({ editor, mark }) {
    const { tr: tr2 } = editor.state;
    const currentPos = editor.state.selection.$from;
    const isAtEnd = currentPos.pos === currentPos.end();
    if (isAtEnd) {
      const currentMarks = currentPos.marks();
      const isInMark = !!currentMarks.find((m) => (m == null ? void 0 : m.type.name) === mark.name);
      if (!isInMark) {
        return false;
      }
      const removeMark2 = currentMarks.find((m) => (m == null ? void 0 : m.type.name) === mark.name);
      if (removeMark2) {
        tr2.removeStoredMark(removeMark2);
      }
      tr2.insertText(" ", currentPos.pos);
      editor.view.dispatch(tr2);
      return true;
    }
    return false;
  }
  configure(options) {
    return super.configure(options);
  }
  extend(extendedConfig) {
    const resolvedConfig = typeof extendedConfig === "function" ? extendedConfig() : extendedConfig;
    return super.extend(resolvedConfig);
  }
};
function isNumber(value) {
  return typeof value === "number";
}
var PasteRule = class {
  constructor(config) {
    this.find = config.find;
    this.handler = config.handler;
  }
};
var pasteRuleMatcherHandler = (text5, find2, event) => {
  if (isRegExp(find2)) {
    return [...text5.matchAll(find2)];
  }
  const matches2 = find2(text5, event);
  if (!matches2) {
    return [];
  }
  return matches2.map((pasteRuleMatch) => {
    const result = [pasteRuleMatch.text];
    result.index = pasteRuleMatch.index;
    result.input = text5;
    result.data = pasteRuleMatch.data;
    if (pasteRuleMatch.replaceWith) {
      if (!pasteRuleMatch.text.includes(pasteRuleMatch.replaceWith)) {
        console.warn('[tiptap warn]: "pasteRuleMatch.replaceWith" must be part of "pasteRuleMatch.text".');
      }
      result.push(pasteRuleMatch.replaceWith);
    }
    return result;
  });
};
function run2(config) {
  const { editor, state, from: from2, to, rule, pasteEvent, dropEvent } = config;
  const { commands, chain, can } = new CommandManager({
    editor,
    state
  });
  const handlers2 = [];
  state.doc.nodesBetween(from2, to, (node, pos) => {
    var _a, _b, _c, _d, _e;
    if (((_b = (_a = node.type) == null ? void 0 : _a.spec) == null ? void 0 : _b.code) || !(node.isText || node.isTextblock || node.isInline)) {
      return;
    }
    const contentSize = (_e = (_d = (_c = node.content) == null ? void 0 : _c.size) != null ? _d : node.nodeSize) != null ? _e : 0;
    const resolvedFrom = Math.max(from2, pos);
    const resolvedTo = Math.min(to, pos + contentSize);
    if (resolvedFrom >= resolvedTo) {
      return;
    }
    const textToMatch = node.isText ? node.text || "" : node.textBetween(resolvedFrom - pos, resolvedTo - pos, void 0, "\uFFFC");
    const matches2 = pasteRuleMatcherHandler(textToMatch, rule.find, pasteEvent);
    matches2.forEach((match) => {
      if (match.index === void 0) {
        return;
      }
      const start = resolvedFrom + match.index + 1;
      const end = start + match[0].length;
      const range = {
        from: state.tr.mapping.map(start),
        to: state.tr.mapping.map(end)
      };
      const handler = rule.handler({
        state,
        range,
        match,
        commands,
        chain,
        can,
        pasteEvent,
        dropEvent
      });
      handlers2.push(handler);
    });
  });
  const success = handlers2.every((handler) => handler !== null);
  return success;
}
var tiptapDragFromOtherEditor = null;
var createClipboardPasteEvent = (text5) => {
  var _a;
  const event = new ClipboardEvent("paste", {
    clipboardData: new DataTransfer()
  });
  (_a = event.clipboardData) == null ? void 0 : _a.setData("text/html", text5);
  return event;
};
function pasteRulesPlugin(props) {
  const { editor, rules } = props;
  let dragSourceElement = null;
  let isPastedFromProseMirror = false;
  let isDroppedFromProseMirror = false;
  let pasteEvent = typeof ClipboardEvent !== "undefined" ? new ClipboardEvent("paste") : null;
  let dropEvent;
  try {
    dropEvent = typeof DragEvent !== "undefined" ? new DragEvent("drop") : null;
  } catch {
    dropEvent = null;
  }
  const processEvent = ({
    state,
    from: from2,
    to,
    rule,
    pasteEvt
  }) => {
    const tr2 = state.tr;
    const chainableState = createChainableState({
      state,
      transaction: tr2
    });
    const handler = run2({
      editor,
      state: chainableState,
      from: Math.max(from2 - 1, 0),
      to: to.b - 1,
      rule,
      pasteEvent: pasteEvt,
      dropEvent
    });
    if (!handler || !tr2.steps.length) {
      return;
    }
    try {
      dropEvent = typeof DragEvent !== "undefined" ? new DragEvent("drop") : null;
    } catch {
      dropEvent = null;
    }
    pasteEvent = typeof ClipboardEvent !== "undefined" ? new ClipboardEvent("paste") : null;
    return tr2;
  };
  const plugins = rules.map((rule) => {
    return new Plugin({
      // we register a global drag handler to track the current drag source element
      view(view) {
        const handleDragstart = (event) => {
          var _a;
          dragSourceElement = ((_a = view.dom.parentElement) == null ? void 0 : _a.contains(event.target)) ? view.dom.parentElement : null;
          if (dragSourceElement) {
            tiptapDragFromOtherEditor = editor;
          }
        };
        const handleDragend = () => {
          if (tiptapDragFromOtherEditor) {
            tiptapDragFromOtherEditor = null;
          }
        };
        window.addEventListener("dragstart", handleDragstart);
        window.addEventListener("dragend", handleDragend);
        return {
          destroy() {
            window.removeEventListener("dragstart", handleDragstart);
            window.removeEventListener("dragend", handleDragend);
          }
        };
      },
      props: {
        handleDOMEvents: {
          drop: (view, event) => {
            isDroppedFromProseMirror = dragSourceElement === view.dom.parentElement;
            dropEvent = event;
            if (!isDroppedFromProseMirror) {
              const dragFromOtherEditor = tiptapDragFromOtherEditor;
              if (dragFromOtherEditor == null ? void 0 : dragFromOtherEditor.isEditable) {
                setTimeout(() => {
                  const selection = dragFromOtherEditor.state.selection;
                  if (selection) {
                    dragFromOtherEditor.commands.deleteRange({ from: selection.from, to: selection.to });
                  }
                }, 10);
              }
            }
            return false;
          },
          paste: (_view, event) => {
            var _a;
            const html = (_a = event.clipboardData) == null ? void 0 : _a.getData("text/html");
            pasteEvent = event;
            isPastedFromProseMirror = !!(html == null ? void 0 : html.includes("data-pm-slice"));
            return false;
          }
        }
      },
      appendTransaction: (transactions, oldState, state) => {
        const transaction = transactions[0];
        const isPaste = transaction.getMeta("uiEvent") === "paste" && !isPastedFromProseMirror;
        const isDrop = transaction.getMeta("uiEvent") === "drop" && !isDroppedFromProseMirror;
        const simulatedPasteMeta = transaction.getMeta("applyPasteRules");
        const isSimulatedPaste = !!simulatedPasteMeta;
        if (!isPaste && !isDrop && !isSimulatedPaste) {
          return;
        }
        if (isSimulatedPaste) {
          let { text: text5 } = simulatedPasteMeta;
          if (typeof text5 === "string") {
            text5 = text5;
          } else {
            text5 = getHTMLFromFragment(Fragment.from(text5), state.schema);
          }
          const { from: from22 } = simulatedPasteMeta;
          const to2 = from22 + text5.length;
          const pasteEvt = createClipboardPasteEvent(text5);
          return processEvent({
            rule,
            state,
            from: from22,
            to: { b: to2 },
            pasteEvt
          });
        }
        const from2 = oldState.doc.content.findDiffStart(state.doc.content);
        const to = oldState.doc.content.findDiffEnd(state.doc.content);
        if (!isNumber(from2) || !to || from2 === to.b) {
          return;
        }
        return processEvent({
          rule,
          state,
          from: from2,
          to,
          pasteEvt: pasteEvent
        });
      }
    });
  });
  return plugins;
}
var ExtensionManager = class {
  constructor(extensions, editor) {
    this.splittableMarks = [];
    this.editor = editor;
    this.baseExtensions = extensions;
    this.extensions = resolveExtensions(extensions);
    this.schema = getSchemaByResolvedExtensions(this.extensions, editor);
    this.setupExtensions();
  }
  /**
   * Get all commands from the extensions.
   * @returns An object with all commands where the key is the command name and the value is the command function
   */
  get commands() {
    return this.extensions.reduce((commands, extension) => {
      const context = {
        name: extension.name,
        options: extension.options,
        storage: this.editor.extensionStorage[extension.name],
        editor: this.editor,
        type: getSchemaTypeByName(extension.name, this.schema)
      };
      const addCommands = getExtensionField(extension, "addCommands", context);
      if (!addCommands) {
        return commands;
      }
      return {
        ...commands,
        ...addCommands()
      };
    }, {});
  }
  /**
   * Get all registered Prosemirror plugins from the extensions.
   * @returns An array of Prosemirror plugins
   */
  get plugins() {
    const { editor } = this;
    const extensions = sortExtensions([...this.extensions].reverse());
    const allPlugins = extensions.flatMap((extension) => {
      const context = {
        name: extension.name,
        options: extension.options,
        storage: this.editor.extensionStorage[extension.name],
        editor,
        type: getSchemaTypeByName(extension.name, this.schema)
      };
      const plugins = [];
      const addKeyboardShortcuts = getExtensionField(
        extension,
        "addKeyboardShortcuts",
        context
      );
      let defaultBindings = {};
      if (extension.type === "mark" && getExtensionField(extension, "exitable", context)) {
        defaultBindings.ArrowRight = () => Mark2.handleExit({ editor, mark: extension });
      }
      if (addKeyboardShortcuts) {
        const bindings = Object.fromEntries(
          Object.entries(addKeyboardShortcuts()).map(([shortcut, method]) => {
            return [shortcut, () => method({ editor })];
          })
        );
        defaultBindings = { ...defaultBindings, ...bindings };
      }
      const keyMapPlugin = keymap(defaultBindings);
      plugins.push(keyMapPlugin);
      const addInputRules = getExtensionField(extension, "addInputRules", context);
      if (isExtensionRulesEnabled(extension, editor.options.enableInputRules) && addInputRules) {
        const rules = addInputRules();
        if (rules && rules.length) {
          const inputResult = inputRulesPlugin({
            editor,
            rules
          });
          const inputPlugins = Array.isArray(inputResult) ? inputResult : [inputResult];
          plugins.push(...inputPlugins);
        }
      }
      const addPasteRules = getExtensionField(extension, "addPasteRules", context);
      if (isExtensionRulesEnabled(extension, editor.options.enablePasteRules) && addPasteRules) {
        const rules = addPasteRules();
        if (rules && rules.length) {
          const pasteRules = pasteRulesPlugin({ editor, rules });
          plugins.push(...pasteRules);
        }
      }
      const addProseMirrorPlugins = getExtensionField(
        extension,
        "addProseMirrorPlugins",
        context
      );
      if (addProseMirrorPlugins) {
        const proseMirrorPlugins = addProseMirrorPlugins();
        plugins.push(...proseMirrorPlugins);
      }
      return plugins;
    });
    return allPlugins;
  }
  /**
   * Get all attributes from the extensions.
   * @returns An array of attributes
   */
  get attributes() {
    return getAttributesFromExtensions(this.extensions);
  }
  /**
   * Get all node views from the extensions.
   * @returns An object with all node views where the key is the node name and the value is the node view function
   */
  get nodeViews() {
    const { editor } = this;
    const { nodeExtensions } = splitExtensions(this.extensions);
    return Object.fromEntries(
      nodeExtensions.filter((extension) => !!getExtensionField(extension, "addNodeView")).map((extension) => {
        const extensionAttributes = this.attributes.filter((attribute) => attribute.type === extension.name);
        const context = {
          name: extension.name,
          options: extension.options,
          storage: this.editor.extensionStorage[extension.name],
          editor,
          type: getNodeType(extension.name, this.schema)
        };
        const addNodeView = getExtensionField(extension, "addNodeView", context);
        if (!addNodeView) {
          return [];
        }
        const nodeViewResult = addNodeView();
        if (!nodeViewResult) {
          return [];
        }
        const nodeview = (node, view, getPos, decorations, innerDecorations) => {
          const HTMLAttributes = getRenderedAttributes(node, extensionAttributes);
          return nodeViewResult({
            // pass-through
            node,
            view,
            getPos,
            decorations,
            innerDecorations,
            // tiptap-specific
            editor,
            extension,
            HTMLAttributes
          });
        };
        return [extension.name, nodeview];
      })
    );
  }
  /**
   * Get the composed dispatchTransaction function from all extensions.
   * @param baseDispatch The base dispatch function (e.g. from the editor or user props)
   * @returns A composed dispatch function
   */
  dispatchTransaction(baseDispatch) {
    const { editor } = this;
    const extensions = sortExtensions([...this.extensions].reverse());
    return extensions.reduceRight((next, extension) => {
      const context = {
        name: extension.name,
        options: extension.options,
        storage: this.editor.extensionStorage[extension.name],
        editor,
        type: getSchemaTypeByName(extension.name, this.schema)
      };
      const dispatchTransaction = getExtensionField(
        extension,
        "dispatchTransaction",
        context
      );
      if (!dispatchTransaction) {
        return next;
      }
      return (transaction) => {
        dispatchTransaction.call(context, { transaction, next });
      };
    }, baseDispatch);
  }
  get markViews() {
    const { editor } = this;
    const { markExtensions } = splitExtensions(this.extensions);
    return Object.fromEntries(
      markExtensions.filter((extension) => !!getExtensionField(extension, "addMarkView")).map((extension) => {
        const extensionAttributes = this.attributes.filter((attribute) => attribute.type === extension.name);
        const context = {
          name: extension.name,
          options: extension.options,
          storage: this.editor.extensionStorage[extension.name],
          editor,
          type: getMarkType(extension.name, this.schema)
        };
        const addMarkView = getExtensionField(extension, "addMarkView", context);
        if (!addMarkView) {
          return [];
        }
        const markView = (mark, view, inline) => {
          const HTMLAttributes = getRenderedAttributes(mark, extensionAttributes);
          return addMarkView()({
            // pass-through
            mark,
            view,
            inline,
            // tiptap-specific
            editor,
            extension,
            HTMLAttributes,
            updateAttributes: (attrs) => {
              updateMarkViewAttributes(mark, editor, attrs);
            }
          });
        };
        return [extension.name, markView];
      })
    );
  }
  /**
   * Go through all extensions, create extension storages & setup marks
   * & bind editor event listener.
   */
  setupExtensions() {
    const extensions = this.extensions;
    this.editor.extensionStorage = Object.fromEntries(
      extensions.map((extension) => [extension.name, extension.storage])
    );
    extensions.forEach((extension) => {
      var _a;
      const context = {
        name: extension.name,
        options: extension.options,
        storage: this.editor.extensionStorage[extension.name],
        editor: this.editor,
        type: getSchemaTypeByName(extension.name, this.schema)
      };
      if (extension.type === "mark") {
        const keepOnSplit = (_a = callOrReturn(getExtensionField(extension, "keepOnSplit", context))) != null ? _a : true;
        if (keepOnSplit) {
          this.splittableMarks.push(extension.name);
        }
      }
      const onBeforeCreate = getExtensionField(extension, "onBeforeCreate", context);
      const onCreate = getExtensionField(extension, "onCreate", context);
      const onUpdate = getExtensionField(extension, "onUpdate", context);
      const onSelectionUpdate = getExtensionField(
        extension,
        "onSelectionUpdate",
        context
      );
      const onTransaction = getExtensionField(extension, "onTransaction", context);
      const onFocus = getExtensionField(extension, "onFocus", context);
      const onBlur = getExtensionField(extension, "onBlur", context);
      const onDestroy = getExtensionField(extension, "onDestroy", context);
      if (onBeforeCreate) {
        this.editor.on("beforeCreate", onBeforeCreate);
      }
      if (onCreate) {
        this.editor.on("create", onCreate);
      }
      if (onUpdate) {
        this.editor.on("update", onUpdate);
      }
      if (onSelectionUpdate) {
        this.editor.on("selectionUpdate", onSelectionUpdate);
      }
      if (onTransaction) {
        this.editor.on("transaction", onTransaction);
      }
      if (onFocus) {
        this.editor.on("focus", onFocus);
      }
      if (onBlur) {
        this.editor.on("blur", onBlur);
      }
      if (onDestroy) {
        this.editor.on("destroy", onDestroy);
      }
    });
  }
};
ExtensionManager.resolve = resolveExtensions;
ExtensionManager.sort = sortExtensions;
ExtensionManager.flatten = flattenExtensions;
var extensions_exports = {};
__export(extensions_exports, {
  ClipboardTextSerializer: () => ClipboardTextSerializer,
  Commands: () => Commands,
  Delete: () => Delete,
  Drop: () => Drop,
  Editable: () => Editable,
  FocusEvents: () => FocusEvents,
  Keymap: () => Keymap,
  Paste: () => Paste,
  Tabindex: () => Tabindex,
  TextDirection: () => TextDirection,
  focusEventsPluginKey: () => focusEventsPluginKey
});
var Extension = class _Extension extends Extendable {
  constructor() {
    super(...arguments);
    this.type = "extension";
  }
  /**
   * Create a new Extension instance
   * @param config - Extension configuration object or a function that returns a configuration object
   */
  static create(config = {}) {
    const resolvedConfig = typeof config === "function" ? config() : config;
    return new _Extension(resolvedConfig);
  }
  configure(options) {
    return super.configure(options);
  }
  extend(extendedConfig) {
    const resolvedConfig = typeof extendedConfig === "function" ? extendedConfig() : extendedConfig;
    return super.extend(resolvedConfig);
  }
};
var ClipboardTextSerializer = Extension.create({
  name: "clipboardTextSerializer",
  addOptions() {
    return {
      blockSeparator: void 0
    };
  },
  addProseMirrorPlugins() {
    return [
      new Plugin({
        key: new PluginKey("clipboardTextSerializer"),
        props: {
          clipboardTextSerializer: () => {
            const { editor } = this;
            const { state, schema } = editor;
            const { doc: doc3, selection } = state;
            const { ranges } = selection;
            const from2 = Math.min(...ranges.map((range2) => range2.$from.pos));
            const to = Math.max(...ranges.map((range2) => range2.$to.pos));
            const textSerializers = getTextSerializersFromSchema(schema);
            const range = { from: from2, to };
            return getTextBetween(doc3, range, {
              ...this.options.blockSeparator !== void 0 ? { blockSeparator: this.options.blockSeparator } : {},
              textSerializers
            });
          }
        }
      })
    ];
  }
});
var Commands = Extension.create({
  name: "commands",
  addCommands() {
    return {
      ...commands_exports
    };
  }
});
var Delete = Extension.create({
  name: "delete",
  onUpdate({ transaction, appendedTransactions }) {
    var _a, _b, _c;
    const callback = () => {
      var _a2, _b2, _c2, _d;
      if ((_d = (_c2 = (_b2 = (_a2 = this.editor.options.coreExtensionOptions) == null ? void 0 : _a2.delete) == null ? void 0 : _b2.filterTransaction) == null ? void 0 : _c2.call(_b2, transaction)) != null ? _d : transaction.getMeta("y-sync$")) {
        return;
      }
      const nextTransaction = combineTransactionSteps(transaction.before, [transaction, ...appendedTransactions]);
      const changes = getChangedRanges(nextTransaction);
      changes.forEach((change) => {
        if (nextTransaction.mapping.mapResult(change.oldRange.from).deletedAfter && nextTransaction.mapping.mapResult(change.oldRange.to).deletedBefore) {
          nextTransaction.before.nodesBetween(change.oldRange.from, change.oldRange.to, (node, from2) => {
            const to = from2 + node.nodeSize - 2;
            const isFullyWithinRange = change.oldRange.from <= from2 && to <= change.oldRange.to;
            this.editor.emit("delete", {
              type: "node",
              node,
              from: from2,
              to,
              newFrom: nextTransaction.mapping.map(from2),
              newTo: nextTransaction.mapping.map(to),
              deletedRange: change.oldRange,
              newRange: change.newRange,
              partial: !isFullyWithinRange,
              editor: this.editor,
              transaction,
              combinedTransform: nextTransaction
            });
          });
        }
      });
      const mapping = nextTransaction.mapping;
      nextTransaction.steps.forEach((step, index) => {
        var _a3, _b3;
        if (step instanceof RemoveMarkStep) {
          const newStart = mapping.slice(index).map(step.from, -1);
          const newEnd = mapping.slice(index).map(step.to);
          const oldStart = mapping.invert().map(newStart, -1);
          const oldEnd = mapping.invert().map(newEnd);
          const foundBeforeMark = (_a3 = nextTransaction.doc.nodeAt(newStart - 1)) == null ? void 0 : _a3.marks.some((mark) => mark.eq(step.mark));
          const foundAfterMark = (_b3 = nextTransaction.doc.nodeAt(newEnd)) == null ? void 0 : _b3.marks.some((mark) => mark.eq(step.mark));
          this.editor.emit("delete", {
            type: "mark",
            mark: step.mark,
            from: step.from,
            to: step.to,
            deletedRange: {
              from: oldStart,
              to: oldEnd
            },
            newRange: {
              from: newStart,
              to: newEnd
            },
            partial: Boolean(foundAfterMark || foundBeforeMark),
            editor: this.editor,
            transaction,
            combinedTransform: nextTransaction
          });
        }
      });
    };
    if ((_c = (_b = (_a = this.editor.options.coreExtensionOptions) == null ? void 0 : _a.delete) == null ? void 0 : _b.async) != null ? _c : true) {
      setTimeout(callback, 0);
    } else {
      callback();
    }
  }
});
var Drop = Extension.create({
  name: "drop",
  addProseMirrorPlugins() {
    return [
      new Plugin({
        key: new PluginKey("tiptapDrop"),
        props: {
          handleDrop: (_10, e, slice2, moved) => {
            this.editor.emit("drop", {
              editor: this.editor,
              event: e,
              slice: slice2,
              moved
            });
          }
        }
      })
    ];
  }
});
var Editable = Extension.create({
  name: "editable",
  addProseMirrorPlugins() {
    return [
      new Plugin({
        key: new PluginKey("editable"),
        props: {
          editable: () => this.editor.options.editable
        }
      })
    ];
  }
});
var focusEventsPluginKey = new PluginKey("focusEvents");
var FocusEvents = Extension.create({
  name: "focusEvents",
  addProseMirrorPlugins() {
    const { editor } = this;
    return [
      new Plugin({
        key: focusEventsPluginKey,
        props: {
          handleDOMEvents: {
            focus: (view, event) => {
              editor.isFocused = true;
              const transaction = editor.state.tr.setMeta("focus", { event }).setMeta("addToHistory", false);
              view.dispatch(transaction);
              return false;
            },
            blur: (view, event) => {
              editor.isFocused = false;
              const transaction = editor.state.tr.setMeta("blur", { event }).setMeta("addToHistory", false);
              view.dispatch(transaction);
              return false;
            }
          }
        }
      })
    ];
  }
});
var Keymap = Extension.create({
  name: "keymap",
  addKeyboardShortcuts() {
    const handleBackspace2 = () => this.editor.commands.first(({ commands }) => [
      () => commands.undoInputRule(),
      // maybe convert first text block node to default node
      () => commands.command(({ tr: tr2 }) => {
        const { selection, doc: doc3 } = tr2;
        const { empty: empty2, $anchor } = selection;
        const { pos, parent } = $anchor;
        const $parentPos = $anchor.parent.isTextblock && pos > 0 ? tr2.doc.resolve(pos - 1) : $anchor;
        const parentIsIsolating = $parentPos.parent.type.spec.isolating;
        const parentPos = $anchor.pos - $anchor.parentOffset;
        const isAtStart = parentIsIsolating && $parentPos.parent.childCount === 1 ? parentPos === $anchor.pos : Selection.atStart(doc3).from === pos;
        if (!empty2 || !parent.type.isTextblock || parent.textContent.length || !isAtStart || isAtStart && $anchor.parent.type.name === "paragraph") {
          return false;
        }
        return commands.clearNodes();
      }),
      () => commands.deleteSelection(),
      () => commands.joinBackward(),
      () => commands.selectNodeBackward()
    ]);
    const handleDelete2 = () => this.editor.commands.first(({ commands }) => [
      () => commands.deleteSelection(),
      () => commands.deleteCurrentNode(),
      () => commands.joinForward(),
      () => commands.selectNodeForward()
    ]);
    const handleEnter = () => this.editor.commands.first(({ commands }) => [
      () => commands.newlineInCode(),
      () => commands.createParagraphNear(),
      () => commands.liftEmptyBlock(),
      () => commands.splitBlock()
    ]);
    const baseKeymap = {
      Enter: handleEnter,
      "Mod-Enter": () => this.editor.commands.exitCode(),
      Backspace: handleBackspace2,
      "Mod-Backspace": handleBackspace2,
      "Shift-Backspace": handleBackspace2,
      Delete: handleDelete2,
      "Mod-Delete": handleDelete2,
      "Mod-a": () => this.editor.commands.selectAll()
    };
    const pcKeymap = {
      ...baseKeymap
    };
    const macKeymap = {
      ...baseKeymap,
      "Ctrl-h": handleBackspace2,
      "Alt-Backspace": handleBackspace2,
      "Ctrl-d": handleDelete2,
      "Ctrl-Alt-Backspace": handleDelete2,
      "Alt-Delete": handleDelete2,
      "Alt-d": handleDelete2,
      "Ctrl-a": () => this.editor.commands.selectTextblockStart(),
      "Ctrl-e": () => this.editor.commands.selectTextblockEnd()
    };
    if (isiOS() || isMacOS()) {
      return macKeymap;
    }
    return pcKeymap;
  },
  addProseMirrorPlugins() {
    return [
      // With this plugin we check if the whole document was selected and deleted.
      // In this case we will additionally call `clearNodes()` to convert e.g. a heading
      // to a paragraph if necessary.
      // This is an alternative to ProseMirror's `AllSelection`, which doesn’t work well
      // with many other commands.
      new Plugin({
        key: new PluginKey("clearDocument"),
        appendTransaction: (transactions, oldState, newState) => {
          if (transactions.some((tr22) => tr22.getMeta("composition"))) {
            return;
          }
          const docChanges = transactions.some((transaction) => transaction.docChanged) && !oldState.doc.eq(newState.doc);
          const ignoreTr = transactions.some((transaction) => transaction.getMeta("preventClearDocument"));
          if (!docChanges || ignoreTr) {
            return;
          }
          const { empty: empty2, from: from2, to } = oldState.selection;
          const allFrom = Selection.atStart(oldState.doc).from;
          const allEnd = Selection.atEnd(oldState.doc).to;
          const allWasSelected = from2 === allFrom && to === allEnd;
          if (empty2 || !allWasSelected) {
            return;
          }
          const isEmpty = isNodeEmpty(newState.doc);
          if (!isEmpty) {
            return;
          }
          const tr2 = newState.tr;
          const state = createChainableState({
            state: newState,
            transaction: tr2
          });
          const { commands } = new CommandManager({
            editor: this.editor,
            state
          });
          commands.clearNodes();
          if (!tr2.steps.length) {
            return;
          }
          return tr2;
        }
      })
    ];
  }
});
var Paste = Extension.create({
  name: "paste",
  addProseMirrorPlugins() {
    return [
      new Plugin({
        key: new PluginKey("tiptapPaste"),
        props: {
          handlePaste: (_view, e, slice2) => {
            this.editor.emit("paste", {
              editor: this.editor,
              event: e,
              slice: slice2
            });
          }
        }
      })
    ];
  }
});
var Tabindex = Extension.create({
  name: "tabindex",
  addProseMirrorPlugins() {
    return [
      new Plugin({
        key: new PluginKey("tabindex"),
        props: {
          attributes: () => this.editor.isEditable ? { tabindex: "0" } : {}
        }
      })
    ];
  }
});
var TextDirection = Extension.create({
  name: "textDirection",
  addOptions() {
    return {
      direction: void 0
    };
  },
  addGlobalAttributes() {
    if (!this.options.direction) {
      return [];
    }
    const { nodeExtensions } = splitExtensions(this.extensions);
    return [
      {
        types: nodeExtensions.filter((extension) => extension.name !== "text").map((extension) => extension.name),
        attributes: {
          dir: {
            default: this.options.direction,
            parseHTML: (element) => {
              const dir = element.getAttribute("dir");
              if (dir && (dir === "ltr" || dir === "rtl" || dir === "auto")) {
                return dir;
              }
              return this.options.direction;
            },
            renderHTML: (attributes) => {
              if (!attributes.dir) {
                return {};
              }
              return {
                dir: attributes.dir
              };
            }
          }
        }
      }
    ];
  },
  addProseMirrorPlugins() {
    return [
      new Plugin({
        key: new PluginKey("textDirection"),
        props: {
          attributes: () => {
            const direction = this.options.direction;
            if (!direction) {
              return {};
            }
            return {
              dir: direction
            };
          }
        }
      })
    ];
  }
});
var NodePos = class _NodePos {
  constructor(pos, editor, isBlock = false, node = null) {
    this.currentNode = null;
    this.actualDepth = null;
    this.isBlock = isBlock;
    this.resolvedPos = pos;
    this.editor = editor;
    this.currentNode = node;
  }
  get name() {
    return this.node.type.name;
  }
  get node() {
    return this.currentNode || this.resolvedPos.node();
  }
  get element() {
    return this.editor.view.domAtPos(this.pos).node;
  }
  get depth() {
    var _a;
    return (_a = this.actualDepth) != null ? _a : this.resolvedPos.depth;
  }
  get pos() {
    return this.resolvedPos.pos;
  }
  get content() {
    return this.node.content;
  }
  set content(content) {
    let from2 = this.from;
    let to = this.to;
    if (this.isBlock) {
      if (this.content.size === 0) {
        console.error(`You can\u2019t set content on a block node. Tried to set content on ${this.name} at ${this.pos}`);
        return;
      }
      from2 = this.from + 1;
      to = this.to - 1;
    }
    this.editor.commands.insertContentAt({ from: from2, to }, content);
  }
  get attributes() {
    return this.node.attrs;
  }
  get textContent() {
    return this.node.textContent;
  }
  get size() {
    return this.node.nodeSize;
  }
  get from() {
    if (this.isBlock) {
      return this.pos;
    }
    return this.resolvedPos.start(this.resolvedPos.depth);
  }
  get range() {
    return {
      from: this.from,
      to: this.to
    };
  }
  get to() {
    if (this.isBlock) {
      return this.pos + this.size;
    }
    return this.resolvedPos.end(this.resolvedPos.depth) + (this.node.isText ? 0 : 1);
  }
  get parent() {
    if (this.depth === 0) {
      return null;
    }
    const parentPos = this.resolvedPos.start(this.resolvedPos.depth - 1);
    const $pos = this.resolvedPos.doc.resolve(parentPos);
    return new _NodePos($pos, this.editor);
  }
  get before() {
    let $pos = this.resolvedPos.doc.resolve(this.from - (this.isBlock ? 1 : 2));
    if ($pos.depth !== this.depth) {
      $pos = this.resolvedPos.doc.resolve(this.from - 3);
    }
    return new _NodePos($pos, this.editor);
  }
  get after() {
    let $pos = this.resolvedPos.doc.resolve(this.to + (this.isBlock ? 2 : 1));
    if ($pos.depth !== this.depth) {
      $pos = this.resolvedPos.doc.resolve(this.to + 3);
    }
    return new _NodePos($pos, this.editor);
  }
  get children() {
    const children = [];
    this.node.content.forEach((node, offset) => {
      const isBlock = node.isBlock && !node.isTextblock;
      const isNonTextAtom = node.isAtom && !node.isText;
      const targetPos = this.pos + offset + (isNonTextAtom ? 0 : 1);
      if (targetPos < 0 || targetPos > this.resolvedPos.doc.nodeSize - 2) {
        return;
      }
      const $pos = this.resolvedPos.doc.resolve(targetPos);
      if (!isBlock && $pos.depth <= this.depth) {
        return;
      }
      const childNodePos = new _NodePos($pos, this.editor, isBlock, isBlock ? node : null);
      if (isBlock) {
        childNodePos.actualDepth = this.depth + 1;
      }
      children.push(new _NodePos($pos, this.editor, isBlock, isBlock ? node : null));
    });
    return children;
  }
  get firstChild() {
    return this.children[0] || null;
  }
  get lastChild() {
    const children = this.children;
    return children[children.length - 1] || null;
  }
  closest(selector, attributes = {}) {
    let node = null;
    let currentNode = this.parent;
    while (currentNode && !node) {
      if (currentNode.node.type.name === selector) {
        if (Object.keys(attributes).length > 0) {
          const nodeAttributes = currentNode.node.attrs;
          const attrKeys = Object.keys(attributes);
          for (let index = 0; index < attrKeys.length; index += 1) {
            const key = attrKeys[index];
            if (nodeAttributes[key] !== attributes[key]) {
              break;
            }
          }
        } else {
          node = currentNode;
        }
      }
      currentNode = currentNode.parent;
    }
    return node;
  }
  querySelector(selector, attributes = {}) {
    return this.querySelectorAll(selector, attributes, true)[0] || null;
  }
  querySelectorAll(selector, attributes = {}, firstItemOnly = false) {
    let nodes = [];
    if (!this.children || this.children.length === 0) {
      return nodes;
    }
    const attrKeys = Object.keys(attributes);
    this.children.forEach((childPos) => {
      if (firstItemOnly && nodes.length > 0) {
        return;
      }
      if (childPos.node.type.name === selector) {
        const doesAllAttributesMatch = attrKeys.every((key) => attributes[key] === childPos.node.attrs[key]);
        if (doesAllAttributesMatch) {
          nodes.push(childPos);
        }
      }
      if (firstItemOnly && nodes.length > 0) {
        return;
      }
      nodes = nodes.concat(childPos.querySelectorAll(selector, attributes, firstItemOnly));
    });
    return nodes;
  }
  setAttribute(attributes) {
    const { tr: tr2 } = this.editor.state;
    tr2.setNodeMarkup(this.from, void 0, {
      ...this.node.attrs,
      ...attributes
    });
    this.editor.view.dispatch(tr2);
  }
};
var style = `.ProseMirror {
  position: relative;
}

.ProseMirror {
  word-wrap: break-word;
  white-space: pre-wrap;
  white-space: break-spaces;
  -webkit-font-variant-ligatures: none;
  font-variant-ligatures: none;
  font-feature-settings: "liga" 0; /* the above doesn't seem to work in Edge */
}

.ProseMirror [contenteditable="false"] {
  white-space: normal;
}

.ProseMirror [contenteditable="false"] [contenteditable="true"] {
  white-space: pre-wrap;
}

.ProseMirror pre {
  white-space: pre-wrap;
}

img.ProseMirror-separator {
  display: inline !important;
  border: none !important;
  margin: 0 !important;
  width: 0 !important;
  height: 0 !important;
}

.ProseMirror-gapcursor {
  display: none;
  pointer-events: none;
  position: absolute;
  margin: 0;
}

.ProseMirror-gapcursor:after {
  content: "";
  display: block;
  position: absolute;
  top: -2px;
  width: 20px;
  border-top: 1px solid black;
  animation: ProseMirror-cursor-blink 1.1s steps(2, start) infinite;
}

@keyframes ProseMirror-cursor-blink {
  to {
    visibility: hidden;
  }
}

.ProseMirror-hideselection *::selection {
  background: transparent;
}

.ProseMirror-hideselection *::-moz-selection {
  background: transparent;
}

.ProseMirror-hideselection * {
  caret-color: transparent;
}

.ProseMirror-focused .ProseMirror-gapcursor {
  display: block;
}`;
function createStyleTag(style2, nonce, suffix) {
  const tiptapStyleTag = document.querySelector(`style[data-tiptap-style${suffix ? `-${suffix}` : ""}]`);
  if (tiptapStyleTag !== null) {
    return tiptapStyleTag;
  }
  const styleNode = document.createElement("style");
  if (nonce) {
    styleNode.setAttribute("nonce", nonce);
  }
  styleNode.setAttribute(`data-tiptap-style${suffix ? `-${suffix}` : ""}`, "");
  styleNode.innerHTML = style2;
  document.getElementsByTagName("head")[0].appendChild(styleNode);
  return styleNode;
}
var Editor = class extends EventEmitter {
  constructor(options = {}) {
    super();
    this.css = null;
    this.className = "tiptap";
    this.editorView = null;
    this.isFocused = false;
    this.isInitialized = false;
    this.extensionStorage = {};
    this.instanceId = Math.random().toString(36).slice(2, 9);
    this.options = {
      element: typeof document !== "undefined" ? document.createElement("div") : null,
      content: "",
      injectCSS: true,
      injectNonce: void 0,
      extensions: [],
      autofocus: false,
      editable: true,
      textDirection: void 0,
      editorProps: {},
      parseOptions: {},
      coreExtensionOptions: {},
      enableInputRules: true,
      enablePasteRules: true,
      enableCoreExtensions: true,
      enableContentCheck: false,
      emitContentError: false,
      onBeforeCreate: () => null,
      onCreate: () => null,
      onMount: () => null,
      onUnmount: () => null,
      onUpdate: () => null,
      onSelectionUpdate: () => null,
      onTransaction: () => null,
      onFocus: () => null,
      onBlur: () => null,
      onDestroy: () => null,
      onContentError: ({ error }) => {
        throw error;
      },
      onPaste: () => null,
      onDrop: () => null,
      onDelete: () => null,
      enableExtensionDispatchTransaction: true
    };
    this.isCapturingTransaction = false;
    this.capturedTransaction = null;
    this.utils = {
      getUpdatedPosition,
      createMappablePosition
    };
    this.setOptions(options);
    this.createExtensionManager();
    this.createCommandManager();
    this.createSchema();
    this.on("beforeCreate", this.options.onBeforeCreate);
    this.emit("beforeCreate", { editor: this });
    this.on("mount", this.options.onMount);
    this.on("unmount", this.options.onUnmount);
    this.on("contentError", this.options.onContentError);
    this.on("create", this.options.onCreate);
    this.on("update", this.options.onUpdate);
    this.on("selectionUpdate", this.options.onSelectionUpdate);
    this.on("transaction", this.options.onTransaction);
    this.on("focus", this.options.onFocus);
    this.on("blur", this.options.onBlur);
    this.on("destroy", this.options.onDestroy);
    this.on("drop", ({ event, slice: slice2, moved }) => this.options.onDrop(event, slice2, moved));
    this.on("paste", ({ event, slice: slice2 }) => this.options.onPaste(event, slice2));
    this.on("delete", this.options.onDelete);
    const initialDoc = this.createDoc();
    const selection = resolveFocusPosition(initialDoc, this.options.autofocus);
    this.editorState = EditorState.create({
      doc: initialDoc,
      schema: this.schema,
      selection: selection || void 0
    });
    if (this.options.element) {
      this.mount(this.options.element);
    }
  }
  /**
   * Attach the editor to the DOM, creating a new editor view.
   */
  mount(el) {
    if (typeof document === "undefined") {
      throw new Error(
        `[tiptap error]: The editor cannot be mounted because there is no 'document' defined in this environment.`
      );
    }
    this.createView(el);
    this.emit("mount", { editor: this });
    if (this.css && !document.head.contains(this.css)) {
      document.head.appendChild(this.css);
    }
    window.setTimeout(() => {
      if (this.isDestroyed) {
        return;
      }
      if (this.options.autofocus !== false && this.options.autofocus !== null) {
        this.commands.focus(this.options.autofocus);
      }
      this.emit("create", { editor: this });
      this.isInitialized = true;
    }, 0);
  }
  /**
   * Remove the editor from the DOM, but still allow remounting at a different point in time
   */
  unmount() {
    if (this.editorView) {
      const dom = this.editorView.dom;
      if (dom == null ? void 0 : dom.editor) {
        delete dom.editor;
      }
      this.editorView.destroy();
    }
    this.editorView = null;
    this.isInitialized = false;
    if (this.css && !document.querySelectorAll(`.${this.className}`).length) {
      try {
        if (typeof this.css.remove === "function") {
          this.css.remove();
        } else if (this.css.parentNode) {
          this.css.parentNode.removeChild(this.css);
        }
      } catch (error) {
        console.warn("Failed to remove CSS element:", error);
      }
    }
    this.css = null;
    this.emit("unmount", { editor: this });
  }
  /**
   * Returns the editor storage.
   */
  get storage() {
    return this.extensionStorage;
  }
  /**
   * An object of all registered commands.
   */
  get commands() {
    return this.commandManager.commands;
  }
  /**
   * Create a command chain to call multiple commands at once.
   */
  chain() {
    return this.commandManager.chain();
  }
  /**
   * Check if a command or a command chain can be executed. Without executing it.
   */
  can() {
    return this.commandManager.can();
  }
  /**
   * Inject CSS styles.
   */
  injectCSS() {
    if (this.options.injectCSS && typeof document !== "undefined") {
      this.css = createStyleTag(style, this.options.injectNonce);
    }
  }
  /**
   * Update editor options.
   *
   * @param options A list of options
   */
  setOptions(options = {}) {
    this.options = {
      ...this.options,
      ...options
    };
    if (!this.editorView || !this.state || this.isDestroyed) {
      return;
    }
    if (this.options.editorProps) {
      this.view.setProps(this.options.editorProps);
    }
    this.view.updateState(this.state);
  }
  /**
   * Update editable state of the editor.
   */
  setEditable(editable, emitUpdate = true) {
    this.setOptions({ editable });
    if (emitUpdate) {
      this.emit("update", { editor: this, transaction: this.state.tr, appendedTransactions: [] });
    }
  }
  /**
   * Returns whether the editor is editable.
   */
  get isEditable() {
    return this.options.editable && this.view && this.view.editable;
  }
  /**
   * Returns the editor state.
   */
  get view() {
    if (this.editorView) {
      return this.editorView;
    }
    return new Proxy(
      {
        state: this.editorState,
        updateState: (state) => {
          this.editorState = state;
        },
        dispatch: (tr2) => {
          this.dispatchTransaction(tr2);
        },
        // Stub some commonly accessed properties to prevent errors
        composing: false,
        dragging: null,
        editable: true,
        isDestroyed: false
      },
      {
        get: (obj, key) => {
          if (this.editorView) {
            return this.editorView[key];
          }
          if (key === "state") {
            return this.editorState;
          }
          if (key in obj) {
            return Reflect.get(obj, key);
          }
          throw new Error(
            `[tiptap error]: The editor view is not available. Cannot access view['${key}']. The editor may not be mounted yet.`
          );
        }
      }
    );
  }
  /**
   * Returns the editor state.
   */
  get state() {
    if (this.editorView) {
      this.editorState = this.view.state;
    }
    return this.editorState;
  }
  /**
   * Register a ProseMirror plugin.
   *
   * @param plugin A ProseMirror plugin
   * @param handlePlugins Control how to merge the plugin into the existing plugins.
   * @returns The new editor state
   */
  registerPlugin(plugin, handlePlugins) {
    const plugins = isFunction(handlePlugins) ? handlePlugins(plugin, [...this.state.plugins]) : [...this.state.plugins, plugin];
    const state = this.state.reconfigure({ plugins });
    this.view.updateState(state);
    return state;
  }
  /**
   * Unregister a ProseMirror plugin.
   *
   * @param nameOrPluginKeyToRemove The plugins name
   * @returns The new editor state or undefined if the editor is destroyed
   */
  unregisterPlugin(nameOrPluginKeyToRemove) {
    if (this.isDestroyed) {
      return void 0;
    }
    const prevPlugins = this.state.plugins;
    let plugins = prevPlugins;
    [].concat(nameOrPluginKeyToRemove).forEach((nameOrPluginKey) => {
      const name = typeof nameOrPluginKey === "string" ? `${nameOrPluginKey}$` : nameOrPluginKey.key;
      plugins = plugins.filter((plugin) => !plugin.key.startsWith(name));
    });
    if (prevPlugins.length === plugins.length) {
      return void 0;
    }
    const state = this.state.reconfigure({
      plugins
    });
    this.view.updateState(state);
    return state;
  }
  /**
   * Creates an extension manager.
   */
  createExtensionManager() {
    var _a, _b;
    const coreExtensions = this.options.enableCoreExtensions ? [
      Editable,
      ClipboardTextSerializer.configure({
        blockSeparator: (_b = (_a = this.options.coreExtensionOptions) == null ? void 0 : _a.clipboardTextSerializer) == null ? void 0 : _b.blockSeparator
      }),
      Commands,
      FocusEvents,
      Keymap,
      Tabindex,
      Drop,
      Paste,
      Delete,
      TextDirection.configure({
        direction: this.options.textDirection
      })
    ].filter((ext) => {
      if (typeof this.options.enableCoreExtensions === "object") {
        return this.options.enableCoreExtensions[ext.name] !== false;
      }
      return true;
    }) : [];
    const allExtensions = [...coreExtensions, ...this.options.extensions].filter((extension) => {
      return ["extension", "node", "mark"].includes(extension == null ? void 0 : extension.type);
    });
    this.extensionManager = new ExtensionManager(allExtensions, this);
  }
  /**
   * Creates an command manager.
   */
  createCommandManager() {
    this.commandManager = new CommandManager({
      editor: this
    });
  }
  /**
   * Creates a ProseMirror schema.
   */
  createSchema() {
    this.schema = this.extensionManager.schema;
  }
  /**
   * Creates the initial document.
   */
  createDoc() {
    let doc3;
    try {
      doc3 = createDocument2(this.options.content, this.schema, this.options.parseOptions, {
        errorOnInvalidContent: this.options.enableContentCheck
      });
    } catch (e) {
      if (!(e instanceof Error) || !["[tiptap error]: Invalid JSON content", "[tiptap error]: Invalid HTML content"].includes(e.message)) {
        throw e;
      }
      this.emit("contentError", {
        editor: this,
        error: e,
        disableCollaboration: () => {
          if ("collaboration" in this.storage && typeof this.storage.collaboration === "object" && this.storage.collaboration) {
            ;
            this.storage.collaboration.isDisabled = true;
          }
          this.options.extensions = this.options.extensions.filter((extension) => extension.name !== "collaboration");
          this.createExtensionManager();
        }
      });
      doc3 = createDocument2(this.options.content, this.schema, this.options.parseOptions, {
        errorOnInvalidContent: false
      });
    }
    return doc3;
  }
  /**
   * Creates a ProseMirror view.
   */
  createView(element) {
    const { editorProps, enableExtensionDispatchTransaction } = this.options;
    const baseDispatch = editorProps.dispatchTransaction || this.dispatchTransaction.bind(this);
    const dispatch = enableExtensionDispatchTransaction ? this.extensionManager.dispatchTransaction(baseDispatch) : baseDispatch;
    this.editorView = new EditorView(element, {
      ...editorProps,
      attributes: {
        // add `role="textbox"` to the editor element
        role: "textbox",
        ...editorProps == null ? void 0 : editorProps.attributes
      },
      dispatchTransaction: dispatch,
      state: this.editorState,
      markViews: this.extensionManager.markViews,
      nodeViews: this.extensionManager.nodeViews
    });
    const newState = this.state.reconfigure({
      plugins: this.extensionManager.plugins
    });
    this.view.updateState(newState);
    this.prependClass();
    this.injectCSS();
    const dom = this.view.dom;
    dom.editor = this;
  }
  /**
   * Creates all node and mark views.
   */
  createNodeViews() {
    if (this.view.isDestroyed) {
      return;
    }
    this.view.setProps({
      markViews: this.extensionManager.markViews,
      nodeViews: this.extensionManager.nodeViews
    });
  }
  /**
   * Prepend class name to element.
   */
  prependClass() {
    this.view.dom.className = `${this.className} ${this.view.dom.className}`;
  }
  captureTransaction(fn) {
    this.isCapturingTransaction = true;
    fn();
    this.isCapturingTransaction = false;
    const tr2 = this.capturedTransaction;
    this.capturedTransaction = null;
    return tr2;
  }
  /**
   * The callback over which to send transactions (state updates) produced by the view.
   *
   * @param transaction An editor state transaction
   */
  dispatchTransaction(transaction) {
    if (this.view.isDestroyed) {
      return;
    }
    if (this.isCapturingTransaction) {
      if (!this.capturedTransaction) {
        this.capturedTransaction = transaction;
        return;
      }
      transaction.steps.forEach((step) => {
        var _a;
        return (_a = this.capturedTransaction) == null ? void 0 : _a.step(step);
      });
      return;
    }
    const { state, transactions } = this.state.applyTransaction(transaction);
    const selectionHasChanged = !this.state.selection.eq(state.selection);
    const rootTrWasApplied = transactions.includes(transaction);
    const prevState = this.state;
    this.emit("beforeTransaction", {
      editor: this,
      transaction,
      nextState: state
    });
    if (!rootTrWasApplied) {
      return;
    }
    this.view.updateState(state);
    this.emit("transaction", {
      editor: this,
      transaction,
      appendedTransactions: transactions.slice(1)
    });
    if (selectionHasChanged) {
      this.emit("selectionUpdate", {
        editor: this,
        transaction
      });
    }
    const mostRecentFocusTr = transactions.findLast((tr2) => tr2.getMeta("focus") || tr2.getMeta("blur"));
    const focus2 = mostRecentFocusTr == null ? void 0 : mostRecentFocusTr.getMeta("focus");
    const blur2 = mostRecentFocusTr == null ? void 0 : mostRecentFocusTr.getMeta("blur");
    if (focus2) {
      this.emit("focus", {
        editor: this,
        event: focus2.event,
        // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
        transaction: mostRecentFocusTr
      });
    }
    if (blur2) {
      this.emit("blur", {
        editor: this,
        event: blur2.event,
        // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
        transaction: mostRecentFocusTr
      });
    }
    if (transaction.getMeta("preventUpdate") || !transactions.some((tr2) => tr2.docChanged) || prevState.doc.eq(state.doc)) {
      return;
    }
    this.emit("update", {
      editor: this,
      transaction,
      appendedTransactions: transactions.slice(1)
    });
  }
  /**
   * Get attributes of the currently selected node or mark.
   */
  getAttributes(nameOrType) {
    return getAttributes(this.state, nameOrType);
  }
  isActive(nameOrAttributes, attributesOrUndefined) {
    const name = typeof nameOrAttributes === "string" ? nameOrAttributes : null;
    const attributes = typeof nameOrAttributes === "string" ? attributesOrUndefined : nameOrAttributes;
    return isActive(this.state, name, attributes);
  }
  /**
   * Get the document as JSON.
   */
  getJSON() {
    return this.state.doc.toJSON();
  }
  /**
   * Get the document as HTML.
   */
  getHTML() {
    return getHTMLFromFragment(this.state.doc.content, this.schema);
  }
  /**
   * Get the document as text.
   */
  getText(options) {
    const { blockSeparator = "\n\n", textSerializers = {} } = options || {};
    return getText2(this.state.doc, {
      blockSeparator,
      textSerializers: {
        ...getTextSerializersFromSchema(this.schema),
        ...textSerializers
      }
    });
  }
  /**
   * Check if there is no content.
   */
  get isEmpty() {
    return isNodeEmpty(this.state.doc);
  }
  /**
   * Destroy the editor.
   */
  destroy() {
    this.emit("destroy");
    this.unmount();
    this.removeAllListeners();
  }
  /**
   * Check if the editor is already destroyed.
   */
  get isDestroyed() {
    var _a, _b;
    return (_b = (_a = this.editorView) == null ? void 0 : _a.isDestroyed) != null ? _b : true;
  }
  $node(selector, attributes) {
    var _a;
    return ((_a = this.$doc) == null ? void 0 : _a.querySelector(selector, attributes)) || null;
  }
  $nodes(selector, attributes) {
    var _a;
    return ((_a = this.$doc) == null ? void 0 : _a.querySelectorAll(selector, attributes)) || null;
  }
  $pos(pos) {
    const $pos = this.state.doc.resolve(pos);
    return new NodePos($pos, this);
  }
  get $doc() {
    return this.$pos(0);
  }
};
function markInputRule(config) {
  return new InputRule({
    find: config.find,
    handler: ({ state, range, match }) => {
      const attributes = callOrReturn(config.getAttributes, void 0, match);
      if (attributes === false || attributes === null) {
        return null;
      }
      const { tr: tr2 } = state;
      const captureGroup = match[match.length - 1];
      const fullMatch = match[0];
      if (captureGroup) {
        const startSpaces = fullMatch.search(/\S/);
        const textStart = range.from + fullMatch.indexOf(captureGroup);
        const textEnd = textStart + captureGroup.length;
        const excludedMarks = getMarksBetween(range.from, range.to, state.doc).filter((item) => {
          const excluded = item.mark.type.excluded;
          return excluded.find((type) => type === config.type && type !== item.mark.type);
        }).filter((item) => item.to > textStart);
        if (excludedMarks.length) {
          return null;
        }
        if (textEnd < range.to) {
          tr2.delete(textEnd, range.to);
        }
        if (textStart > range.from) {
          tr2.delete(range.from + startSpaces, textStart);
        }
        const markEnd = range.from + startSpaces + captureGroup.length;
        tr2.addMark(range.from + startSpaces, markEnd, config.type.create(attributes || {}));
        tr2.removeStoredMark(config.type);
      }
    },
    undoable: config.undoable
  });
}
function nodeInputRule(config) {
  return new InputRule({
    find: config.find,
    handler: ({ state, range, match }) => {
      const attributes = callOrReturn(config.getAttributes, void 0, match) || {};
      const { tr: tr2 } = state;
      const start = range.from;
      let end = range.to;
      const newNode = config.type.create(attributes);
      if (match[1]) {
        const offset = match[0].lastIndexOf(match[1]);
        let matchStart = start + offset;
        if (matchStart > end) {
          matchStart = end;
        } else {
          end = matchStart + match[1].length;
        }
        const lastChar = match[0][match[0].length - 1];
        tr2.insertText(lastChar, start + match[0].length - 1);
        tr2.replaceWith(matchStart, end, newNode);
      } else if (match[0]) {
        const insertionStart = config.type.isInline ? start : start - 1;
        tr2.insert(insertionStart, config.type.create(attributes)).delete(tr2.mapping.map(start), tr2.mapping.map(end));
      }
      tr2.scrollIntoView();
    },
    undoable: config.undoable
  });
}
function textblockTypeInputRule(config) {
  return new InputRule({
    find: config.find,
    handler: ({ state, range, match }) => {
      const $start = state.doc.resolve(range.from);
      const attributes = callOrReturn(config.getAttributes, void 0, match) || {};
      if (!$start.node(-1).canReplaceWith($start.index(-1), $start.indexAfter(-1), config.type)) {
        return null;
      }
      state.tr.delete(range.from, range.to).setBlockType(range.from, range.from, config.type, attributes);
    },
    undoable: config.undoable
  });
}
function wrappingInputRule(config) {
  return new InputRule({
    find: config.find,
    handler: ({ state, range, match, chain }) => {
      const attributes = callOrReturn(config.getAttributes, void 0, match) || {};
      const tr2 = state.tr.delete(range.from, range.to);
      const $start = tr2.doc.resolve(range.from);
      const blockRange = $start.blockRange();
      const wrapping = blockRange && findWrapping(blockRange, config.type, attributes);
      if (!wrapping) {
        return null;
      }
      tr2.wrap(blockRange, wrapping);
      if (config.keepMarks && config.editor) {
        const { selection, storedMarks } = state;
        const { splittableMarks } = config.editor.extensionManager;
        const marks = storedMarks || selection.$to.parentOffset && selection.$from.marks();
        if (marks) {
          const filteredMarks = marks.filter((mark) => splittableMarks.includes(mark.type.name));
          tr2.ensureMarks(filteredMarks);
        }
      }
      if (config.keepAttributes) {
        const nodeType = config.type.name === "bulletList" || config.type.name === "orderedList" ? "listItem" : "taskList";
        chain().updateAttributes(nodeType, attributes).run();
      }
      const before = tr2.doc.resolve(range.from - 1).nodeBefore;
      if (before && before.type === config.type && canJoin(tr2.doc, range.from - 1) && (!config.joinPredicate || config.joinPredicate(match, before))) {
        tr2.join(range.from - 1);
      }
    },
    undoable: config.undoable
  });
}
function canInsertNode(state, nodeType) {
  const { selection } = state;
  const { $from } = selection;
  if (selection instanceof NodeSelection) {
    const index = $from.index();
    const parent = $from.parent;
    return parent.canReplaceWith(index, index + 1, nodeType);
  }
  let depth = $from.depth;
  while (depth >= 0) {
    const index = $from.index(depth);
    const parent = $from.node(depth);
    const match = parent.contentMatchAt(index);
    if (match.matchType(nodeType)) {
      return true;
    }
    depth -= 1;
  }
  return false;
}
var markdown_exports = {};
__export(markdown_exports, {
  createAtomBlockMarkdownSpec: () => createAtomBlockMarkdownSpec,
  createBlockMarkdownSpec: () => createBlockMarkdownSpec,
  createInlineMarkdownSpec: () => createInlineMarkdownSpec,
  parseAttributes: () => parseAttributes,
  parseIndentedBlocks: () => parseIndentedBlocks,
  renderNestedMarkdownContent: () => renderNestedMarkdownContent,
  serializeAttributes: () => serializeAttributes
});
function parseAttributes(attrString) {
  if (!(attrString == null ? void 0 : attrString.trim())) {
    return {};
  }
  const attributes = {};
  const quotedStrings = [];
  const tempString = attrString.replace(/["']([^"']*)["']/g, (match) => {
    quotedStrings.push(match);
    return `__QUOTED_${quotedStrings.length - 1}__`;
  });
  const classMatches = tempString.match(/(?:^|\s)\.([a-zA-Z][\w-]*)/g);
  if (classMatches) {
    const classes = classMatches.map((match) => match.trim().slice(1));
    attributes.class = classes.join(" ");
  }
  const idMatch = tempString.match(/(?:^|\s)#([a-zA-Z][\w-]*)/);
  if (idMatch) {
    attributes.id = idMatch[1];
  }
  const kvRegex = /([a-zA-Z][\w-]*)\s*=\s*(__QUOTED_\d+__)/g;
  const kvMatches = Array.from(tempString.matchAll(kvRegex));
  kvMatches.forEach(([, key, quotedRef]) => {
    var _a;
    const quotedIndex = parseInt(((_a = quotedRef.match(/__QUOTED_(\d+)__/)) == null ? void 0 : _a[1]) || "0", 10);
    const quotedValue = quotedStrings[quotedIndex];
    if (quotedValue) {
      attributes[key] = quotedValue.slice(1, -1);
    }
  });
  const cleanString = tempString.replace(/(?:^|\s)\.([a-zA-Z][\w-]*)/g, "").replace(/(?:^|\s)#([a-zA-Z][\w-]*)/g, "").replace(/([a-zA-Z][\w-]*)\s*=\s*__QUOTED_\d+__/g, "").trim();
  if (cleanString) {
    const booleanAttrs = cleanString.split(/\s+/).filter(Boolean);
    booleanAttrs.forEach((attr) => {
      if (attr.match(/^[a-zA-Z][\w-]*$/)) {
        attributes[attr] = true;
      }
    });
  }
  return attributes;
}
function serializeAttributes(attributes) {
  if (!attributes || Object.keys(attributes).length === 0) {
    return "";
  }
  const parts = [];
  if (attributes.class) {
    const classes = String(attributes.class).split(/\s+/).filter(Boolean);
    classes.forEach((cls) => parts.push(`.${cls}`));
  }
  if (attributes.id) {
    parts.push(`#${attributes.id}`);
  }
  Object.entries(attributes).forEach(([key, value]) => {
    if (key === "class" || key === "id") {
      return;
    }
    if (value === true) {
      parts.push(key);
    } else if (value !== false && value != null) {
      parts.push(`${key}="${String(value)}"`);
    }
  });
  return parts.join(" ");
}
function createAtomBlockMarkdownSpec(options) {
  const {
    nodeName,
    name: markdownName,
    parseAttributes: parseAttributes2 = parseAttributes,
    serializeAttributes: serializeAttributes2 = serializeAttributes,
    defaultAttributes = {},
    requiredAttributes = [],
    allowedAttributes
  } = options;
  const blockName = markdownName || nodeName;
  const filterAttributes = (attrs) => {
    if (!allowedAttributes) {
      return attrs;
    }
    const filtered = {};
    allowedAttributes.forEach((key) => {
      if (key in attrs) {
        filtered[key] = attrs[key];
      }
    });
    return filtered;
  };
  return {
    parseMarkdown: (token, h2) => {
      const attrs = { ...defaultAttributes, ...token.attributes };
      return h2.createNode(nodeName, attrs, []);
    },
    markdownTokenizer: {
      name: nodeName,
      level: "block",
      start(src) {
        var _a;
        const regex = new RegExp(`^:::${blockName}(?:\\s|$)`, "m");
        const index = (_a = src.match(regex)) == null ? void 0 : _a.index;
        return index !== void 0 ? index : -1;
      },
      tokenize(src, _tokens, _lexer) {
        const regex = new RegExp(`^:::${blockName}(?:\\s+\\{([^}]*)\\})?\\s*:::(?:\\n|$)`);
        const match = src.match(regex);
        if (!match) {
          return void 0;
        }
        const attrString = match[1] || "";
        const attributes = parseAttributes2(attrString);
        const missingRequired = requiredAttributes.find((required) => !(required in attributes));
        if (missingRequired) {
          return void 0;
        }
        return {
          type: nodeName,
          raw: match[0],
          attributes
        };
      }
    },
    renderMarkdown: (node) => {
      const filteredAttrs = filterAttributes(node.attrs || {});
      const attrs = serializeAttributes2(filteredAttrs);
      const attrString = attrs ? ` {${attrs}}` : "";
      return `:::${blockName}${attrString} :::`;
    }
  };
}
function createBlockMarkdownSpec(options) {
  const {
    nodeName,
    name: markdownName,
    getContent,
    parseAttributes: parseAttributes2 = parseAttributes,
    serializeAttributes: serializeAttributes2 = serializeAttributes,
    defaultAttributes = {},
    content = "block",
    allowedAttributes
  } = options;
  const blockName = markdownName || nodeName;
  const filterAttributes = (attrs) => {
    if (!allowedAttributes) {
      return attrs;
    }
    const filtered = {};
    allowedAttributes.forEach((key) => {
      if (key in attrs) {
        filtered[key] = attrs[key];
      }
    });
    return filtered;
  };
  return {
    parseMarkdown: (token, h2) => {
      let nodeContent;
      if (getContent) {
        const contentResult = getContent(token);
        nodeContent = typeof contentResult === "string" ? [{ type: "text", text: contentResult }] : contentResult;
      } else if (content === "block") {
        nodeContent = h2.parseChildren(token.tokens || []);
      } else {
        nodeContent = h2.parseInline(token.tokens || []);
      }
      const attrs = { ...defaultAttributes, ...token.attributes };
      return h2.createNode(nodeName, attrs, nodeContent);
    },
    markdownTokenizer: {
      name: nodeName,
      level: "block",
      start(src) {
        var _a;
        const regex = new RegExp(`^:::${blockName}`, "m");
        const index = (_a = src.match(regex)) == null ? void 0 : _a.index;
        return index !== void 0 ? index : -1;
      },
      tokenize(src, _tokens, lexer) {
        var _a;
        const openingRegex = new RegExp(`^:::${blockName}(?:\\s+\\{([^}]*)\\})?\\s*\\n`);
        const openingMatch = src.match(openingRegex);
        if (!openingMatch) {
          return void 0;
        }
        const [openingTag, attrString = ""] = openingMatch;
        const attributes = parseAttributes2(attrString);
        let level = 1;
        const position = openingTag.length;
        let matchedContent = "";
        const blockPattern = /^:::([\w-]*)(\s.*)?/gm;
        const remaining = src.slice(position);
        blockPattern.lastIndex = 0;
        for (; ; ) {
          const match = blockPattern.exec(remaining);
          if (match === null) {
            break;
          }
          const matchPos = match.index;
          const blockType = match[1];
          if ((_a = match[2]) == null ? void 0 : _a.endsWith(":::")) {
            continue;
          }
          if (blockType) {
            level += 1;
          } else {
            level -= 1;
            if (level === 0) {
              const rawContent = remaining.slice(0, matchPos);
              matchedContent = rawContent.trim();
              const fullMatch = src.slice(0, position + matchPos + match[0].length);
              let contentTokens = [];
              if (matchedContent) {
                if (content === "block") {
                  contentTokens = lexer.blockTokens(rawContent);
                  contentTokens.forEach((token) => {
                    if (token.text && (!token.tokens || token.tokens.length === 0)) {
                      token.tokens = lexer.inlineTokens(token.text);
                    }
                  });
                  while (contentTokens.length > 0) {
                    const lastToken = contentTokens[contentTokens.length - 1];
                    if (lastToken.type === "paragraph" && (!lastToken.text || lastToken.text.trim() === "")) {
                      contentTokens.pop();
                    } else {
                      break;
                    }
                  }
                } else {
                  contentTokens = lexer.inlineTokens(matchedContent);
                }
              }
              return {
                type: nodeName,
                raw: fullMatch,
                attributes,
                content: matchedContent,
                tokens: contentTokens
              };
            }
          }
        }
        return void 0;
      }
    },
    renderMarkdown: (node, h2) => {
      const filteredAttrs = filterAttributes(node.attrs || {});
      const attrs = serializeAttributes2(filteredAttrs);
      const attrString = attrs ? ` {${attrs}}` : "";
      const renderedContent = h2.renderChildren(node.content || [], "\n\n");
      return `:::${blockName}${attrString}

${renderedContent}

:::`;
    }
  };
}
function parseShortcodeAttributes(attrString) {
  if (!attrString.trim()) {
    return {};
  }
  const attributes = {};
  const regex = /(\w+)=(?:"([^"]*)"|'([^']*)')/g;
  let match = regex.exec(attrString);
  while (match !== null) {
    const [, key, doubleQuoted, singleQuoted] = match;
    attributes[key] = doubleQuoted || singleQuoted;
    match = regex.exec(attrString);
  }
  return attributes;
}
function serializeShortcodeAttributes(attrs) {
  return Object.entries(attrs).filter(([, value]) => value !== void 0 && value !== null).map(([key, value]) => `${key}="${value}"`).join(" ");
}
function createInlineMarkdownSpec(options) {
  const {
    nodeName,
    name: shortcodeName,
    getContent,
    parseAttributes: parseAttributes2 = parseShortcodeAttributes,
    serializeAttributes: serializeAttributes2 = serializeShortcodeAttributes,
    defaultAttributes = {},
    selfClosing = false,
    allowedAttributes
  } = options;
  const shortcode = shortcodeName || nodeName;
  const filterAttributes = (attrs) => {
    if (!allowedAttributes) {
      return attrs;
    }
    const filtered = {};
    allowedAttributes.forEach((attr) => {
      const attrName = typeof attr === "string" ? attr : attr.name;
      const skipIfDefault = typeof attr === "string" ? void 0 : attr.skipIfDefault;
      if (attrName in attrs) {
        const value = attrs[attrName];
        if (skipIfDefault !== void 0 && value === skipIfDefault) {
          return;
        }
        filtered[attrName] = value;
      }
    });
    return filtered;
  };
  const escapedShortcode = shortcode.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
  return {
    parseMarkdown: (token, h2) => {
      const attrs = { ...defaultAttributes, ...token.attributes };
      if (selfClosing) {
        return h2.createNode(nodeName, attrs);
      }
      const content = getContent ? getContent(token) : token.content || "";
      if (content) {
        return h2.createNode(nodeName, attrs, [h2.createTextNode(content)]);
      }
      return h2.createNode(nodeName, attrs, []);
    },
    markdownTokenizer: {
      name: nodeName,
      level: "inline",
      start(src) {
        const startPattern = selfClosing ? new RegExp(`\\[${escapedShortcode}\\s*[^\\]]*\\]`) : new RegExp(`\\[${escapedShortcode}\\s*[^\\]]*\\][\\s\\S]*?\\[\\/${escapedShortcode}\\]`);
        const match = src.match(startPattern);
        const index = match == null ? void 0 : match.index;
        return index !== void 0 ? index : -1;
      },
      tokenize(src, _tokens, _lexer) {
        const tokenPattern = selfClosing ? new RegExp(`^\\[${escapedShortcode}\\s*([^\\]]*)\\]`) : new RegExp(`^\\[${escapedShortcode}\\s*([^\\]]*)\\]([\\s\\S]*?)\\[\\/${escapedShortcode}\\]`);
        const match = src.match(tokenPattern);
        if (!match) {
          return void 0;
        }
        let content = "";
        let attrString = "";
        if (selfClosing) {
          const [, attrs] = match;
          attrString = attrs;
        } else {
          const [, attrs, contentMatch] = match;
          attrString = attrs;
          content = contentMatch || "";
        }
        const attributes = parseAttributes2(attrString.trim());
        return {
          type: nodeName,
          raw: match[0],
          content: content.trim(),
          attributes
        };
      }
    },
    renderMarkdown: (node) => {
      let content = "";
      if (getContent) {
        content = getContent(node);
      } else if (node.content && node.content.length > 0) {
        content = node.content.filter((child) => child.type === "text").map((child) => child.text).join("");
      }
      const filteredAttrs = filterAttributes(node.attrs || {});
      const attrs = serializeAttributes2(filteredAttrs);
      const attrString = attrs ? ` ${attrs}` : "";
      if (selfClosing) {
        return `[${shortcode}${attrString}]`;
      }
      return `[${shortcode}${attrString}]${content}[/${shortcode}]`;
    }
  };
}
function parseIndentedBlocks(src, config, lexer) {
  var _a, _b, _c, _d;
  const lines = src.split("\n");
  const items = [];
  let totalRaw = "";
  let i = 0;
  const baseIndentSize = config.baseIndentSize || 2;
  while (i < lines.length) {
    const currentLine = lines[i];
    const itemMatch = currentLine.match(config.itemPattern);
    if (!itemMatch) {
      if (items.length > 0) {
        break;
      } else if (currentLine.trim() === "") {
        i += 1;
        totalRaw = `${totalRaw}${currentLine}
`;
        continue;
      } else {
        return void 0;
      }
    }
    const itemData = config.extractItemData(itemMatch);
    const { indentLevel, mainContent } = itemData;
    totalRaw = `${totalRaw}${currentLine}
`;
    const itemContent = [mainContent];
    i += 1;
    while (i < lines.length) {
      const nextLine = lines[i];
      if (nextLine.trim() === "") {
        const nextNonEmptyIndex = lines.slice(i + 1).findIndex((l) => l.trim() !== "");
        if (nextNonEmptyIndex === -1) {
          break;
        }
        const nextNonEmpty = lines[i + 1 + nextNonEmptyIndex];
        const nextIndent2 = ((_b = (_a = nextNonEmpty.match(/^(\s*)/)) == null ? void 0 : _a[1]) == null ? void 0 : _b.length) || 0;
        if (nextIndent2 > indentLevel) {
          itemContent.push(nextLine);
          totalRaw = `${totalRaw}${nextLine}
`;
          i += 1;
          continue;
        } else {
          break;
        }
      }
      const nextIndent = ((_d = (_c = nextLine.match(/^(\s*)/)) == null ? void 0 : _c[1]) == null ? void 0 : _d.length) || 0;
      if (nextIndent > indentLevel) {
        itemContent.push(nextLine);
        totalRaw = `${totalRaw}${nextLine}
`;
        i += 1;
      } else {
        break;
      }
    }
    let nestedTokens;
    const nestedContent = itemContent.slice(1);
    if (nestedContent.length > 0) {
      const dedentedNested = nestedContent.map((nestedLine) => nestedLine.slice(indentLevel + baseIndentSize)).join("\n");
      if (dedentedNested.trim()) {
        if (config.customNestedParser) {
          nestedTokens = config.customNestedParser(dedentedNested);
        } else {
          nestedTokens = lexer.blockTokens(dedentedNested);
        }
      }
    }
    const token = config.createToken(itemData, nestedTokens);
    items.push(token);
  }
  if (items.length === 0) {
    return void 0;
  }
  return {
    items,
    raw: totalRaw
  };
}
function renderNestedMarkdownContent(node, h2, prefixOrGenerator, ctx) {
  if (!node || !Array.isArray(node.content)) {
    return "";
  }
  const prefix = typeof prefixOrGenerator === "function" ? prefixOrGenerator(ctx) : prefixOrGenerator;
  const [content, ...children] = node.content;
  const mainContent = h2.renderChildren([content]);
  const output7 = [`${prefix}${mainContent}`];
  if (children && children.length > 0) {
    children.forEach((child) => {
      const childContent = h2.renderChildren([child]);
      if (childContent) {
        const indentedChild = childContent.split("\n").map((line) => line ? h2.indent(line) : "").join("\n");
        output7.push(indentedChild);
      }
    });
  }
  return output7.join("\n");
}
function updateMarkViewAttributes(checkMark, editor, attrs = {}) {
  const { state } = editor;
  const { doc: doc3, tr: tr2 } = state;
  const thisMark = checkMark;
  doc3.descendants((node, pos) => {
    const from2 = tr2.mapping.map(pos);
    const to = tr2.mapping.map(pos) + node.nodeSize;
    let foundMark = null;
    node.marks.forEach((mark) => {
      if (mark !== thisMark) {
        return false;
      }
      foundMark = mark;
    });
    if (!foundMark) {
      return;
    }
    let needsUpdate = false;
    Object.keys(attrs).forEach((k) => {
      if (attrs[k] !== foundMark.attrs[k]) {
        needsUpdate = true;
      }
    });
    if (needsUpdate) {
      const updatedMark = checkMark.type.create({
        ...checkMark.attrs,
        ...attrs
      });
      tr2.removeMark(from2, to, checkMark.type);
      tr2.addMark(from2, to, updatedMark);
    }
  });
  if (tr2.docChanged) {
    editor.view.dispatch(tr2);
  }
}
var Node3 = class _Node extends Extendable {
  constructor() {
    super(...arguments);
    this.type = "node";
  }
  /**
   * Create a new Node instance
   * @param config - Node configuration object or a function that returns a configuration object
   */
  static create(config = {}) {
    const resolvedConfig = typeof config === "function" ? config() : config;
    return new _Node(resolvedConfig);
  }
  configure(options) {
    return super.configure(options);
  }
  extend(extendedConfig) {
    const resolvedConfig = typeof extendedConfig === "function" ? extendedConfig() : extendedConfig;
    return super.extend(resolvedConfig);
  }
};
function markPasteRule(config) {
  return new PasteRule({
    find: config.find,
    handler: ({ state, range, match, pasteEvent }) => {
      const attributes = callOrReturn(config.getAttributes, void 0, match, pasteEvent);
      if (attributes === false || attributes === null) {
        return null;
      }
      const { tr: tr2 } = state;
      const captureGroup = match[match.length - 1];
      const fullMatch = match[0];
      let markEnd = range.to;
      if (captureGroup) {
        const startSpaces = fullMatch.search(/\S/);
        const textStart = range.from + fullMatch.indexOf(captureGroup);
        const textEnd = textStart + captureGroup.length;
        const excludedMarks = getMarksBetween(range.from, range.to, state.doc).filter((item) => {
          const excluded = item.mark.type.excluded;
          return excluded.find((type) => type === config.type && type !== item.mark.type);
        }).filter((item) => item.to > textStart);
        if (excludedMarks.length) {
          return null;
        }
        if (textEnd < range.to) {
          tr2.delete(textEnd, range.to);
        }
        if (textStart > range.from) {
          tr2.delete(range.from + startSpaces, textStart);
        }
        markEnd = range.from + startSpaces + captureGroup.length;
        tr2.addMark(range.from + startSpaces, markEnd, config.type.create(attributes || {}));
        tr2.removeStoredMark(config.type);
      }
    }
  });
}

// ../../node_modules/.pnpm/@tiptap+core@3.15.3_@tiptap+pm@3.15.3/node_modules/@tiptap/core/dist/jsx-runtime/jsx-runtime.js
var h = (tag, attributes) => {
  if (tag === "slot") {
    return 0;
  }
  if (tag instanceof Function) {
    return tag(attributes);
  }
  const { children, ...rest } = attributes != null ? attributes : {};
  if (tag === "svg") {
    throw new Error("SVG elements are not supported in the JSX syntax, use the array syntax instead");
  }
  return [tag, rest, children];
};

// ../../node_modules/.pnpm/@tiptap+extension-blockquote@3.15.3_@tiptap+core@3.15.3_@tiptap+pm@3.15.3_/node_modules/@tiptap/extension-blockquote/dist/index.js
var inputRegex = /^\s*>\s$/;
var Blockquote = Node3.create({
  name: "blockquote",
  addOptions() {
    return {
      HTMLAttributes: {}
    };
  },
  content: "block+",
  group: "block",
  defining: true,
  parseHTML() {
    return [{ tag: "blockquote" }];
  },
  renderHTML({ HTMLAttributes }) {
    return /* @__PURE__ */ h("blockquote", { ...mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), children: /* @__PURE__ */ h("slot", {}) });
  },
  parseMarkdown: (token, helpers) => {
    return helpers.createNode("blockquote", void 0, helpers.parseChildren(token.tokens || []));
  },
  renderMarkdown: (node, h2) => {
    if (!node.content) {
      return "";
    }
    const prefix = ">";
    const result = [];
    node.content.forEach((child) => {
      const childContent = h2.renderChildren([child]);
      const lines = childContent.split("\n");
      const linesWithPrefix = lines.map((line) => {
        if (line.trim() === "") {
          return prefix;
        }
        return `${prefix} ${line}`;
      });
      result.push(linesWithPrefix.join("\n"));
    });
    return result.join(`
${prefix}
`);
  },
  addCommands() {
    return {
      setBlockquote: () => ({ commands }) => {
        return commands.wrapIn(this.name);
      },
      toggleBlockquote: () => ({ commands }) => {
        return commands.toggleWrap(this.name);
      },
      unsetBlockquote: () => ({ commands }) => {
        return commands.lift(this.name);
      }
    };
  },
  addKeyboardShortcuts() {
    return {
      "Mod-Shift-b": () => this.editor.commands.toggleBlockquote()
    };
  },
  addInputRules() {
    return [
      wrappingInputRule({
        find: inputRegex,
        type: this.type
      })
    ];
  }
});

// ../../node_modules/.pnpm/@tiptap+extension-bold@3.15.3_@tiptap+core@3.15.3_@tiptap+pm@3.15.3_/node_modules/@tiptap/extension-bold/dist/index.js
var starInputRegex = /(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))$/;
var starPasteRegex = /(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))/g;
var underscoreInputRegex = /(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))$/;
var underscorePasteRegex = /(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))/g;
var Bold = Mark2.create({
  name: "bold",
  addOptions() {
    return {
      HTMLAttributes: {}
    };
  },
  parseHTML() {
    return [
      {
        tag: "strong"
      },
      {
        tag: "b",
        getAttrs: (node) => node.style.fontWeight !== "normal" && null
      },
      {
        style: "font-weight=400",
        clearMark: (mark) => mark.type.name === this.name
      },
      {
        style: "font-weight",
        getAttrs: (value) => /^(bold(er)?|[5-9]\d{2,})$/.test(value) && null
      }
    ];
  },
  renderHTML({ HTMLAttributes }) {
    return /* @__PURE__ */ h("strong", { ...mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), children: /* @__PURE__ */ h("slot", {}) });
  },
  markdownTokenName: "strong",
  parseMarkdown: (token, helpers) => {
    return helpers.applyMark("bold", helpers.parseInline(token.tokens || []));
  },
  renderMarkdown: (node, h2) => {
    return `**${h2.renderChildren(node)}**`;
  },
  addCommands() {
    return {
      setBold: () => ({ commands }) => {
        return commands.setMark(this.name);
      },
      toggleBold: () => ({ commands }) => {
        return commands.toggleMark(this.name);
      },
      unsetBold: () => ({ commands }) => {
        return commands.unsetMark(this.name);
      }
    };
  },
  addKeyboardShortcuts() {
    return {
      "Mod-b": () => this.editor.commands.toggleBold(),
      "Mod-B": () => this.editor.commands.toggleBold()
    };
  },
  addInputRules() {
    return [
      markInputRule({
        find: starInputRegex,
        type: this.type
      }),
      markInputRule({
        find: underscoreInputRegex,
        type: this.type
      })
    ];
  },
  addPasteRules() {
    return [
      markPasteRule({
        find: starPasteRegex,
        type: this.type
      }),
      markPasteRule({
        find: underscorePasteRegex,
        type: this.type
      })
    ];
  }
});

// ../../node_modules/.pnpm/@tiptap+extension-code@3.15.3_@tiptap+core@3.15.3_@tiptap+pm@3.15.3_/node_modules/@tiptap/extension-code/dist/index.js
var inputRegex2 = /(^|[^`])`([^`]+)`(?!`)$/;
var pasteRegex = /(^|[^`])`([^`]+)`(?!`)/g;
var Code = Mark2.create({
  name: "code",
  addOptions() {
    return {
      HTMLAttributes: {}
    };
  },
  excludes: "_",
  code: true,
  exitable: true,
  parseHTML() {
    return [{ tag: "code" }];
  },
  renderHTML({ HTMLAttributes }) {
    return ["code", mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), 0];
  },
  markdownTokenName: "codespan",
  parseMarkdown: (token, helpers) => {
    return helpers.applyMark("code", [{ type: "text", text: token.text || "" }]);
  },
  renderMarkdown: (node, h2) => {
    if (!node.content) {
      return "";
    }
    return `\`${h2.renderChildren(node.content)}\``;
  },
  addCommands() {
    return {
      setCode: () => ({ commands }) => {
        return commands.setMark(this.name);
      },
      toggleCode: () => ({ commands }) => {
        return commands.toggleMark(this.name);
      },
      unsetCode: () => ({ commands }) => {
        return commands.unsetMark(this.name);
      }
    };
  },
  addKeyboardShortcuts() {
    return {
      "Mod-e": () => this.editor.commands.toggleCode()
    };
  },
  addInputRules() {
    return [
      markInputRule({
        find: inputRegex2,
        type: this.type
      })
    ];
  },
  addPasteRules() {
    return [
      markPasteRule({
        find: pasteRegex,
        type: this.type
      })
    ];
  }
});

// ../../node_modules/.pnpm/@tiptap+extension-code-block@3.15.3_@tiptap+core@3.15.3_@tiptap+pm@3.15.3__@tiptap+pm@3.15.3/node_modules/@tiptap/extension-code-block/dist/index.js
var DEFAULT_TAB_SIZE = 4;
var backtickInputRegex = /^```([a-z]+)?[\s\n]$/;
var tildeInputRegex = /^~~~([a-z]+)?[\s\n]$/;
var CodeBlock = Node3.create({
  name: "codeBlock",
  addOptions() {
    return {
      languageClassPrefix: "language-",
      exitOnTripleEnter: true,
      exitOnArrowDown: true,
      defaultLanguage: null,
      enableTabIndentation: false,
      tabSize: DEFAULT_TAB_SIZE,
      HTMLAttributes: {}
    };
  },
  content: "text*",
  marks: "",
  group: "block",
  code: true,
  defining: true,
  addAttributes() {
    return {
      language: {
        default: this.options.defaultLanguage,
        parseHTML: (element) => {
          var _a;
          const { languageClassPrefix } = this.options;
          if (!languageClassPrefix) {
            return null;
          }
          const classNames = [...((_a = element.firstElementChild) == null ? void 0 : _a.classList) || []];
          const languages = classNames.filter((className) => className.startsWith(languageClassPrefix)).map((className) => className.replace(languageClassPrefix, ""));
          const language = languages[0];
          if (!language) {
            return null;
          }
          return language;
        },
        rendered: false
      }
    };
  },
  parseHTML() {
    return [
      {
        tag: "pre",
        preserveWhitespace: "full"
      }
    ];
  },
  renderHTML({ node, HTMLAttributes }) {
    return [
      "pre",
      mergeAttributes(this.options.HTMLAttributes, HTMLAttributes),
      [
        "code",
        {
          class: node.attrs.language ? this.options.languageClassPrefix + node.attrs.language : null
        },
        0
      ]
    ];
  },
  markdownTokenName: "code",
  parseMarkdown: (token, helpers) => {
    var _a;
    if (((_a = token.raw) == null ? void 0 : _a.startsWith("```")) === false && token.codeBlockStyle !== "indented") {
      return [];
    }
    return helpers.createNode(
      "codeBlock",
      { language: token.lang || null },
      token.text ? [helpers.createTextNode(token.text)] : []
    );
  },
  renderMarkdown: (node, h2) => {
    var _a;
    let output7 = "";
    const language = ((_a = node.attrs) == null ? void 0 : _a.language) || "";
    if (!node.content) {
      output7 = `\`\`\`${language}

\`\`\``;
    } else {
      const lines = [`\`\`\`${language}`, h2.renderChildren(node.content), "```"];
      output7 = lines.join("\n");
    }
    return output7;
  },
  addCommands() {
    return {
      setCodeBlock: (attributes) => ({ commands }) => {
        return commands.setNode(this.name, attributes);
      },
      toggleCodeBlock: (attributes) => ({ commands }) => {
        return commands.toggleNode(this.name, "paragraph", attributes);
      }
    };
  },
  addKeyboardShortcuts() {
    return {
      "Mod-Alt-c": () => this.editor.commands.toggleCodeBlock(),
      // remove code block when at start of document or code block is empty
      Backspace: () => {
        const { empty: empty2, $anchor } = this.editor.state.selection;
        const isAtStart = $anchor.pos === 1;
        if (!empty2 || $anchor.parent.type.name !== this.name) {
          return false;
        }
        if (isAtStart || !$anchor.parent.textContent.length) {
          return this.editor.commands.clearNodes();
        }
        return false;
      },
      // handle tab indentation
      Tab: ({ editor }) => {
        var _a;
        if (!this.options.enableTabIndentation) {
          return false;
        }
        const tabSize = (_a = this.options.tabSize) != null ? _a : DEFAULT_TAB_SIZE;
        const { state } = editor;
        const { selection } = state;
        const { $from, empty: empty2 } = selection;
        if ($from.parent.type !== this.type) {
          return false;
        }
        const indent = " ".repeat(tabSize);
        if (empty2) {
          return editor.commands.insertContent(indent);
        }
        return editor.commands.command(({ tr: tr2 }) => {
          const { from: from2, to } = selection;
          const text5 = state.doc.textBetween(from2, to, "\n", "\n");
          const lines = text5.split("\n");
          const indentedText = lines.map((line) => indent + line).join("\n");
          tr2.replaceWith(from2, to, state.schema.text(indentedText));
          return true;
        });
      },
      // handle shift+tab reverse indentation
      "Shift-Tab": ({ editor }) => {
        var _a;
        if (!this.options.enableTabIndentation) {
          return false;
        }
        const tabSize = (_a = this.options.tabSize) != null ? _a : DEFAULT_TAB_SIZE;
        const { state } = editor;
        const { selection } = state;
        const { $from, empty: empty2 } = selection;
        if ($from.parent.type !== this.type) {
          return false;
        }
        if (empty2) {
          return editor.commands.command(({ tr: tr2 }) => {
            var _a2;
            const { pos } = $from;
            const codeBlockStart = $from.start();
            const codeBlockEnd = $from.end();
            const allText = state.doc.textBetween(codeBlockStart, codeBlockEnd, "\n", "\n");
            const lines = allText.split("\n");
            let currentLineIndex = 0;
            let charCount = 0;
            const relativeCursorPos = pos - codeBlockStart;
            for (let i = 0; i < lines.length; i += 1) {
              if (charCount + lines[i].length >= relativeCursorPos) {
                currentLineIndex = i;
                break;
              }
              charCount += lines[i].length + 1;
            }
            const currentLine = lines[currentLineIndex];
            const leadingSpaces = ((_a2 = currentLine.match(/^ */)) == null ? void 0 : _a2[0]) || "";
            const spacesToRemove = Math.min(leadingSpaces.length, tabSize);
            if (spacesToRemove === 0) {
              return true;
            }
            let lineStartPos = codeBlockStart;
            for (let i = 0; i < currentLineIndex; i += 1) {
              lineStartPos += lines[i].length + 1;
            }
            tr2.delete(lineStartPos, lineStartPos + spacesToRemove);
            const cursorPosInLine = pos - lineStartPos;
            if (cursorPosInLine <= spacesToRemove) {
              tr2.setSelection(TextSelection.create(tr2.doc, lineStartPos));
            }
            return true;
          });
        }
        return editor.commands.command(({ tr: tr2 }) => {
          const { from: from2, to } = selection;
          const text5 = state.doc.textBetween(from2, to, "\n", "\n");
          const lines = text5.split("\n");
          const reverseIndentText = lines.map((line) => {
            var _a2;
            const leadingSpaces = ((_a2 = line.match(/^ */)) == null ? void 0 : _a2[0]) || "";
            const spacesToRemove = Math.min(leadingSpaces.length, tabSize);
            return line.slice(spacesToRemove);
          }).join("\n");
          tr2.replaceWith(from2, to, state.schema.text(reverseIndentText));
          return true;
        });
      },
      // exit node on triple enter
      Enter: ({ editor }) => {
        if (!this.options.exitOnTripleEnter) {
          return false;
        }
        const { state } = editor;
        const { selection } = state;
        const { $from, empty: empty2 } = selection;
        if (!empty2 || $from.parent.type !== this.type) {
          return false;
        }
        const isAtEnd = $from.parentOffset === $from.parent.nodeSize - 2;
        const endsWithDoubleNewline = $from.parent.textContent.endsWith("\n\n");
        if (!isAtEnd || !endsWithDoubleNewline) {
          return false;
        }
        return editor.chain().command(({ tr: tr2 }) => {
          tr2.delete($from.pos - 2, $from.pos);
          return true;
        }).exitCode().run();
      },
      // exit node on arrow down
      ArrowDown: ({ editor }) => {
        if (!this.options.exitOnArrowDown) {
          return false;
        }
        const { state } = editor;
        const { selection, doc: doc3 } = state;
        const { $from, empty: empty2 } = selection;
        if (!empty2 || $from.parent.type !== this.type) {
          return false;
        }
        const isAtEnd = $from.parentOffset === $from.parent.nodeSize - 2;
        if (!isAtEnd) {
          return false;
        }
        const after = $from.after();
        if (after === void 0) {
          return false;
        }
        const nodeAfter = doc3.nodeAt(after);
        if (nodeAfter) {
          return editor.commands.command(({ tr: tr2 }) => {
            tr2.setSelection(Selection.near(doc3.resolve(after)));
            return true;
          });
        }
        return editor.commands.exitCode();
      }
    };
  },
  addInputRules() {
    return [
      textblockTypeInputRule({
        find: backtickInputRegex,
        type: this.type,
        getAttributes: (match) => ({
          language: match[1]
        })
      }),
      textblockTypeInputRule({
        find: tildeInputRegex,
        type: this.type,
        getAttributes: (match) => ({
          language: match[1]
        })
      })
    ];
  },
  addProseMirrorPlugins() {
    return [
      // this plugin creates a code block for pasted content from VS Code
      // we can also detect the copied code language
      new Plugin({
        key: new PluginKey("codeBlockVSCodeHandler"),
        props: {
          handlePaste: (view, event) => {
            if (!event.clipboardData) {
              return false;
            }
            if (this.editor.isActive(this.type.name)) {
              return false;
            }
            const text5 = event.clipboardData.getData("text/plain");
            const vscode = event.clipboardData.getData("vscode-editor-data");
            const vscodeData = vscode ? JSON.parse(vscode) : void 0;
            const language = vscodeData == null ? void 0 : vscodeData.mode;
            if (!text5 || !language) {
              return false;
            }
            const { tr: tr2, schema } = view.state;
            const textNode = schema.text(text5.replace(/\r\n?/g, "\n"));
            tr2.replaceSelectionWith(this.type.create({ language }, textNode));
            if (tr2.selection.$from.parent.type !== this.type) {
              tr2.setSelection(TextSelection.near(tr2.doc.resolve(Math.max(0, tr2.selection.from - 2))));
            }
            tr2.setMeta("paste", true);
            view.dispatch(tr2);
            return true;
          }
        }
      })
    ];
  }
});

// ../../node_modules/.pnpm/@tiptap+extension-document@3.15.3_@tiptap+core@3.15.3_@tiptap+pm@3.15.3_/node_modules/@tiptap/extension-document/dist/index.js
var Document = Node3.create({
  name: "doc",
  topNode: true,
  content: "block+",
  renderMarkdown: (node, h2) => {
    if (!node.content) {
      return "";
    }
    return h2.renderChildren(node.content, "\n\n");
  }
});

// ../../node_modules/.pnpm/@tiptap+extension-hard-break@3.15.3_@tiptap+core@3.15.3_@tiptap+pm@3.15.3_/node_modules/@tiptap/extension-hard-break/dist/index.js
var HardBreak = Node3.create({
  name: "hardBreak",
  markdownTokenName: "br",
  addOptions() {
    return {
      keepMarks: true,
      HTMLAttributes: {}
    };
  },
  inline: true,
  group: "inline",
  selectable: false,
  linebreakReplacement: true,
  parseHTML() {
    return [{ tag: "br" }];
  },
  renderHTML({ HTMLAttributes }) {
    return ["br", mergeAttributes(this.options.HTMLAttributes, HTMLAttributes)];
  },
  renderText() {
    return "\n";
  },
  renderMarkdown: () => `  
`,
  parseMarkdown: () => {
    return {
      type: "hardBreak"
    };
  },
  addCommands() {
    return {
      setHardBreak: () => ({ commands, chain, state, editor }) => {
        return commands.first([
          () => commands.exitCode(),
          () => commands.command(() => {
            const { selection, storedMarks } = state;
            if (selection.$from.parent.type.spec.isolating) {
              return false;
            }
            const { keepMarks } = this.options;
            const { splittableMarks } = editor.extensionManager;
            const marks = storedMarks || selection.$to.parentOffset && selection.$from.marks();
            return chain().insertContent({ type: this.name }).command(({ tr: tr2, dispatch }) => {
              if (dispatch && marks && keepMarks) {
                const filteredMarks = marks.filter((mark) => splittableMarks.includes(mark.type.name));
                tr2.ensureMarks(filteredMarks);
              }
              return true;
            }).run();
          })
        ]);
      }
    };
  },
  addKeyboardShortcuts() {
    return {
      "Mod-Enter": () => this.editor.commands.setHardBreak(),
      "Shift-Enter": () => this.editor.commands.setHardBreak()
    };
  }
});

// ../../node_modules/.pnpm/@tiptap+extension-heading@3.15.3_@tiptap+core@3.15.3_@tiptap+pm@3.15.3_/node_modules/@tiptap/extension-heading/dist/index.js
var Heading = Node3.create({
  name: "heading",
  addOptions() {
    return {
      levels: [1, 2, 3, 4, 5, 6],
      HTMLAttributes: {}
    };
  },
  content: "inline*",
  group: "block",
  defining: true,
  addAttributes() {
    return {
      level: {
        default: 1,
        rendered: false
      }
    };
  },
  parseHTML() {
    return this.options.levels.map((level) => ({
      tag: `h${level}`,
      attrs: { level }
    }));
  },
  renderHTML({ node, HTMLAttributes }) {
    const hasLevel = this.options.levels.includes(node.attrs.level);
    const level = hasLevel ? node.attrs.level : this.options.levels[0];
    return [`h${level}`, mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), 0];
  },
  parseMarkdown: (token, helpers) => {
    return helpers.createNode("heading", { level: token.depth || 1 }, helpers.parseInline(token.tokens || []));
  },
  renderMarkdown: (node, h2) => {
    var _a;
    const level = ((_a = node.attrs) == null ? void 0 : _a.level) ? parseInt(node.attrs.level, 10) : 1;
    const headingChars = "#".repeat(level);
    if (!node.content) {
      return "";
    }
    return `${headingChars} ${h2.renderChildren(node.content)}`;
  },
  addCommands() {
    return {
      setHeading: (attributes) => ({ commands }) => {
        if (!this.options.levels.includes(attributes.level)) {
          return false;
        }
        return commands.setNode(this.name, attributes);
      },
      toggleHeading: (attributes) => ({ commands }) => {
        if (!this.options.levels.includes(attributes.level)) {
          return false;
        }
        return commands.toggleNode(this.name, "paragraph", attributes);
      }
    };
  },
  addKeyboardShortcuts() {
    return this.options.levels.reduce(
      (items, level) => ({
        ...items,
        ...{
          [`Mod-Alt-${level}`]: () => this.editor.commands.toggleHeading({ level })
        }
      }),
      {}
    );
  },
  addInputRules() {
    return this.options.levels.map((level) => {
      return textblockTypeInputRule({
        find: new RegExp(`^(#{${Math.min(...this.options.levels)},${level}})\\s$`),
        type: this.type,
        getAttributes: {
          level
        }
      });
    });
  }
});

// ../../node_modules/.pnpm/@tiptap+extension-horizontal-rule@3.15.3_@tiptap+core@3.15.3_@tiptap+pm@3.15.3__@tiptap+pm@3.15.3/node_modules/@tiptap/extension-horizontal-rule/dist/index.js
var HorizontalRule = Node3.create({
  name: "horizontalRule",
  addOptions() {
    return {
      HTMLAttributes: {},
      nextNodeType: "paragraph"
    };
  },
  group: "block",
  parseHTML() {
    return [{ tag: "hr" }];
  },
  renderHTML({ HTMLAttributes }) {
    return ["hr", mergeAttributes(this.options.HTMLAttributes, HTMLAttributes)];
  },
  markdownTokenName: "hr",
  parseMarkdown: (token, helpers) => {
    return helpers.createNode("horizontalRule");
  },
  renderMarkdown: () => {
    return "---";
  },
  addCommands() {
    return {
      setHorizontalRule: () => ({ chain, state }) => {
        if (!canInsertNode(state, state.schema.nodes[this.name])) {
          return false;
        }
        const { selection } = state;
        const { $to: $originTo } = selection;
        const currentChain = chain();
        if (isNodeSelection(selection)) {
          currentChain.insertContentAt($originTo.pos, {
            type: this.name
          });
        } else {
          currentChain.insertContent({ type: this.name });
        }
        return currentChain.command(({ state: chainState, tr: tr2, dispatch }) => {
          if (dispatch) {
            const { $to } = tr2.selection;
            const posAfter2 = $to.end();
            if ($to.nodeAfter) {
              if ($to.nodeAfter.isTextblock) {
                tr2.setSelection(TextSelection.create(tr2.doc, $to.pos + 1));
              } else if ($to.nodeAfter.isBlock) {
                tr2.setSelection(NodeSelection.create(tr2.doc, $to.pos));
              } else {
                tr2.setSelection(TextSelection.create(tr2.doc, $to.pos));
              }
            } else {
              const nodeType = chainState.schema.nodes[this.options.nextNodeType] || $to.parent.type.contentMatch.defaultType;
              const node = nodeType == null ? void 0 : nodeType.create();
              if (node) {
                tr2.insert(posAfter2, node);
                tr2.setSelection(TextSelection.create(tr2.doc, posAfter2 + 1));
              }
            }
            tr2.scrollIntoView();
          }
          return true;
        }).run();
      }
    };
  },
  addInputRules() {
    return [
      nodeInputRule({
        find: /^(?:---|—-|___\s|\*\*\*\s)$/,
        type: this.type
      })
    ];
  }
});

// ../../node_modules/.pnpm/@tiptap+extension-italic@3.15.3_@tiptap+core@3.15.3_@tiptap+pm@3.15.3_/node_modules/@tiptap/extension-italic/dist/index.js
var starInputRegex2 = /(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))$/;
var starPasteRegex2 = /(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))/g;
var underscoreInputRegex2 = /(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))$/;
var underscorePasteRegex2 = /(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))/g;
var Italic = Mark2.create({
  name: "italic",
  addOptions() {
    return {
      HTMLAttributes: {}
    };
  },
  parseHTML() {
    return [
      {
        tag: "em"
      },
      {
        tag: "i",
        getAttrs: (node) => node.style.fontStyle !== "normal" && null
      },
      {
        style: "font-style=normal",
        clearMark: (mark) => mark.type.name === this.name
      },
      {
        style: "font-style=italic"
      }
    ];
  },
  renderHTML({ HTMLAttributes }) {
    return ["em", mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), 0];
  },
  addCommands() {
    return {
      setItalic: () => ({ commands }) => {
        return commands.setMark(this.name);
      },
      toggleItalic: () => ({ commands }) => {
        return commands.toggleMark(this.name);
      },
      unsetItalic: () => ({ commands }) => {
        return commands.unsetMark(this.name);
      }
    };
  },
  markdownTokenName: "em",
  parseMarkdown: (token, helpers) => {
    return helpers.applyMark("italic", helpers.parseInline(token.tokens || []));
  },
  renderMarkdown: (node, h2) => {
    return `*${h2.renderChildren(node)}*`;
  },
  addKeyboardShortcuts() {
    return {
      "Mod-i": () => this.editor.commands.toggleItalic(),
      "Mod-I": () => this.editor.commands.toggleItalic()
    };
  },
  addInputRules() {
    return [
      markInputRule({
        find: starInputRegex2,
        type: this.type
      }),
      markInputRule({
        find: underscoreInputRegex2,
        type: this.type
      })
    ];
  },
  addPasteRules() {
    return [
      markPasteRule({
        find: starPasteRegex2,
        type: this.type
      }),
      markPasteRule({
        find: underscorePasteRegex2,
        type: this.type
      })
    ];
  }
});

// ../../node_modules/.pnpm/linkifyjs@4.3.2/node_modules/linkifyjs/dist/linkify.mjs
var encodedTlds = " \xF6gensberater2ung14sicherung10t2g1i0ajes4deo3g1king4llas4n1p1rgin4sa1ion4va1o3laanderen9n1odka3lvo3te1ing3o2yage5u2wales2mart4ter4ng0gou5tch0es6eather0channel12bcam3er2site5d0ding5ibo2r3f1hoswho6ien2ki2lliamhill9n0dows4e1ners6me2olterskluwer11odside6rk0s2ld3w2s1tc1f3xbox3erox4ihuan4n2xx2yz3yachts4hoo3maxun5ndex5e1odobashi7ga2kohama6u0tube6t1un3za0ppos4ra3ero3ip2m1one3uerich6w2";
var encodedUtlds = "\u03B5\u03BB1\u03C52\u0431\u04331\u0435\u043B3\u0434\u0435\u0442\u04384\u0435\u044E2\u043A\u0430\u0442\u043E\u043B\u0438\u043A6\u043E\u043C3\u043C\u043A\u04342\u043E\u043D1\u0441\u043A\u0432\u04306\u043E\u043D\u043B\u0430\u0439\u043D5\u0440\u04333\u0440\u0443\u04412\u04442\u0441\u0430\u0439\u04423\u0440\u04313\u0443\u043A\u04403\u049B\u0430\u04373\u0570\u0561\u05753\u05D9\u05E9\u05E8\u05D0\u05DC5\u05E7\u05D5\u05DD3\u0627\u0628\u0648\u0638\u0628\u064A5\u0631\u0627\u0645\u0643\u06485\u0644\u0627\u0631\u062F\u06464\u0628\u062D\u0631\u064A\u06465\u062C\u0632\u0627\u0626\u06315\u0633\u0639\u0648\u062F\u064A\u06296\u0639\u0644\u064A\u0627\u06465\u0645\u063A\u0631\u06285\u0645\u0627\u0631\u0627\u062A5\u06CC\u0631\u0627\u06465\u0628\u0627\u0631\u062A2\u0632\u0627\u06314\u064A\u062A\u06433\u06BE\u0627\u0631\u062A5\u062A\u0648\u0646\u06334\u0633\u0648\u062F\u0627\u06463\u0631\u064A\u06295\u0634\u0628\u0643\u06294\u0639\u0631\u0627\u06422\u06282\u0645\u0627\u06464\u0641\u0644\u0633\u0637\u064A\u06466\u0642\u0637\u06313\u0643\u0627\u062B\u0648\u0644\u064A\u06436\u0648\u06453\u0645\u0635\u06312\u0644\u064A\u0633\u064A\u06275\u0648\u0631\u064A\u062A\u0627\u0646\u064A\u06277\u0642\u06394\u0647\u0645\u0631\u0627\u06475\u067E\u0627\u06A9\u0633\u062A\u0627\u06467\u0680\u0627\u0631\u062A4\u0915\u0949\u092E3\u0928\u0947\u091F3\u092D\u093E\u0930\u09240\u092E\u094D3\u094B\u09245\u0938\u0902\u0917\u0920\u09285\u09AC\u09BE\u0982\u09B2\u09BE5\u09AD\u09BE\u09B0\u09A42\u09F0\u09A44\u0A2D\u0A3E\u0A30\u0A244\u0AAD\u0ABE\u0AB0\u0AA44\u0B2D\u0B3E\u0B30\u0B244\u0B87\u0BA8\u0BCD\u0BA4\u0BBF\u0BAF\u0BBE6\u0BB2\u0B99\u0BCD\u0B95\u0BC86\u0B9A\u0BBF\u0B99\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0BC2\u0BB0\u0BCD11\u0C2D\u0C3E\u0C30\u0C24\u0C4D5\u0CAD\u0CBE\u0CB0\u0CA44\u0D2D\u0D3E\u0D30\u0D24\u0D025\u0DBD\u0D82\u0D9A\u0DCF4\u0E04\u0E2D\u0E213\u0E44\u0E17\u0E223\u0EA5\u0EB2\u0EA73\u10D2\u10D42\u307F\u3093\u306A3\u30A2\u30DE\u30BE\u30F34\u30AF\u30E9\u30A6\u30C94\u30B0\u30FC\u30B0\u30EB4\u30B3\u30E02\u30B9\u30C8\u30A23\u30BB\u30FC\u30EB3\u30D5\u30A1\u30C3\u30B7\u30E7\u30F36\u30DD\u30A4\u30F3\u30C84\u4E16\u754C2\u4E2D\u4FE11\u56FD1\u570B1\u6587\u7F513\u4E9A\u9A6C\u900A3\u4F01\u4E1A2\u4F5B\u5C712\u4FE1\u606F2\u5065\u5EB72\u516B\u53662\u516C\u53F81\u76CA2\u53F0\u6E7E1\u70632\u5546\u57CE1\u5E971\u68072\u5609\u91CC0\u5927\u9152\u5E975\u5728\u7EBF2\u5927\u62FF2\u5929\u4E3B\u65593\u5A31\u4E502\u5BB6\u96FB2\u5E7F\u4E1C2\u5FAE\u535A2\u6148\u55842\u6211\u7231\u4F603\u624B\u673A2\u62DB\u80582\u653F\u52A11\u5E9C2\u65B0\u52A0\u57612\u95FB2\u65F6\u5C1A2\u66F8\u7C4D2\u673A\u67842\u6DE1\u9A6C\u95213\u6E38\u620F2\u6FB3\u95802\u70B9\u770B2\u79FB\u52A82\u7EC4\u7EC7\u673A\u67844\u7F51\u57401\u5E971\u7AD91\u7EDC2\u8054\u901A2\u8C37\u6B4C2\u8D2D\u72692\u901A\u8CA92\u96C6\u56E22\u96FB\u8A0A\u76C8\u79D14\u98DE\u5229\u6D663\u98DF\u54C12\u9910\u53852\u9999\u683C\u91CC\u62C93\u6E2F2\uB2F7\uB1371\uCEF42\uC0BC\uC1312\uD55C\uAD6D2";
var numeric = "numeric";
var ascii = "ascii";
var alpha = "alpha";
var asciinumeric = "asciinumeric";
var alphanumeric = "alphanumeric";
var domain = "domain";
var emoji = "emoji";
var scheme = "scheme";
var slashscheme = "slashscheme";
var whitespace = "whitespace";
function registerGroup(name, groups) {
  if (!(name in groups)) {
    groups[name] = [];
  }
  return groups[name];
}
function addToGroups(t, flags, groups) {
  if (flags[numeric]) {
    flags[asciinumeric] = true;
    flags[alphanumeric] = true;
  }
  if (flags[ascii]) {
    flags[asciinumeric] = true;
    flags[alpha] = true;
  }
  if (flags[asciinumeric]) {
    flags[alphanumeric] = true;
  }
  if (flags[alpha]) {
    flags[alphanumeric] = true;
  }
  if (flags[alphanumeric]) {
    flags[domain] = true;
  }
  if (flags[emoji]) {
    flags[domain] = true;
  }
  for (const k in flags) {
    const group = registerGroup(k, groups);
    if (group.indexOf(t) < 0) {
      group.push(t);
    }
  }
}
function flagsForToken(t, groups) {
  const result = {};
  for (const c in groups) {
    if (groups[c].indexOf(t) >= 0) {
      result[c] = true;
    }
  }
  return result;
}
function State(token = null) {
  this.j = {};
  this.jr = [];
  this.jd = null;
  this.t = token;
}
State.groups = {};
State.prototype = {
  accepts() {
    return !!this.t;
  },
  /**
   * Follow an existing transition from the given input to the next state.
   * Does not mutate.
   * @param {string} input character or token type to transition on
   * @returns {?State<T>} the next state, if any
   */
  go(input) {
    const state = this;
    const nextState = state.j[input];
    if (nextState) {
      return nextState;
    }
    for (let i = 0; i < state.jr.length; i++) {
      const regex = state.jr[i][0];
      const nextState2 = state.jr[i][1];
      if (nextState2 && regex.test(input)) {
        return nextState2;
      }
    }
    return state.jd;
  },
  /**
   * Whether the state has a transition for the given input. Set the second
   * argument to true to only look for an exact match (and not a default or
   * regular-expression-based transition)
   * @param {string} input
   * @param {boolean} exactOnly
   */
  has(input, exactOnly = false) {
    return exactOnly ? input in this.j : !!this.go(input);
  },
  /**
   * Short for "transition all"; create a transition from the array of items
   * in the given list to the same final resulting state.
   * @param {string | string[]} inputs Group of inputs to transition on
   * @param {Transition<T> | State<T>} [next] Transition options
   * @param {Flags} [flags] Collections flags to add token to
   * @param {Collections<T>} [groups] Master list of token groups
   */
  ta(inputs, next, flags, groups) {
    for (let i = 0; i < inputs.length; i++) {
      this.tt(inputs[i], next, flags, groups);
    }
  },
  /**
   * Short for "take regexp transition"; defines a transition for this state
   * when it encounters a token which matches the given regular expression
   * @param {RegExp} regexp Regular expression transition (populate first)
   * @param {T | State<T>} [next] Transition options
   * @param {Flags} [flags] Collections flags to add token to
   * @param {Collections<T>} [groups] Master list of token groups
   * @returns {State<T>} taken after the given input
   */
  tr(regexp, next, flags, groups) {
    groups = groups || State.groups;
    let nextState;
    if (next && next.j) {
      nextState = next;
    } else {
      nextState = new State(next);
      if (flags && groups) {
        addToGroups(next, flags, groups);
      }
    }
    this.jr.push([regexp, nextState]);
    return nextState;
  },
  /**
   * Short for "take transitions", will take as many sequential transitions as
   * the length of the given input and returns the
   * resulting final state.
   * @param {string | string[]} input
   * @param {T | State<T>} [next] Transition options
   * @param {Flags} [flags] Collections flags to add token to
   * @param {Collections<T>} [groups] Master list of token groups
   * @returns {State<T>} taken after the given input
   */
  ts(input, next, flags, groups) {
    let state = this;
    const len = input.length;
    if (!len) {
      return state;
    }
    for (let i = 0; i < len - 1; i++) {
      state = state.tt(input[i]);
    }
    return state.tt(input[len - 1], next, flags, groups);
  },
  /**
   * Short for "take transition", this is a method for building/working with
   * state machines.
   *
   * If a state already exists for the given input, returns it.
   *
   * If a token is specified, that state will emit that token when reached by
   * the linkify engine.
   *
   * If no state exists, it will be initialized with some default transitions
   * that resemble existing default transitions.
   *
   * If a state is given for the second argument, that state will be
   * transitioned to on the given input regardless of what that input
   * previously did.
   *
   * Specify a token group flags to define groups that this token belongs to.
   * The token will be added to corresponding entires in the given groups
   * object.
   *
   * @param {string} input character, token type to transition on
   * @param {T | State<T>} [next] Transition options
   * @param {Flags} [flags] Collections flags to add token to
   * @param {Collections<T>} [groups] Master list of groups
   * @returns {State<T>} taken after the given input
   */
  tt(input, next, flags, groups) {
    groups = groups || State.groups;
    const state = this;
    if (next && next.j) {
      state.j[input] = next;
      return next;
    }
    const t = next;
    let nextState, templateState = state.go(input);
    if (templateState) {
      nextState = new State();
      Object.assign(nextState.j, templateState.j);
      nextState.jr.push.apply(nextState.jr, templateState.jr);
      nextState.jd = templateState.jd;
      nextState.t = templateState.t;
    } else {
      nextState = new State();
    }
    if (t) {
      if (groups) {
        if (nextState.t && typeof nextState.t === "string") {
          const allFlags = Object.assign(flagsForToken(nextState.t, groups), flags);
          addToGroups(t, allFlags, groups);
        } else if (flags) {
          addToGroups(t, flags, groups);
        }
      }
      nextState.t = t;
    }
    state.j[input] = nextState;
    return nextState;
  }
};
var ta = (state, input, next, flags, groups) => state.ta(input, next, flags, groups);
var tr = (state, regexp, next, flags, groups) => state.tr(regexp, next, flags, groups);
var ts = (state, input, next, flags, groups) => state.ts(input, next, flags, groups);
var tt = (state, input, next, flags, groups) => state.tt(input, next, flags, groups);
var WORD = "WORD";
var UWORD = "UWORD";
var ASCIINUMERICAL = "ASCIINUMERICAL";
var ALPHANUMERICAL = "ALPHANUMERICAL";
var LOCALHOST = "LOCALHOST";
var TLD = "TLD";
var UTLD = "UTLD";
var SCHEME = "SCHEME";
var SLASH_SCHEME = "SLASH_SCHEME";
var NUM = "NUM";
var WS = "WS";
var NL = "NL";
var OPENBRACE = "OPENBRACE";
var CLOSEBRACE = "CLOSEBRACE";
var OPENBRACKET = "OPENBRACKET";
var CLOSEBRACKET = "CLOSEBRACKET";
var OPENPAREN = "OPENPAREN";
var CLOSEPAREN = "CLOSEPAREN";
var OPENANGLEBRACKET = "OPENANGLEBRACKET";
var CLOSEANGLEBRACKET = "CLOSEANGLEBRACKET";
var FULLWIDTHLEFTPAREN = "FULLWIDTHLEFTPAREN";
var FULLWIDTHRIGHTPAREN = "FULLWIDTHRIGHTPAREN";
var LEFTCORNERBRACKET = "LEFTCORNERBRACKET";
var RIGHTCORNERBRACKET = "RIGHTCORNERBRACKET";
var LEFTWHITECORNERBRACKET = "LEFTWHITECORNERBRACKET";
var RIGHTWHITECORNERBRACKET = "RIGHTWHITECORNERBRACKET";
var FULLWIDTHLESSTHAN = "FULLWIDTHLESSTHAN";
var FULLWIDTHGREATERTHAN = "FULLWIDTHGREATERTHAN";
var AMPERSAND = "AMPERSAND";
var APOSTROPHE = "APOSTROPHE";
var ASTERISK = "ASTERISK";
var AT = "AT";
var BACKSLASH = "BACKSLASH";
var BACKTICK = "BACKTICK";
var CARET = "CARET";
var COLON = "COLON";
var COMMA = "COMMA";
var DOLLAR = "DOLLAR";
var DOT = "DOT";
var EQUALS = "EQUALS";
var EXCLAMATION = "EXCLAMATION";
var HYPHEN = "HYPHEN";
var PERCENT = "PERCENT";
var PIPE = "PIPE";
var PLUS = "PLUS";
var POUND = "POUND";
var QUERY = "QUERY";
var QUOTE = "QUOTE";
var FULLWIDTHMIDDLEDOT = "FULLWIDTHMIDDLEDOT";
var SEMI = "SEMI";
var SLASH = "SLASH";
var TILDE = "TILDE";
var UNDERSCORE = "UNDERSCORE";
var EMOJI$1 = "EMOJI";
var SYM = "SYM";
var tk = /* @__PURE__ */ Object.freeze({
  __proto__: null,
  ALPHANUMERICAL,
  AMPERSAND,
  APOSTROPHE,
  ASCIINUMERICAL,
  ASTERISK,
  AT,
  BACKSLASH,
  BACKTICK,
  CARET,
  CLOSEANGLEBRACKET,
  CLOSEBRACE,
  CLOSEBRACKET,
  CLOSEPAREN,
  COLON,
  COMMA,
  DOLLAR,
  DOT,
  EMOJI: EMOJI$1,
  EQUALS,
  EXCLAMATION,
  FULLWIDTHGREATERTHAN,
  FULLWIDTHLEFTPAREN,
  FULLWIDTHLESSTHAN,
  FULLWIDTHMIDDLEDOT,
  FULLWIDTHRIGHTPAREN,
  HYPHEN,
  LEFTCORNERBRACKET,
  LEFTWHITECORNERBRACKET,
  LOCALHOST,
  NL,
  NUM,
  OPENANGLEBRACKET,
  OPENBRACE,
  OPENBRACKET,
  OPENPAREN,
  PERCENT,
  PIPE,
  PLUS,
  POUND,
  QUERY,
  QUOTE,
  RIGHTCORNERBRACKET,
  RIGHTWHITECORNERBRACKET,
  SCHEME,
  SEMI,
  SLASH,
  SLASH_SCHEME,
  SYM,
  TILDE,
  TLD,
  UNDERSCORE,
  UTLD,
  UWORD,
  WORD,
  WS
});
var ASCII_LETTER = /[a-z]/;
var LETTER = new RegExp("\\p{L}", "u");
var EMOJI = new RegExp("\\p{Emoji}", "u");
var DIGIT = /\d/;
var SPACE = /\s/;
var CR = "\r";
var LF = "\n";
var EMOJI_VARIATION = "\uFE0F";
var EMOJI_JOINER = "\u200D";
var OBJECT_REPLACEMENT = "\uFFFC";
var tlds = null;
var utlds = null;
function init$2(customSchemes = []) {
  const groups = {};
  State.groups = groups;
  const Start = new State();
  if (tlds == null) {
    tlds = decodeTlds(encodedTlds);
  }
  if (utlds == null) {
    utlds = decodeTlds(encodedUtlds);
  }
  tt(Start, "'", APOSTROPHE);
  tt(Start, "{", OPENBRACE);
  tt(Start, "}", CLOSEBRACE);
  tt(Start, "[", OPENBRACKET);
  tt(Start, "]", CLOSEBRACKET);
  tt(Start, "(", OPENPAREN);
  tt(Start, ")", CLOSEPAREN);
  tt(Start, "<", OPENANGLEBRACKET);
  tt(Start, ">", CLOSEANGLEBRACKET);
  tt(Start, "\uFF08", FULLWIDTHLEFTPAREN);
  tt(Start, "\uFF09", FULLWIDTHRIGHTPAREN);
  tt(Start, "\u300C", LEFTCORNERBRACKET);
  tt(Start, "\u300D", RIGHTCORNERBRACKET);
  tt(Start, "\u300E", LEFTWHITECORNERBRACKET);
  tt(Start, "\u300F", RIGHTWHITECORNERBRACKET);
  tt(Start, "\uFF1C", FULLWIDTHLESSTHAN);
  tt(Start, "\uFF1E", FULLWIDTHGREATERTHAN);
  tt(Start, "&", AMPERSAND);
  tt(Start, "*", ASTERISK);
  tt(Start, "@", AT);
  tt(Start, "`", BACKTICK);
  tt(Start, "^", CARET);
  tt(Start, ":", COLON);
  tt(Start, ",", COMMA);
  tt(Start, "$", DOLLAR);
  tt(Start, ".", DOT);
  tt(Start, "=", EQUALS);
  tt(Start, "!", EXCLAMATION);
  tt(Start, "-", HYPHEN);
  tt(Start, "%", PERCENT);
  tt(Start, "|", PIPE);
  tt(Start, "+", PLUS);
  tt(Start, "#", POUND);
  tt(Start, "?", QUERY);
  tt(Start, '"', QUOTE);
  tt(Start, "/", SLASH);
  tt(Start, ";", SEMI);
  tt(Start, "~", TILDE);
  tt(Start, "_", UNDERSCORE);
  tt(Start, "\\", BACKSLASH);
  tt(Start, "\u30FB", FULLWIDTHMIDDLEDOT);
  const Num = tr(Start, DIGIT, NUM, {
    [numeric]: true
  });
  tr(Num, DIGIT, Num);
  const Asciinumeric = tr(Num, ASCII_LETTER, ASCIINUMERICAL, {
    [asciinumeric]: true
  });
  const Alphanumeric = tr(Num, LETTER, ALPHANUMERICAL, {
    [alphanumeric]: true
  });
  const Word = tr(Start, ASCII_LETTER, WORD, {
    [ascii]: true
  });
  tr(Word, DIGIT, Asciinumeric);
  tr(Word, ASCII_LETTER, Word);
  tr(Asciinumeric, DIGIT, Asciinumeric);
  tr(Asciinumeric, ASCII_LETTER, Asciinumeric);
  const UWord = tr(Start, LETTER, UWORD, {
    [alpha]: true
  });
  tr(UWord, ASCII_LETTER);
  tr(UWord, DIGIT, Alphanumeric);
  tr(UWord, LETTER, UWord);
  tr(Alphanumeric, DIGIT, Alphanumeric);
  tr(Alphanumeric, ASCII_LETTER);
  tr(Alphanumeric, LETTER, Alphanumeric);
  const Nl2 = tt(Start, LF, NL, {
    [whitespace]: true
  });
  const Cr = tt(Start, CR, WS, {
    [whitespace]: true
  });
  const Ws = tr(Start, SPACE, WS, {
    [whitespace]: true
  });
  tt(Start, OBJECT_REPLACEMENT, Ws);
  tt(Cr, LF, Nl2);
  tt(Cr, OBJECT_REPLACEMENT, Ws);
  tr(Cr, SPACE, Ws);
  tt(Ws, CR);
  tt(Ws, LF);
  tr(Ws, SPACE, Ws);
  tt(Ws, OBJECT_REPLACEMENT, Ws);
  const Emoji = tr(Start, EMOJI, EMOJI$1, {
    [emoji]: true
  });
  tt(Emoji, "#");
  tr(Emoji, EMOJI, Emoji);
  tt(Emoji, EMOJI_VARIATION, Emoji);
  const EmojiJoiner = tt(Emoji, EMOJI_JOINER);
  tt(EmojiJoiner, "#");
  tr(EmojiJoiner, EMOJI, Emoji);
  const wordjr = [[ASCII_LETTER, Word], [DIGIT, Asciinumeric]];
  const uwordjr = [[ASCII_LETTER, null], [LETTER, UWord], [DIGIT, Alphanumeric]];
  for (let i = 0; i < tlds.length; i++) {
    fastts(Start, tlds[i], TLD, WORD, wordjr);
  }
  for (let i = 0; i < utlds.length; i++) {
    fastts(Start, utlds[i], UTLD, UWORD, uwordjr);
  }
  addToGroups(TLD, {
    tld: true,
    ascii: true
  }, groups);
  addToGroups(UTLD, {
    utld: true,
    alpha: true
  }, groups);
  fastts(Start, "file", SCHEME, WORD, wordjr);
  fastts(Start, "mailto", SCHEME, WORD, wordjr);
  fastts(Start, "http", SLASH_SCHEME, WORD, wordjr);
  fastts(Start, "https", SLASH_SCHEME, WORD, wordjr);
  fastts(Start, "ftp", SLASH_SCHEME, WORD, wordjr);
  fastts(Start, "ftps", SLASH_SCHEME, WORD, wordjr);
  addToGroups(SCHEME, {
    scheme: true,
    ascii: true
  }, groups);
  addToGroups(SLASH_SCHEME, {
    slashscheme: true,
    ascii: true
  }, groups);
  customSchemes = customSchemes.sort((a2, b2) => a2[0] > b2[0] ? 1 : -1);
  for (let i = 0; i < customSchemes.length; i++) {
    const sch = customSchemes[i][0];
    const optionalSlashSlash = customSchemes[i][1];
    const flags = optionalSlashSlash ? {
      [scheme]: true
    } : {
      [slashscheme]: true
    };
    if (sch.indexOf("-") >= 0) {
      flags[domain] = true;
    } else if (!ASCII_LETTER.test(sch)) {
      flags[numeric] = true;
    } else if (DIGIT.test(sch)) {
      flags[asciinumeric] = true;
    } else {
      flags[ascii] = true;
    }
    ts(Start, sch, sch, flags);
  }
  ts(Start, "localhost", LOCALHOST, {
    ascii: true
  });
  Start.jd = new State(SYM);
  return {
    start: Start,
    tokens: Object.assign({
      groups
    }, tk)
  };
}
function run$1(start, str) {
  const iterable = stringToArray(str.replace(/[A-Z]/g, (c) => c.toLowerCase()));
  const charCount = iterable.length;
  const tokens = [];
  let cursor = 0;
  let charCursor = 0;
  while (charCursor < charCount) {
    let state = start;
    let nextState = null;
    let tokenLength = 0;
    let latestAccepting = null;
    let sinceAccepts = -1;
    let charsSinceAccepts = -1;
    while (charCursor < charCount && (nextState = state.go(iterable[charCursor]))) {
      state = nextState;
      if (state.accepts()) {
        sinceAccepts = 0;
        charsSinceAccepts = 0;
        latestAccepting = state;
      } else if (sinceAccepts >= 0) {
        sinceAccepts += iterable[charCursor].length;
        charsSinceAccepts++;
      }
      tokenLength += iterable[charCursor].length;
      cursor += iterable[charCursor].length;
      charCursor++;
    }
    cursor -= sinceAccepts;
    charCursor -= charsSinceAccepts;
    tokenLength -= sinceAccepts;
    tokens.push({
      t: latestAccepting.t,
      // token type/name
      v: str.slice(cursor - tokenLength, cursor),
      // string value
      s: cursor - tokenLength,
      // start index
      e: cursor
      // end index (excluding)
    });
  }
  return tokens;
}
function stringToArray(str) {
  const result = [];
  const len = str.length;
  let index = 0;
  while (index < len) {
    let first2 = str.charCodeAt(index);
    let second;
    let char = first2 < 55296 || first2 > 56319 || index + 1 === len || (second = str.charCodeAt(index + 1)) < 56320 || second > 57343 ? str[index] : str.slice(index, index + 2);
    result.push(char);
    index += char.length;
  }
  return result;
}
function fastts(state, input, t, defaultt, jr) {
  let next;
  const len = input.length;
  for (let i = 0; i < len - 1; i++) {
    const char = input[i];
    if (state.j[char]) {
      next = state.j[char];
    } else {
      next = new State(defaultt);
      next.jr = jr.slice();
      state.j[char] = next;
    }
    state = next;
  }
  next = new State(t);
  next.jr = jr.slice();
  state.j[input[len - 1]] = next;
  return next;
}
function decodeTlds(encoded) {
  const words = [];
  const stack = [];
  let i = 0;
  let digits = "0123456789";
  while (i < encoded.length) {
    let popDigitCount = 0;
    while (digits.indexOf(encoded[i + popDigitCount]) >= 0) {
      popDigitCount++;
    }
    if (popDigitCount > 0) {
      words.push(stack.join(""));
      for (let popCount = parseInt(encoded.substring(i, i + popDigitCount), 10); popCount > 0; popCount--) {
        stack.pop();
      }
      i += popDigitCount;
    } else {
      stack.push(encoded[i]);
      i++;
    }
  }
  return words;
}
var defaults = {
  defaultProtocol: "http",
  events: null,
  format: noop,
  formatHref: noop,
  nl2br: false,
  tagName: "a",
  target: null,
  rel: null,
  validate: true,
  truncate: Infinity,
  className: null,
  attributes: null,
  ignoreTags: [],
  render: null
};
function Options(opts, defaultRender = null) {
  let o2 = Object.assign({}, defaults);
  if (opts) {
    o2 = Object.assign(o2, opts instanceof Options ? opts.o : opts);
  }
  const ignoredTags = o2.ignoreTags;
  const uppercaseIgnoredTags = [];
  for (let i = 0; i < ignoredTags.length; i++) {
    uppercaseIgnoredTags.push(ignoredTags[i].toUpperCase());
  }
  this.o = o2;
  if (defaultRender) {
    this.defaultRender = defaultRender;
  }
  this.ignoreTags = uppercaseIgnoredTags;
}
Options.prototype = {
  o: defaults,
  /**
   * @type string[]
   */
  ignoreTags: [],
  /**
   * @param {IntermediateRepresentation} ir
   * @returns {any}
   */
  defaultRender(ir) {
    return ir;
  },
  /**
   * Returns true or false based on whether a token should be displayed as a
   * link based on the user options.
   * @param {MultiToken} token
   * @returns {boolean}
   */
  check(token) {
    return this.get("validate", token.toString(), token);
  },
  // Private methods
  /**
   * Resolve an option's value based on the value of the option and the given
   * params. If operator and token are specified and the target option is
   * callable, automatically calls the function with the given argument.
   * @template {keyof Opts} K
   * @param {K} key Name of option to use
   * @param {string} [operator] will be passed to the target option if it's a
   * function. If not specified, RAW function value gets returned
   * @param {MultiToken} [token] The token from linkify.tokenize
   * @returns {Opts[K] | any}
   */
  get(key, operator3, token) {
    const isCallable = operator3 != null;
    let option = this.o[key];
    if (!option) {
      return option;
    }
    if (typeof option === "object") {
      option = token.t in option ? option[token.t] : defaults[key];
      if (typeof option === "function" && isCallable) {
        option = option(operator3, token);
      }
    } else if (typeof option === "function" && isCallable) {
      option = option(operator3, token.t, token);
    }
    return option;
  },
  /**
   * @template {keyof Opts} L
   * @param {L} key Name of options object to use
   * @param {string} [operator]
   * @param {MultiToken} [token]
   * @returns {Opts[L] | any}
   */
  getObj(key, operator3, token) {
    let obj = this.o[key];
    if (typeof obj === "function" && operator3 != null) {
      obj = obj(operator3, token.t, token);
    }
    return obj;
  },
  /**
   * Convert the given token to a rendered element that may be added to the
   * calling-interface's DOM
   * @param {MultiToken} token Token to render to an HTML element
   * @returns {any} Render result; e.g., HTML string, DOM element, React
   *   Component, etc.
   */
  render(token) {
    const ir = token.render(this);
    const renderFn = this.get("render", null, token) || this.defaultRender;
    return renderFn(ir, token.t, token);
  }
};
function noop(val) {
  return val;
}
function MultiToken(value, tokens) {
  this.t = "token";
  this.v = value;
  this.tk = tokens;
}
MultiToken.prototype = {
  isLink: false,
  /**
   * Return the string this token represents.
   * @return {string}
   */
  toString() {
    return this.v;
  },
  /**
   * What should the value for this token be in the `href` HTML attribute?
   * Returns the `.toString` value by default.
   * @param {string} [scheme]
   * @return {string}
   */
  toHref(scheme2) {
    return this.toString();
  },
  /**
   * @param {Options} options Formatting options
   * @returns {string}
   */
  toFormattedString(options) {
    const val = this.toString();
    const truncate = options.get("truncate", val, this);
    const formatted = options.get("format", val, this);
    return truncate && formatted.length > truncate ? formatted.substring(0, truncate) + "\u2026" : formatted;
  },
  /**
   *
   * @param {Options} options
   * @returns {string}
   */
  toFormattedHref(options) {
    return options.get("formatHref", this.toHref(options.get("defaultProtocol")), this);
  },
  /**
   * The start index of this token in the original input string
   * @returns {number}
   */
  startIndex() {
    return this.tk[0].s;
  },
  /**
   * The end index of this token in the original input string (up to this
   * index but not including it)
   * @returns {number}
   */
  endIndex() {
    return this.tk[this.tk.length - 1].e;
  },
  /**
  	Returns an object  of relevant values for this token, which includes keys
  	* type - Kind of token ('url', 'email', etc.)
  	* value - Original text
  	* href - The value that should be added to the anchor tag's href
  		attribute
  		@method toObject
  	@param {string} [protocol] `'http'` by default
  */
  toObject(protocol = defaults.defaultProtocol) {
    return {
      type: this.t,
      value: this.toString(),
      isLink: this.isLink,
      href: this.toHref(protocol),
      start: this.startIndex(),
      end: this.endIndex()
    };
  },
  /**
   *
   * @param {Options} options Formatting option
   */
  toFormattedObject(options) {
    return {
      type: this.t,
      value: this.toFormattedString(options),
      isLink: this.isLink,
      href: this.toFormattedHref(options),
      start: this.startIndex(),
      end: this.endIndex()
    };
  },
  /**
   * Whether this token should be rendered as a link according to the given options
   * @param {Options} options
   * @returns {boolean}
   */
  validate(options) {
    return options.get("validate", this.toString(), this);
  },
  /**
   * Return an object that represents how this link should be rendered.
   * @param {Options} options Formattinng options
   */
  render(options) {
    const token = this;
    const href = this.toHref(options.get("defaultProtocol"));
    const formattedHref = options.get("formatHref", href, this);
    const tagName = options.get("tagName", href, token);
    const content = this.toFormattedString(options);
    const attributes = {};
    const className = options.get("className", href, token);
    const target2 = options.get("target", href, token);
    const rel2 = options.get("rel", href, token);
    const attrs = options.getObj("attributes", href, token);
    const eventListeners = options.getObj("events", href, token);
    attributes.href = formattedHref;
    if (className) {
      attributes.class = className;
    }
    if (target2) {
      attributes.target = target2;
    }
    if (rel2) {
      attributes.rel = rel2;
    }
    if (attrs) {
      Object.assign(attributes, attrs);
    }
    return {
      tagName,
      attributes,
      content,
      eventListeners
    };
  }
};
function createTokenClass(type, props) {
  class Token2 extends MultiToken {
    constructor(value, tokens) {
      super(value, tokens);
      this.t = type;
    }
  }
  for (const p2 in props) {
    Token2.prototype[p2] = props[p2];
  }
  Token2.t = type;
  return Token2;
}
var Email = createTokenClass("email", {
  isLink: true,
  toHref() {
    return "mailto:" + this.toString();
  }
});
var Text = createTokenClass("text");
var Nl = createTokenClass("nl");
var Url = createTokenClass("url", {
  isLink: true,
  /**
  	Lowercases relevant parts of the domain and adds the protocol if
  	required. Note that this will not escape unsafe HTML characters in the
  	URL.
  		@param {string} [scheme] default scheme (e.g., 'https')
  	@return {string} the full href
  */
  toHref(scheme2 = defaults.defaultProtocol) {
    return this.hasProtocol() ? this.v : `${scheme2}://${this.v}`;
  },
  /**
   * Check whether this URL token has a protocol
   * @return {boolean}
   */
  hasProtocol() {
    const tokens = this.tk;
    return tokens.length >= 2 && tokens[0].t !== LOCALHOST && tokens[1].t === COLON;
  }
});
var makeState = (arg) => new State(arg);
function init$1({
  groups
}) {
  const qsAccepting = groups.domain.concat([AMPERSAND, ASTERISK, AT, BACKSLASH, BACKTICK, CARET, DOLLAR, EQUALS, HYPHEN, NUM, PERCENT, PIPE, PLUS, POUND, SLASH, SYM, TILDE, UNDERSCORE]);
  const qsNonAccepting = [APOSTROPHE, COLON, COMMA, DOT, EXCLAMATION, PERCENT, QUERY, QUOTE, SEMI, OPENANGLEBRACKET, CLOSEANGLEBRACKET, OPENBRACE, CLOSEBRACE, CLOSEBRACKET, OPENBRACKET, OPENPAREN, CLOSEPAREN, FULLWIDTHLEFTPAREN, FULLWIDTHRIGHTPAREN, LEFTCORNERBRACKET, RIGHTCORNERBRACKET, LEFTWHITECORNERBRACKET, RIGHTWHITECORNERBRACKET, FULLWIDTHLESSTHAN, FULLWIDTHGREATERTHAN];
  const localpartAccepting = [AMPERSAND, APOSTROPHE, ASTERISK, BACKSLASH, BACKTICK, CARET, DOLLAR, EQUALS, HYPHEN, OPENBRACE, CLOSEBRACE, PERCENT, PIPE, PLUS, POUND, QUERY, SLASH, SYM, TILDE, UNDERSCORE];
  const Start = makeState();
  const Localpart = tt(Start, TILDE);
  ta(Localpart, localpartAccepting, Localpart);
  ta(Localpart, groups.domain, Localpart);
  const Domain = makeState(), Scheme = makeState(), SlashScheme = makeState();
  ta(Start, groups.domain, Domain);
  ta(Start, groups.scheme, Scheme);
  ta(Start, groups.slashscheme, SlashScheme);
  ta(Domain, localpartAccepting, Localpart);
  ta(Domain, groups.domain, Domain);
  const LocalpartAt = tt(Domain, AT);
  tt(Localpart, AT, LocalpartAt);
  tt(Scheme, AT, LocalpartAt);
  tt(SlashScheme, AT, LocalpartAt);
  const LocalpartDot = tt(Localpart, DOT);
  ta(LocalpartDot, localpartAccepting, Localpart);
  ta(LocalpartDot, groups.domain, Localpart);
  const EmailDomain = makeState();
  ta(LocalpartAt, groups.domain, EmailDomain);
  ta(EmailDomain, groups.domain, EmailDomain);
  const EmailDomainDot = tt(EmailDomain, DOT);
  ta(EmailDomainDot, groups.domain, EmailDomain);
  const Email$1 = makeState(Email);
  ta(EmailDomainDot, groups.tld, Email$1);
  ta(EmailDomainDot, groups.utld, Email$1);
  tt(LocalpartAt, LOCALHOST, Email$1);
  const EmailDomainHyphen = tt(EmailDomain, HYPHEN);
  tt(EmailDomainHyphen, HYPHEN, EmailDomainHyphen);
  ta(EmailDomainHyphen, groups.domain, EmailDomain);
  ta(Email$1, groups.domain, EmailDomain);
  tt(Email$1, DOT, EmailDomainDot);
  tt(Email$1, HYPHEN, EmailDomainHyphen);
  const EmailColon = tt(Email$1, COLON);
  ta(EmailColon, groups.numeric, Email);
  const DomainHyphen = tt(Domain, HYPHEN);
  const DomainDot = tt(Domain, DOT);
  tt(DomainHyphen, HYPHEN, DomainHyphen);
  ta(DomainHyphen, groups.domain, Domain);
  ta(DomainDot, localpartAccepting, Localpart);
  ta(DomainDot, groups.domain, Domain);
  const DomainDotTld = makeState(Url);
  ta(DomainDot, groups.tld, DomainDotTld);
  ta(DomainDot, groups.utld, DomainDotTld);
  ta(DomainDotTld, groups.domain, Domain);
  ta(DomainDotTld, localpartAccepting, Localpart);
  tt(DomainDotTld, DOT, DomainDot);
  tt(DomainDotTld, HYPHEN, DomainHyphen);
  tt(DomainDotTld, AT, LocalpartAt);
  const DomainDotTldColon = tt(DomainDotTld, COLON);
  const DomainDotTldColonPort = makeState(Url);
  ta(DomainDotTldColon, groups.numeric, DomainDotTldColonPort);
  const Url$1 = makeState(Url);
  const UrlNonaccept = makeState();
  ta(Url$1, qsAccepting, Url$1);
  ta(Url$1, qsNonAccepting, UrlNonaccept);
  ta(UrlNonaccept, qsAccepting, Url$1);
  ta(UrlNonaccept, qsNonAccepting, UrlNonaccept);
  tt(DomainDotTld, SLASH, Url$1);
  tt(DomainDotTldColonPort, SLASH, Url$1);
  const SchemeColon = tt(Scheme, COLON);
  const SlashSchemeColon = tt(SlashScheme, COLON);
  const SlashSchemeColonSlash = tt(SlashSchemeColon, SLASH);
  const UriPrefix = tt(SlashSchemeColonSlash, SLASH);
  ta(Scheme, groups.domain, Domain);
  tt(Scheme, DOT, DomainDot);
  tt(Scheme, HYPHEN, DomainHyphen);
  ta(SlashScheme, groups.domain, Domain);
  tt(SlashScheme, DOT, DomainDot);
  tt(SlashScheme, HYPHEN, DomainHyphen);
  ta(SchemeColon, groups.domain, Url$1);
  tt(SchemeColon, SLASH, Url$1);
  tt(SchemeColon, QUERY, Url$1);
  ta(UriPrefix, groups.domain, Url$1);
  ta(UriPrefix, qsAccepting, Url$1);
  tt(UriPrefix, SLASH, Url$1);
  const bracketPairs = [
    [OPENBRACE, CLOSEBRACE],
    // {}
    [OPENBRACKET, CLOSEBRACKET],
    // []
    [OPENPAREN, CLOSEPAREN],
    // ()
    [OPENANGLEBRACKET, CLOSEANGLEBRACKET],
    // <>
    [FULLWIDTHLEFTPAREN, FULLWIDTHRIGHTPAREN],
    // （）
    [LEFTCORNERBRACKET, RIGHTCORNERBRACKET],
    // 「」
    [LEFTWHITECORNERBRACKET, RIGHTWHITECORNERBRACKET],
    // 『』
    [FULLWIDTHLESSTHAN, FULLWIDTHGREATERTHAN]
    // ＜＞
  ];
  for (let i = 0; i < bracketPairs.length; i++) {
    const [OPEN, CLOSE] = bracketPairs[i];
    const UrlOpen = tt(Url$1, OPEN);
    tt(UrlNonaccept, OPEN, UrlOpen);
    tt(UrlOpen, CLOSE, Url$1);
    const UrlOpenQ = makeState(Url);
    ta(UrlOpen, qsAccepting, UrlOpenQ);
    const UrlOpenSyms = makeState();
    ta(UrlOpen, qsNonAccepting);
    ta(UrlOpenQ, qsAccepting, UrlOpenQ);
    ta(UrlOpenQ, qsNonAccepting, UrlOpenSyms);
    ta(UrlOpenSyms, qsAccepting, UrlOpenQ);
    ta(UrlOpenSyms, qsNonAccepting, UrlOpenSyms);
    tt(UrlOpenQ, CLOSE, Url$1);
    tt(UrlOpenSyms, CLOSE, Url$1);
  }
  tt(Start, LOCALHOST, DomainDotTld);
  tt(Start, NL, Nl);
  return {
    start: Start,
    tokens: tk
  };
}
function run3(start, input, tokens) {
  let len = tokens.length;
  let cursor = 0;
  let multis = [];
  let textTokens = [];
  while (cursor < len) {
    let state = start;
    let secondState = null;
    let nextState = null;
    let multiLength = 0;
    let latestAccepting = null;
    let sinceAccepts = -1;
    while (cursor < len && !(secondState = state.go(tokens[cursor].t))) {
      textTokens.push(tokens[cursor++]);
    }
    while (cursor < len && (nextState = secondState || state.go(tokens[cursor].t))) {
      secondState = null;
      state = nextState;
      if (state.accepts()) {
        sinceAccepts = 0;
        latestAccepting = state;
      } else if (sinceAccepts >= 0) {
        sinceAccepts++;
      }
      cursor++;
      multiLength++;
    }
    if (sinceAccepts < 0) {
      cursor -= multiLength;
      if (cursor < len) {
        textTokens.push(tokens[cursor]);
        cursor++;
      }
    } else {
      if (textTokens.length > 0) {
        multis.push(initMultiToken(Text, input, textTokens));
        textTokens = [];
      }
      cursor -= sinceAccepts;
      multiLength -= sinceAccepts;
      const Multi = latestAccepting.t;
      const subtokens = tokens.slice(cursor - multiLength, cursor);
      multis.push(initMultiToken(Multi, input, subtokens));
    }
  }
  if (textTokens.length > 0) {
    multis.push(initMultiToken(Text, input, textTokens));
  }
  return multis;
}
function initMultiToken(Multi, input, tokens) {
  const startIdx = tokens[0].s;
  const endIdx = tokens[tokens.length - 1].e;
  const value = input.slice(startIdx, endIdx);
  return new Multi(value, tokens);
}
var warn = typeof console !== "undefined" && console && console.warn || (() => {
});
var warnAdvice = "until manual call of linkify.init(). Register all schemes and plugins before invoking linkify the first time.";
var INIT = {
  scanner: null,
  parser: null,
  tokenQueue: [],
  pluginQueue: [],
  customSchemes: [],
  initialized: false
};
function reset() {
  State.groups = {};
  INIT.scanner = null;
  INIT.parser = null;
  INIT.tokenQueue = [];
  INIT.pluginQueue = [];
  INIT.customSchemes = [];
  INIT.initialized = false;
  return INIT;
}
function registerCustomProtocol(scheme2, optionalSlashSlash = false) {
  if (INIT.initialized) {
    warn(`linkifyjs: already initialized - will not register custom scheme "${scheme2}" ${warnAdvice}`);
  }
  if (!/^[0-9a-z]+(-[0-9a-z]+)*$/.test(scheme2)) {
    throw new Error(`linkifyjs: incorrect scheme format.
1. Must only contain digits, lowercase ASCII letters or "-"
2. Cannot start or end with "-"
3. "-" cannot repeat`);
  }
  INIT.customSchemes.push([scheme2, optionalSlashSlash]);
}
function init() {
  INIT.scanner = init$2(INIT.customSchemes);
  for (let i = 0; i < INIT.tokenQueue.length; i++) {
    INIT.tokenQueue[i][1]({
      scanner: INIT.scanner
    });
  }
  INIT.parser = init$1(INIT.scanner.tokens);
  for (let i = 0; i < INIT.pluginQueue.length; i++) {
    INIT.pluginQueue[i][1]({
      scanner: INIT.scanner,
      parser: INIT.parser
    });
  }
  INIT.initialized = true;
  return INIT;
}
function tokenize(str) {
  if (!INIT.initialized) {
    init();
  }
  return run3(INIT.parser.start, str, run$1(INIT.scanner.start, str));
}
tokenize.scan = run$1;
function find(str, type = null, opts = null) {
  if (type && typeof type === "object") {
    if (opts) {
      throw Error(`linkifyjs: Invalid link type ${type}; must be a string`);
    }
    opts = type;
    type = null;
  }
  const options = new Options(opts);
  const tokens = tokenize(str);
  const filtered = [];
  for (let i = 0; i < tokens.length; i++) {
    const token = tokens[i];
    if (token.isLink && (!type || token.t === type) && options.check(token)) {
      filtered.push(token.toFormattedObject(options));
    }
  }
  return filtered;
}

// ../../node_modules/.pnpm/@tiptap+extension-link@3.15.3_@tiptap+core@3.15.3_@tiptap+pm@3.15.3__@tiptap+pm@3.15.3/node_modules/@tiptap/extension-link/dist/index.js
var UNICODE_WHITESPACE_PATTERN = "[\0- \xA0\u1680\u180E\u2000-\u2029\u205F\u3000]";
var UNICODE_WHITESPACE_REGEX = new RegExp(UNICODE_WHITESPACE_PATTERN);
var UNICODE_WHITESPACE_REGEX_END = new RegExp(`${UNICODE_WHITESPACE_PATTERN}$`);
var UNICODE_WHITESPACE_REGEX_GLOBAL = new RegExp(UNICODE_WHITESPACE_PATTERN, "g");
function isValidLinkStructure(tokens) {
  if (tokens.length === 1) {
    return tokens[0].isLink;
  }
  if (tokens.length === 3 && tokens[1].isLink) {
    return ["()", "[]"].includes(tokens[0].value + tokens[2].value);
  }
  return false;
}
function autolink(options) {
  return new Plugin({
    key: new PluginKey("autolink"),
    appendTransaction: (transactions, oldState, newState) => {
      const docChanges = transactions.some((transaction) => transaction.docChanged) && !oldState.doc.eq(newState.doc);
      const preventAutolink = transactions.some((transaction) => transaction.getMeta("preventAutolink"));
      if (!docChanges || preventAutolink) {
        return;
      }
      const { tr: tr2 } = newState;
      const transform = combineTransactionSteps(oldState.doc, [...transactions]);
      const changes = getChangedRanges(transform);
      changes.forEach(({ newRange }) => {
        const nodesInChangedRanges = findChildrenInRange(newState.doc, newRange, (node) => node.isTextblock);
        let textBlock;
        let textBeforeWhitespace;
        if (nodesInChangedRanges.length > 1) {
          textBlock = nodesInChangedRanges[0];
          textBeforeWhitespace = newState.doc.textBetween(
            textBlock.pos,
            textBlock.pos + textBlock.node.nodeSize,
            void 0,
            " "
          );
        } else if (nodesInChangedRanges.length) {
          const endText = newState.doc.textBetween(newRange.from, newRange.to, " ", " ");
          if (!UNICODE_WHITESPACE_REGEX_END.test(endText)) {
            return;
          }
          textBlock = nodesInChangedRanges[0];
          textBeforeWhitespace = newState.doc.textBetween(textBlock.pos, newRange.to, void 0, " ");
        }
        if (textBlock && textBeforeWhitespace) {
          const wordsBeforeWhitespace = textBeforeWhitespace.split(UNICODE_WHITESPACE_REGEX).filter(Boolean);
          if (wordsBeforeWhitespace.length <= 0) {
            return false;
          }
          const lastWordBeforeSpace = wordsBeforeWhitespace[wordsBeforeWhitespace.length - 1];
          const lastWordAndBlockOffset = textBlock.pos + textBeforeWhitespace.lastIndexOf(lastWordBeforeSpace);
          if (!lastWordBeforeSpace) {
            return false;
          }
          const linksBeforeSpace = tokenize(lastWordBeforeSpace).map((t) => t.toObject(options.defaultProtocol));
          if (!isValidLinkStructure(linksBeforeSpace)) {
            return false;
          }
          linksBeforeSpace.filter((link) => link.isLink).map((link) => ({
            ...link,
            from: lastWordAndBlockOffset + link.start + 1,
            to: lastWordAndBlockOffset + link.end + 1
          })).filter((link) => {
            if (!newState.schema.marks.code) {
              return true;
            }
            return !newState.doc.rangeHasMark(link.from, link.to, newState.schema.marks.code);
          }).filter((link) => options.validate(link.value)).filter((link) => options.shouldAutoLink(link.value)).forEach((link) => {
            if (getMarksBetween(link.from, link.to, newState.doc).some((item) => item.mark.type === options.type)) {
              return;
            }
            tr2.addMark(
              link.from,
              link.to,
              options.type.create({
                href: link.href
              })
            );
          });
        }
      });
      if (!tr2.steps.length) {
        return;
      }
      return tr2;
    }
  });
}
function clickHandler(options) {
  return new Plugin({
    key: new PluginKey("handleClickLink"),
    props: {
      handleClick: (view, pos, event) => {
        var _a, _b;
        if (event.button !== 0) {
          return false;
        }
        if (!view.editable) {
          return false;
        }
        let handled = false;
        if (options.enableClickSelection) {
          const commandResult = options.editor.commands.extendMarkRange(options.type.name);
          handled = commandResult;
        }
        if (options.openOnClick) {
          let link = null;
          if (event.target instanceof HTMLAnchorElement) {
            link = event.target;
          } else {
            let a2 = event.target;
            const els = [];
            while (a2.nodeName !== "DIV") {
              els.push(a2);
              a2 = a2.parentNode;
            }
            link = els.find((value) => value.nodeName === "A");
          }
          if (!link) {
            return handled;
          }
          const attrs = getAttributes(view.state, options.type.name);
          const href = (_a = link == null ? void 0 : link.href) != null ? _a : attrs.href;
          const target2 = (_b = link == null ? void 0 : link.target) != null ? _b : attrs.target;
          if (link && href) {
            window.open(href, target2);
            handled = true;
          }
        }
        return handled;
      }
    }
  });
}
function pasteHandler(options) {
  return new Plugin({
    key: new PluginKey("handlePasteLink"),
    props: {
      handlePaste: (view, _event, slice2) => {
        const { shouldAutoLink } = options;
        const { state } = view;
        const { selection } = state;
        const { empty: empty2 } = selection;
        if (empty2) {
          return false;
        }
        let textContent = "";
        slice2.content.forEach((node) => {
          textContent += node.textContent;
        });
        const link = find(textContent, { defaultProtocol: options.defaultProtocol }).find(
          (item) => item.isLink && item.value === textContent
        );
        if (!textContent || !link || shouldAutoLink !== void 0 && !shouldAutoLink(link.value)) {
          return false;
        }
        return options.editor.commands.setMark(options.type, {
          href: link.href
        });
      }
    }
  });
}
function isAllowedUri(uri, protocols) {
  const allowedProtocols = ["http", "https", "ftp", "ftps", "mailto", "tel", "callto", "sms", "cid", "xmpp"];
  if (protocols) {
    protocols.forEach((protocol) => {
      const nextProtocol = typeof protocol === "string" ? protocol : protocol.scheme;
      if (nextProtocol) {
        allowedProtocols.push(nextProtocol);
      }
    });
  }
  return !uri || uri.replace(UNICODE_WHITESPACE_REGEX_GLOBAL, "").match(
    new RegExp(
      // eslint-disable-next-line no-useless-escape
      `^(?:(?:${allowedProtocols.join("|")}):|[^a-z]|[a-z0-9+.-]+(?:[^a-z+.-:]|$))`,
      "i"
    )
  );
}
var Link = Mark2.create({
  name: "link",
  priority: 1e3,
  keepOnSplit: false,
  exitable: true,
  onCreate() {
    if (this.options.validate && !this.options.shouldAutoLink) {
      this.options.shouldAutoLink = this.options.validate;
      console.warn("The `validate` option is deprecated. Rename to the `shouldAutoLink` option instead.");
    }
    this.options.protocols.forEach((protocol) => {
      if (typeof protocol === "string") {
        registerCustomProtocol(protocol);
        return;
      }
      registerCustomProtocol(protocol.scheme, protocol.optionalSlashes);
    });
  },
  onDestroy() {
    reset();
  },
  inclusive() {
    return this.options.autolink;
  },
  addOptions() {
    return {
      openOnClick: true,
      enableClickSelection: false,
      linkOnPaste: true,
      autolink: true,
      protocols: [],
      defaultProtocol: "http",
      HTMLAttributes: {
        target: "_blank",
        rel: "noopener noreferrer nofollow",
        class: null
      },
      isAllowedUri: (url, ctx) => !!isAllowedUri(url, ctx.protocols),
      validate: (url) => !!url,
      shouldAutoLink: (url) => {
        const hasProtocol = /^[a-z][a-z0-9+.-]*:\/\//i.test(url);
        const hasMaybeProtocol = /^[a-z][a-z0-9+.-]*:/i.test(url);
        if (hasProtocol || hasMaybeProtocol && !url.includes("@")) {
          return true;
        }
        const urlWithoutUserinfo = url.includes("@") ? url.split("@").pop() : url;
        const hostname = urlWithoutUserinfo.split(/[/?#:]/)[0];
        if (/^\d{1,3}(\.\d{1,3}){3}$/.test(hostname)) {
          return false;
        }
        if (!/\./.test(hostname)) {
          return false;
        }
        return true;
      }
    };
  },
  addAttributes() {
    return {
      href: {
        default: null,
        parseHTML(element) {
          return element.getAttribute("href");
        }
      },
      target: {
        default: this.options.HTMLAttributes.target
      },
      rel: {
        default: this.options.HTMLAttributes.rel
      },
      class: {
        default: this.options.HTMLAttributes.class
      }
    };
  },
  parseHTML() {
    return [
      {
        tag: "a[href]",
        getAttrs: (dom) => {
          const href = dom.getAttribute("href");
          if (!href || !this.options.isAllowedUri(href, {
            defaultValidate: (url) => !!isAllowedUri(url, this.options.protocols),
            protocols: this.options.protocols,
            defaultProtocol: this.options.defaultProtocol
          })) {
            return false;
          }
          return null;
        }
      }
    ];
  },
  renderHTML({ HTMLAttributes }) {
    if (!this.options.isAllowedUri(HTMLAttributes.href, {
      defaultValidate: (href) => !!isAllowedUri(href, this.options.protocols),
      protocols: this.options.protocols,
      defaultProtocol: this.options.defaultProtocol
    })) {
      return ["a", mergeAttributes(this.options.HTMLAttributes, { ...HTMLAttributes, href: "" }), 0];
    }
    return ["a", mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), 0];
  },
  markdownTokenName: "link",
  parseMarkdown: (token, helpers) => {
    return helpers.applyMark("link", helpers.parseInline(token.tokens || []), {
      href: token.href,
      title: token.title || null
    });
  },
  renderMarkdown: (node, h2) => {
    var _a;
    const href = ((_a = node.attrs) == null ? void 0 : _a.href) || "";
    const text5 = h2.renderChildren(node);
    return `[${text5}](${href})`;
  },
  addCommands() {
    return {
      setLink: (attributes) => ({ chain }) => {
        const { href } = attributes;
        if (!this.options.isAllowedUri(href, {
          defaultValidate: (url) => !!isAllowedUri(url, this.options.protocols),
          protocols: this.options.protocols,
          defaultProtocol: this.options.defaultProtocol
        })) {
          return false;
        }
        return chain().setMark(this.name, attributes).setMeta("preventAutolink", true).run();
      },
      toggleLink: (attributes) => ({ chain }) => {
        const { href } = attributes || {};
        if (href && !this.options.isAllowedUri(href, {
          defaultValidate: (url) => !!isAllowedUri(url, this.options.protocols),
          protocols: this.options.protocols,
          defaultProtocol: this.options.defaultProtocol
        })) {
          return false;
        }
        return chain().toggleMark(this.name, attributes, { extendEmptyMarkRange: true }).setMeta("preventAutolink", true).run();
      },
      unsetLink: () => ({ chain }) => {
        return chain().unsetMark(this.name, { extendEmptyMarkRange: true }).setMeta("preventAutolink", true).run();
      }
    };
  },
  addPasteRules() {
    return [
      markPasteRule({
        find: (text5) => {
          const foundLinks = [];
          if (text5) {
            const { protocols, defaultProtocol } = this.options;
            const links = find(text5).filter(
              (item) => item.isLink && this.options.isAllowedUri(item.value, {
                defaultValidate: (href) => !!isAllowedUri(href, protocols),
                protocols,
                defaultProtocol
              })
            );
            if (links.length) {
              links.forEach((link) => {
                if (!this.options.shouldAutoLink(link.value)) {
                  return;
                }
                foundLinks.push({
                  text: link.value,
                  data: {
                    href: link.href
                  },
                  index: link.start
                });
              });
            }
          }
          return foundLinks;
        },
        type: this.type,
        getAttributes: (match) => {
          var _a;
          return {
            href: (_a = match.data) == null ? void 0 : _a.href
          };
        }
      })
    ];
  },
  addProseMirrorPlugins() {
    const plugins = [];
    const { protocols, defaultProtocol } = this.options;
    if (this.options.autolink) {
      plugins.push(
        autolink({
          type: this.type,
          defaultProtocol: this.options.defaultProtocol,
          validate: (url) => this.options.isAllowedUri(url, {
            defaultValidate: (href) => !!isAllowedUri(href, protocols),
            protocols,
            defaultProtocol
          }),
          shouldAutoLink: this.options.shouldAutoLink
        })
      );
    }
    plugins.push(
      clickHandler({
        type: this.type,
        editor: this.editor,
        openOnClick: this.options.openOnClick === "whenNotEditable" ? true : this.options.openOnClick,
        enableClickSelection: this.options.enableClickSelection
      })
    );
    if (this.options.linkOnPaste) {
      plugins.push(
        pasteHandler({
          editor: this.editor,
          defaultProtocol: this.options.defaultProtocol,
          type: this.type,
          shouldAutoLink: this.options.shouldAutoLink
        })
      );
    }
    return plugins;
  }
});

// ../../node_modules/.pnpm/@tiptap+extension-list@3.15.3_@tiptap+core@3.15.3_@tiptap+pm@3.15.3__@tiptap+pm@3.15.3/node_modules/@tiptap/extension-list/dist/index.js
var __defProp3 = Object.defineProperty;
var __export2 = (target2, all) => {
  for (var name in all)
    __defProp3(target2, name, { get: all[name], enumerable: true });
};
var ListItemName = "listItem";
var TextStyleName = "textStyle";
var bulletListInputRegex = /^\s*([-+*])\s$/;
var BulletList = Node3.create({
  name: "bulletList",
  addOptions() {
    return {
      itemTypeName: "listItem",
      HTMLAttributes: {},
      keepMarks: false,
      keepAttributes: false
    };
  },
  group: "block list",
  content() {
    return `${this.options.itemTypeName}+`;
  },
  parseHTML() {
    return [{ tag: "ul" }];
  },
  renderHTML({ HTMLAttributes }) {
    return ["ul", mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), 0];
  },
  markdownTokenName: "list",
  parseMarkdown: (token, helpers) => {
    if (token.type !== "list" || token.ordered) {
      return [];
    }
    return {
      type: "bulletList",
      content: token.items ? helpers.parseChildren(token.items) : []
    };
  },
  renderMarkdown: (node, h2) => {
    if (!node.content) {
      return "";
    }
    return h2.renderChildren(node.content, "\n");
  },
  markdownOptions: {
    indentsContent: true
  },
  addCommands() {
    return {
      toggleBulletList: () => ({ commands, chain }) => {
        if (this.options.keepAttributes) {
          return chain().toggleList(this.name, this.options.itemTypeName, this.options.keepMarks).updateAttributes(ListItemName, this.editor.getAttributes(TextStyleName)).run();
        }
        return commands.toggleList(this.name, this.options.itemTypeName, this.options.keepMarks);
      }
    };
  },
  addKeyboardShortcuts() {
    return {
      "Mod-Shift-8": () => this.editor.commands.toggleBulletList()
    };
  },
  addInputRules() {
    let inputRule = wrappingInputRule({
      find: bulletListInputRegex,
      type: this.type
    });
    if (this.options.keepMarks || this.options.keepAttributes) {
      inputRule = wrappingInputRule({
        find: bulletListInputRegex,
        type: this.type,
        keepMarks: this.options.keepMarks,
        keepAttributes: this.options.keepAttributes,
        getAttributes: () => {
          return this.editor.getAttributes(TextStyleName);
        },
        editor: this.editor
      });
    }
    return [inputRule];
  }
});
var ListItem = Node3.create({
  name: "listItem",
  addOptions() {
    return {
      HTMLAttributes: {},
      bulletListTypeName: "bulletList",
      orderedListTypeName: "orderedList"
    };
  },
  content: "paragraph block*",
  defining: true,
  parseHTML() {
    return [
      {
        tag: "li"
      }
    ];
  },
  renderHTML({ HTMLAttributes }) {
    return ["li", mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), 0];
  },
  markdownTokenName: "list_item",
  parseMarkdown: (token, helpers) => {
    if (token.type !== "list_item") {
      return [];
    }
    let content = [];
    if (token.tokens && token.tokens.length > 0) {
      const hasParagraphTokens = token.tokens.some((t) => t.type === "paragraph");
      if (hasParagraphTokens) {
        content = helpers.parseChildren(token.tokens);
      } else {
        const firstToken = token.tokens[0];
        if (firstToken && firstToken.type === "text" && firstToken.tokens && firstToken.tokens.length > 0) {
          const inlineContent = helpers.parseInline(firstToken.tokens);
          content = [
            {
              type: "paragraph",
              content: inlineContent
            }
          ];
          if (token.tokens.length > 1) {
            const remainingTokens = token.tokens.slice(1);
            const additionalContent = helpers.parseChildren(remainingTokens);
            content.push(...additionalContent);
          }
        } else {
          content = helpers.parseChildren(token.tokens);
        }
      }
    }
    if (content.length === 0) {
      content = [
        {
          type: "paragraph",
          content: []
        }
      ];
    }
    return {
      type: "listItem",
      content
    };
  },
  renderMarkdown: (node, h2, ctx) => {
    return renderNestedMarkdownContent(
      node,
      h2,
      (context) => {
        if (context.parentType === "bulletList") {
          return "- ";
        }
        if (context.parentType === "orderedList") {
          return `${context.index + 1}. `;
        }
        return "- ";
      },
      ctx
    );
  },
  addKeyboardShortcuts() {
    return {
      Enter: () => this.editor.commands.splitListItem(this.name),
      Tab: () => this.editor.commands.sinkListItem(this.name),
      "Shift-Tab": () => this.editor.commands.liftListItem(this.name)
    };
  }
});
var listHelpers_exports = {};
__export2(listHelpers_exports, {
  findListItemPos: () => findListItemPos,
  getNextListDepth: () => getNextListDepth,
  handleBackspace: () => handleBackspace,
  handleDelete: () => handleDelete,
  hasListBefore: () => hasListBefore,
  hasListItemAfter: () => hasListItemAfter,
  hasListItemBefore: () => hasListItemBefore,
  listItemHasSubList: () => listItemHasSubList,
  nextListIsDeeper: () => nextListIsDeeper,
  nextListIsHigher: () => nextListIsHigher
});
var findListItemPos = (typeOrName, state) => {
  const { $from } = state.selection;
  const nodeType = getNodeType(typeOrName, state.schema);
  let currentNode = null;
  let currentDepth = $from.depth;
  let currentPos = $from.pos;
  let targetDepth = null;
  while (currentDepth > 0 && targetDepth === null) {
    currentNode = $from.node(currentDepth);
    if (currentNode.type === nodeType) {
      targetDepth = currentDepth;
    } else {
      currentDepth -= 1;
      currentPos -= 1;
    }
  }
  if (targetDepth === null) {
    return null;
  }
  return { $pos: state.doc.resolve(currentPos), depth: targetDepth };
};
var getNextListDepth = (typeOrName, state) => {
  const listItemPos = findListItemPos(typeOrName, state);
  if (!listItemPos) {
    return false;
  }
  const [, depth] = getNodeAtPosition(state, typeOrName, listItemPos.$pos.pos + 4);
  return depth;
};
var hasListBefore = (editorState, name, parentListTypes) => {
  const { $anchor } = editorState.selection;
  const previousNodePos = Math.max(0, $anchor.pos - 2);
  const previousNode = editorState.doc.resolve(previousNodePos).node();
  if (!previousNode || !parentListTypes.includes(previousNode.type.name)) {
    return false;
  }
  return true;
};
var hasListItemBefore = (typeOrName, state) => {
  var _a;
  const { $anchor } = state.selection;
  const $targetPos = state.doc.resolve($anchor.pos - 2);
  if ($targetPos.index() === 0) {
    return false;
  }
  if (((_a = $targetPos.nodeBefore) == null ? void 0 : _a.type.name) !== typeOrName) {
    return false;
  }
  return true;
};
var listItemHasSubList = (typeOrName, state, node) => {
  if (!node) {
    return false;
  }
  const nodeType = getNodeType(typeOrName, state.schema);
  let hasSubList = false;
  node.descendants((child) => {
    if (child.type === nodeType) {
      hasSubList = true;
    }
  });
  return hasSubList;
};
var handleBackspace = (editor, name, parentListTypes) => {
  if (editor.commands.undoInputRule()) {
    return true;
  }
  if (editor.state.selection.from !== editor.state.selection.to) {
    return false;
  }
  if (!isNodeActive(editor.state, name) && hasListBefore(editor.state, name, parentListTypes)) {
    const { $anchor } = editor.state.selection;
    const $listPos = editor.state.doc.resolve($anchor.before() - 1);
    const listDescendants = [];
    $listPos.node().descendants((node, pos) => {
      if (node.type.name === name) {
        listDescendants.push({ node, pos });
      }
    });
    const lastItem = listDescendants.at(-1);
    if (!lastItem) {
      return false;
    }
    const $lastItemPos = editor.state.doc.resolve($listPos.start() + lastItem.pos + 1);
    return editor.chain().cut({ from: $anchor.start() - 1, to: $anchor.end() + 1 }, $lastItemPos.end()).joinForward().run();
  }
  if (!isNodeActive(editor.state, name)) {
    return false;
  }
  if (!isAtStartOfNode(editor.state)) {
    return false;
  }
  const listItemPos = findListItemPos(name, editor.state);
  if (!listItemPos) {
    return false;
  }
  const $prev = editor.state.doc.resolve(listItemPos.$pos.pos - 2);
  const prevNode = $prev.node(listItemPos.depth);
  const previousListItemHasSubList = listItemHasSubList(name, editor.state, prevNode);
  if (hasListItemBefore(name, editor.state) && !previousListItemHasSubList) {
    return editor.commands.joinItemBackward();
  }
  return editor.chain().liftListItem(name).run();
};
var nextListIsDeeper = (typeOrName, state) => {
  const listDepth = getNextListDepth(typeOrName, state);
  const listItemPos = findListItemPos(typeOrName, state);
  if (!listItemPos || !listDepth) {
    return false;
  }
  if (listDepth > listItemPos.depth) {
    return true;
  }
  return false;
};
var nextListIsHigher = (typeOrName, state) => {
  const listDepth = getNextListDepth(typeOrName, state);
  const listItemPos = findListItemPos(typeOrName, state);
  if (!listItemPos || !listDepth) {
    return false;
  }
  if (listDepth < listItemPos.depth) {
    return true;
  }
  return false;
};
var handleDelete = (editor, name) => {
  if (!isNodeActive(editor.state, name)) {
    return false;
  }
  if (!isAtEndOfNode(editor.state, name)) {
    return false;
  }
  const { selection } = editor.state;
  const { $from, $to } = selection;
  if (!selection.empty && $from.sameParent($to)) {
    return false;
  }
  if (nextListIsDeeper(name, editor.state)) {
    return editor.chain().focus(editor.state.selection.from + 4).lift(name).joinBackward().run();
  }
  if (nextListIsHigher(name, editor.state)) {
    return editor.chain().joinForward().joinBackward().run();
  }
  return editor.commands.joinItemForward();
};
var hasListItemAfter = (typeOrName, state) => {
  var _a;
  const { $anchor } = state.selection;
  const $targetPos = state.doc.resolve($anchor.pos - $anchor.parentOffset - 2);
  if ($targetPos.index() === $targetPos.parent.childCount - 1) {
    return false;
  }
  if (((_a = $targetPos.nodeAfter) == null ? void 0 : _a.type.name) !== typeOrName) {
    return false;
  }
  return true;
};
var ListKeymap = Extension.create({
  name: "listKeymap",
  addOptions() {
    return {
      listTypes: [
        {
          itemName: "listItem",
          wrapperNames: ["bulletList", "orderedList"]
        },
        {
          itemName: "taskItem",
          wrapperNames: ["taskList"]
        }
      ]
    };
  },
  addKeyboardShortcuts() {
    return {
      Delete: ({ editor }) => {
        let handled = false;
        this.options.listTypes.forEach(({ itemName }) => {
          if (editor.state.schema.nodes[itemName] === void 0) {
            return;
          }
          if (handleDelete(editor, itemName)) {
            handled = true;
          }
        });
        return handled;
      },
      "Mod-Delete": ({ editor }) => {
        let handled = false;
        this.options.listTypes.forEach(({ itemName }) => {
          if (editor.state.schema.nodes[itemName] === void 0) {
            return;
          }
          if (handleDelete(editor, itemName)) {
            handled = true;
          }
        });
        return handled;
      },
      Backspace: ({ editor }) => {
        let handled = false;
        this.options.listTypes.forEach(({ itemName, wrapperNames }) => {
          if (editor.state.schema.nodes[itemName] === void 0) {
            return;
          }
          if (handleBackspace(editor, itemName, wrapperNames)) {
            handled = true;
          }
        });
        return handled;
      },
      "Mod-Backspace": ({ editor }) => {
        let handled = false;
        this.options.listTypes.forEach(({ itemName, wrapperNames }) => {
          if (editor.state.schema.nodes[itemName] === void 0) {
            return;
          }
          if (handleBackspace(editor, itemName, wrapperNames)) {
            handled = true;
          }
        });
        return handled;
      }
    };
  }
});
var ORDERED_LIST_ITEM_REGEX = /^(\s*)(\d+)\.\s+(.*)$/;
var INDENTED_LINE_REGEX = /^\s/;
function collectOrderedListItems(lines) {
  const listItems = [];
  let currentLineIndex = 0;
  let consumed = 0;
  while (currentLineIndex < lines.length) {
    const line = lines[currentLineIndex];
    const match = line.match(ORDERED_LIST_ITEM_REGEX);
    if (!match) {
      break;
    }
    const [, indent, number2, content] = match;
    const indentLevel = indent.length;
    let itemContent = content;
    let nextLineIndex = currentLineIndex + 1;
    const itemLines = [line];
    while (nextLineIndex < lines.length) {
      const nextLine = lines[nextLineIndex];
      const nextMatch = nextLine.match(ORDERED_LIST_ITEM_REGEX);
      if (nextMatch) {
        break;
      }
      if (nextLine.trim() === "") {
        itemLines.push(nextLine);
        itemContent += "\n";
        nextLineIndex += 1;
      } else if (nextLine.match(INDENTED_LINE_REGEX)) {
        itemLines.push(nextLine);
        itemContent += `
${nextLine.slice(indentLevel + 2)}`;
        nextLineIndex += 1;
      } else {
        break;
      }
    }
    listItems.push({
      indent: indentLevel,
      number: parseInt(number2, 10),
      content: itemContent.trim(),
      raw: itemLines.join("\n")
    });
    consumed = nextLineIndex;
    currentLineIndex = nextLineIndex;
  }
  return [listItems, consumed];
}
function buildNestedStructure(items, baseIndent, lexer) {
  var _a;
  const result = [];
  let currentIndex = 0;
  while (currentIndex < items.length) {
    const item = items[currentIndex];
    if (item.indent === baseIndent) {
      const contentLines = item.content.split("\n");
      const mainText = ((_a = contentLines[0]) == null ? void 0 : _a.trim()) || "";
      const tokens = [];
      if (mainText) {
        tokens.push({
          type: "paragraph",
          raw: mainText,
          tokens: lexer.inlineTokens(mainText)
        });
      }
      const additionalContent = contentLines.slice(1).join("\n").trim();
      if (additionalContent) {
        const blockTokens = lexer.blockTokens(additionalContent);
        tokens.push(...blockTokens);
      }
      let lookAheadIndex = currentIndex + 1;
      const nestedItems = [];
      while (lookAheadIndex < items.length && items[lookAheadIndex].indent > baseIndent) {
        nestedItems.push(items[lookAheadIndex]);
        lookAheadIndex += 1;
      }
      if (nestedItems.length > 0) {
        const nextIndent = Math.min(...nestedItems.map((nestedItem) => nestedItem.indent));
        const nestedListItems = buildNestedStructure(nestedItems, nextIndent, lexer);
        tokens.push({
          type: "list",
          ordered: true,
          start: nestedItems[0].number,
          items: nestedListItems,
          raw: nestedItems.map((nestedItem) => nestedItem.raw).join("\n")
        });
      }
      result.push({
        type: "list_item",
        raw: item.raw,
        tokens
      });
      currentIndex = lookAheadIndex;
    } else {
      currentIndex += 1;
    }
  }
  return result;
}
function parseListItems(items, helpers) {
  return items.map((item) => {
    if (item.type !== "list_item") {
      return helpers.parseChildren([item])[0];
    }
    const content = [];
    if (item.tokens && item.tokens.length > 0) {
      item.tokens.forEach((itemToken) => {
        if (itemToken.type === "paragraph" || itemToken.type === "list" || itemToken.type === "blockquote" || itemToken.type === "code") {
          content.push(...helpers.parseChildren([itemToken]));
        } else if (itemToken.type === "text" && itemToken.tokens) {
          const inlineContent = helpers.parseChildren([itemToken]);
          content.push({
            type: "paragraph",
            content: inlineContent
          });
        } else {
          const parsed = helpers.parseChildren([itemToken]);
          if (parsed.length > 0) {
            content.push(...parsed);
          }
        }
      });
    }
    return {
      type: "listItem",
      content
    };
  });
}
var ListItemName2 = "listItem";
var TextStyleName2 = "textStyle";
var orderedListInputRegex = /^(\d+)\.\s$/;
var OrderedList = Node3.create({
  name: "orderedList",
  addOptions() {
    return {
      itemTypeName: "listItem",
      HTMLAttributes: {},
      keepMarks: false,
      keepAttributes: false
    };
  },
  group: "block list",
  content() {
    return `${this.options.itemTypeName}+`;
  },
  addAttributes() {
    return {
      start: {
        default: 1,
        parseHTML: (element) => {
          return element.hasAttribute("start") ? parseInt(element.getAttribute("start") || "", 10) : 1;
        }
      },
      type: {
        default: null,
        parseHTML: (element) => element.getAttribute("type")
      }
    };
  },
  parseHTML() {
    return [
      {
        tag: "ol"
      }
    ];
  },
  renderHTML({ HTMLAttributes }) {
    const { start, ...attributesWithoutStart } = HTMLAttributes;
    return start === 1 ? ["ol", mergeAttributes(this.options.HTMLAttributes, attributesWithoutStart), 0] : ["ol", mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), 0];
  },
  markdownTokenName: "list",
  parseMarkdown: (token, helpers) => {
    if (token.type !== "list" || !token.ordered) {
      return [];
    }
    const startValue = token.start || 1;
    const content = token.items ? parseListItems(token.items, helpers) : [];
    if (startValue !== 1) {
      return {
        type: "orderedList",
        attrs: { start: startValue },
        content
      };
    }
    return {
      type: "orderedList",
      content
    };
  },
  renderMarkdown: (node, h2) => {
    if (!node.content) {
      return "";
    }
    return h2.renderChildren(node.content, "\n");
  },
  markdownTokenizer: {
    name: "orderedList",
    level: "block",
    start: (src) => {
      const match = src.match(/^(\s*)(\d+)\.\s+/);
      const index = match == null ? void 0 : match.index;
      return index !== void 0 ? index : -1;
    },
    tokenize: (src, _tokens, lexer) => {
      var _a;
      const lines = src.split("\n");
      const [listItems, consumed] = collectOrderedListItems(lines);
      if (listItems.length === 0) {
        return void 0;
      }
      const items = buildNestedStructure(listItems, 0, lexer);
      if (items.length === 0) {
        return void 0;
      }
      const startValue = ((_a = listItems[0]) == null ? void 0 : _a.number) || 1;
      return {
        type: "list",
        ordered: true,
        start: startValue,
        items,
        raw: lines.slice(0, consumed).join("\n")
      };
    }
  },
  markdownOptions: {
    indentsContent: true
  },
  addCommands() {
    return {
      toggleOrderedList: () => ({ commands, chain }) => {
        if (this.options.keepAttributes) {
          return chain().toggleList(this.name, this.options.itemTypeName, this.options.keepMarks).updateAttributes(ListItemName2, this.editor.getAttributes(TextStyleName2)).run();
        }
        return commands.toggleList(this.name, this.options.itemTypeName, this.options.keepMarks);
      }
    };
  },
  addKeyboardShortcuts() {
    return {
      "Mod-Shift-7": () => this.editor.commands.toggleOrderedList()
    };
  },
  addInputRules() {
    let inputRule = wrappingInputRule({
      find: orderedListInputRegex,
      type: this.type,
      getAttributes: (match) => ({ start: +match[1] }),
      joinPredicate: (match, node) => node.childCount + node.attrs.start === +match[1]
    });
    if (this.options.keepMarks || this.options.keepAttributes) {
      inputRule = wrappingInputRule({
        find: orderedListInputRegex,
        type: this.type,
        keepMarks: this.options.keepMarks,
        keepAttributes: this.options.keepAttributes,
        getAttributes: (match) => ({ start: +match[1], ...this.editor.getAttributes(TextStyleName2) }),
        joinPredicate: (match, node) => node.childCount + node.attrs.start === +match[1],
        editor: this.editor
      });
    }
    return [inputRule];
  }
});
var inputRegex3 = /^\s*(\[([( |x])?\])\s$/;
var TaskItem = Node3.create({
  name: "taskItem",
  addOptions() {
    return {
      nested: false,
      HTMLAttributes: {},
      taskListTypeName: "taskList",
      a11y: void 0
    };
  },
  content() {
    return this.options.nested ? "paragraph block*" : "paragraph+";
  },
  defining: true,
  addAttributes() {
    return {
      checked: {
        default: false,
        keepOnSplit: false,
        parseHTML: (element) => {
          const dataChecked = element.getAttribute("data-checked");
          return dataChecked === "" || dataChecked === "true";
        },
        renderHTML: (attributes) => ({
          "data-checked": attributes.checked
        })
      }
    };
  },
  parseHTML() {
    return [
      {
        tag: `li[data-type="${this.name}"]`,
        priority: 51
      }
    ];
  },
  renderHTML({ node, HTMLAttributes }) {
    return [
      "li",
      mergeAttributes(this.options.HTMLAttributes, HTMLAttributes, {
        "data-type": this.name
      }),
      [
        "label",
        [
          "input",
          {
            type: "checkbox",
            checked: node.attrs.checked ? "checked" : null
          }
        ],
        ["span"]
      ],
      ["div", 0]
    ];
  },
  parseMarkdown: (token, h2) => {
    const content = [];
    if (token.tokens && token.tokens.length > 0) {
      content.push(h2.createNode("paragraph", {}, h2.parseInline(token.tokens)));
    } else if (token.text) {
      content.push(h2.createNode("paragraph", {}, [h2.createNode("text", { text: token.text })]));
    } else {
      content.push(h2.createNode("paragraph", {}, []));
    }
    if (token.nestedTokens && token.nestedTokens.length > 0) {
      const nestedContent = h2.parseChildren(token.nestedTokens);
      content.push(...nestedContent);
    }
    return h2.createNode("taskItem", { checked: token.checked || false }, content);
  },
  renderMarkdown: (node, h2) => {
    var _a;
    const checkedChar = ((_a = node.attrs) == null ? void 0 : _a.checked) ? "x" : " ";
    const prefix = `- [${checkedChar}] `;
    return renderNestedMarkdownContent(node, h2, prefix);
  },
  addKeyboardShortcuts() {
    const shortcuts = {
      Enter: () => this.editor.commands.splitListItem(this.name),
      "Shift-Tab": () => this.editor.commands.liftListItem(this.name)
    };
    if (!this.options.nested) {
      return shortcuts;
    }
    return {
      ...shortcuts,
      Tab: () => this.editor.commands.sinkListItem(this.name)
    };
  },
  addNodeView() {
    return ({ node, HTMLAttributes, getPos, editor }) => {
      const listItem = document.createElement("li");
      const checkboxWrapper = document.createElement("label");
      const checkboxStyler = document.createElement("span");
      const checkbox = document.createElement("input");
      const content = document.createElement("div");
      const updateA11Y = (currentNode) => {
        var _a, _b;
        checkbox.ariaLabel = ((_b = (_a = this.options.a11y) == null ? void 0 : _a.checkboxLabel) == null ? void 0 : _b.call(_a, currentNode, checkbox.checked)) || `Task item checkbox for ${currentNode.textContent || "empty task item"}`;
      };
      updateA11Y(node);
      checkboxWrapper.contentEditable = "false";
      checkbox.type = "checkbox";
      checkbox.addEventListener("mousedown", (event) => event.preventDefault());
      checkbox.addEventListener("change", (event) => {
        if (!editor.isEditable && !this.options.onReadOnlyChecked) {
          checkbox.checked = !checkbox.checked;
          return;
        }
        const { checked } = event.target;
        if (editor.isEditable && typeof getPos === "function") {
          editor.chain().focus(void 0, { scrollIntoView: false }).command(({ tr: tr2 }) => {
            const position = getPos();
            if (typeof position !== "number") {
              return false;
            }
            const currentNode = tr2.doc.nodeAt(position);
            tr2.setNodeMarkup(position, void 0, {
              ...currentNode == null ? void 0 : currentNode.attrs,
              checked
            });
            return true;
          }).run();
        }
        if (!editor.isEditable && this.options.onReadOnlyChecked) {
          if (!this.options.onReadOnlyChecked(node, checked)) {
            checkbox.checked = !checkbox.checked;
          }
        }
      });
      Object.entries(this.options.HTMLAttributes).forEach(([key, value]) => {
        listItem.setAttribute(key, value);
      });
      listItem.dataset.checked = node.attrs.checked;
      checkbox.checked = node.attrs.checked;
      checkboxWrapper.append(checkbox, checkboxStyler);
      listItem.append(checkboxWrapper, content);
      Object.entries(HTMLAttributes).forEach(([key, value]) => {
        listItem.setAttribute(key, value);
      });
      let prevRenderedAttributeKeys = new Set(Object.keys(HTMLAttributes));
      return {
        dom: listItem,
        contentDOM: content,
        update: (updatedNode) => {
          if (updatedNode.type !== this.type) {
            return false;
          }
          listItem.dataset.checked = updatedNode.attrs.checked;
          checkbox.checked = updatedNode.attrs.checked;
          updateA11Y(updatedNode);
          const extensionAttributes = editor.extensionManager.attributes;
          const newHTMLAttributes = getRenderedAttributes(updatedNode, extensionAttributes);
          const newKeys = new Set(Object.keys(newHTMLAttributes));
          const staticAttrs = this.options.HTMLAttributes;
          prevRenderedAttributeKeys.forEach((key) => {
            if (!newKeys.has(key)) {
              if (key in staticAttrs) {
                listItem.setAttribute(key, staticAttrs[key]);
              } else {
                listItem.removeAttribute(key);
              }
            }
          });
          Object.entries(newHTMLAttributes).forEach(([key, value]) => {
            if (value === null || value === void 0) {
              if (key in staticAttrs) {
                listItem.setAttribute(key, staticAttrs[key]);
              } else {
                listItem.removeAttribute(key);
              }
            } else {
              listItem.setAttribute(key, value);
            }
          });
          prevRenderedAttributeKeys = newKeys;
          return true;
        }
      };
    };
  },
  addInputRules() {
    return [
      wrappingInputRule({
        find: inputRegex3,
        type: this.type,
        getAttributes: (match) => ({
          checked: match[match.length - 1] === "x"
        })
      })
    ];
  }
});
var TaskList = Node3.create({
  name: "taskList",
  addOptions() {
    return {
      itemTypeName: "taskItem",
      HTMLAttributes: {}
    };
  },
  group: "block list",
  content() {
    return `${this.options.itemTypeName}+`;
  },
  parseHTML() {
    return [
      {
        tag: `ul[data-type="${this.name}"]`,
        priority: 51
      }
    ];
  },
  renderHTML({ HTMLAttributes }) {
    return ["ul", mergeAttributes(this.options.HTMLAttributes, HTMLAttributes, { "data-type": this.name }), 0];
  },
  parseMarkdown: (token, h2) => {
    return h2.createNode("taskList", {}, h2.parseChildren(token.items || []));
  },
  renderMarkdown: (node, h2) => {
    if (!node.content) {
      return "";
    }
    return h2.renderChildren(node.content, "\n");
  },
  markdownTokenizer: {
    name: "taskList",
    level: "block",
    start(src) {
      var _a;
      const index = (_a = src.match(/^\s*[-+*]\s+\[([ xX])\]\s+/)) == null ? void 0 : _a.index;
      return index !== void 0 ? index : -1;
    },
    tokenize(src, tokens, lexer) {
      const parseTaskListContent = (content) => {
        const nestedResult = parseIndentedBlocks(
          content,
          {
            itemPattern: /^(\s*)([-+*])\s+\[([ xX])\]\s+(.*)$/,
            extractItemData: (match) => ({
              indentLevel: match[1].length,
              mainContent: match[4],
              checked: match[3].toLowerCase() === "x"
            }),
            createToken: (data, nestedTokens) => ({
              type: "taskItem",
              raw: "",
              mainContent: data.mainContent,
              indentLevel: data.indentLevel,
              checked: data.checked,
              text: data.mainContent,
              tokens: lexer.inlineTokens(data.mainContent),
              nestedTokens
            }),
            // Allow recursive nesting
            customNestedParser: parseTaskListContent
          },
          lexer
        );
        if (nestedResult) {
          return [
            {
              type: "taskList",
              raw: nestedResult.raw,
              items: nestedResult.items
            }
          ];
        }
        return lexer.blockTokens(content);
      };
      const result = parseIndentedBlocks(
        src,
        {
          itemPattern: /^(\s*)([-+*])\s+\[([ xX])\]\s+(.*)$/,
          extractItemData: (match) => ({
            indentLevel: match[1].length,
            mainContent: match[4],
            checked: match[3].toLowerCase() === "x"
          }),
          createToken: (data, nestedTokens) => ({
            type: "taskItem",
            raw: "",
            mainContent: data.mainContent,
            indentLevel: data.indentLevel,
            checked: data.checked,
            text: data.mainContent,
            tokens: lexer.inlineTokens(data.mainContent),
            nestedTokens
          }),
          // Use the recursive parser for nested content
          customNestedParser: parseTaskListContent
        },
        lexer
      );
      if (!result) {
        return void 0;
      }
      return {
        type: "taskList",
        raw: result.raw,
        items: result.items
      };
    }
  },
  markdownOptions: {
    indentsContent: true
  },
  addCommands() {
    return {
      toggleTaskList: () => ({ commands }) => {
        return commands.toggleList(this.name, this.options.itemTypeName);
      }
    };
  },
  addKeyboardShortcuts() {
    return {
      "Mod-Shift-9": () => this.editor.commands.toggleTaskList()
    };
  }
});
var ListKit = Extension.create({
  name: "listKit",
  addExtensions() {
    const extensions = [];
    if (this.options.bulletList !== false) {
      extensions.push(BulletList.configure(this.options.bulletList));
    }
    if (this.options.listItem !== false) {
      extensions.push(ListItem.configure(this.options.listItem));
    }
    if (this.options.listKeymap !== false) {
      extensions.push(ListKeymap.configure(this.options.listKeymap));
    }
    if (this.options.orderedList !== false) {
      extensions.push(OrderedList.configure(this.options.orderedList));
    }
    if (this.options.taskItem !== false) {
      extensions.push(TaskItem.configure(this.options.taskItem));
    }
    if (this.options.taskList !== false) {
      extensions.push(TaskList.configure(this.options.taskList));
    }
    return extensions;
  }
});

// ../../node_modules/.pnpm/@tiptap+extension-paragraph@3.15.3_@tiptap+core@3.15.3_@tiptap+pm@3.15.3_/node_modules/@tiptap/extension-paragraph/dist/index.js
var Paragraph = Node3.create({
  name: "paragraph",
  priority: 1e3,
  addOptions() {
    return {
      HTMLAttributes: {}
    };
  },
  group: "block",
  content: "inline*",
  parseHTML() {
    return [{ tag: "p" }];
  },
  renderHTML({ HTMLAttributes }) {
    return ["p", mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), 0];
  },
  parseMarkdown: (token, helpers) => {
    const tokens = token.tokens || [];
    if (tokens.length === 1 && tokens[0].type === "image") {
      return helpers.parseChildren([tokens[0]]);
    }
    return helpers.createNode(
      "paragraph",
      void 0,
      // no attributes for paragraph
      helpers.parseInline(tokens)
    );
  },
  renderMarkdown: (node, h2) => {
    if (!node || !Array.isArray(node.content)) {
      return "";
    }
    return h2.renderChildren(node.content);
  },
  addCommands() {
    return {
      setParagraph: () => ({ commands }) => {
        return commands.setNode(this.name);
      }
    };
  },
  addKeyboardShortcuts() {
    return {
      "Mod-Alt-0": () => this.editor.commands.setParagraph()
    };
  }
});

// ../../node_modules/.pnpm/@tiptap+extension-strike@3.15.3_@tiptap+core@3.15.3_@tiptap+pm@3.15.3_/node_modules/@tiptap/extension-strike/dist/index.js
var inputRegex4 = /(?:^|\s)(~~(?!\s+~~)((?:[^~]+))~~(?!\s+~~))$/;
var pasteRegex2 = /(?:^|\s)(~~(?!\s+~~)((?:[^~]+))~~(?!\s+~~))/g;
var Strike = Mark2.create({
  name: "strike",
  addOptions() {
    return {
      HTMLAttributes: {}
    };
  },
  parseHTML() {
    return [
      {
        tag: "s"
      },
      {
        tag: "del"
      },
      {
        tag: "strike"
      },
      {
        style: "text-decoration",
        consuming: false,
        getAttrs: (style2) => style2.includes("line-through") ? {} : false
      }
    ];
  },
  renderHTML({ HTMLAttributes }) {
    return ["s", mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), 0];
  },
  markdownTokenName: "del",
  parseMarkdown: (token, helpers) => {
    return helpers.applyMark("strike", helpers.parseInline(token.tokens || []));
  },
  renderMarkdown: (node, h2) => {
    return `~~${h2.renderChildren(node)}~~`;
  },
  addCommands() {
    return {
      setStrike: () => ({ commands }) => {
        return commands.setMark(this.name);
      },
      toggleStrike: () => ({ commands }) => {
        return commands.toggleMark(this.name);
      },
      unsetStrike: () => ({ commands }) => {
        return commands.unsetMark(this.name);
      }
    };
  },
  addKeyboardShortcuts() {
    return {
      "Mod-Shift-s": () => this.editor.commands.toggleStrike()
    };
  },
  addInputRules() {
    return [
      markInputRule({
        find: inputRegex4,
        type: this.type
      })
    ];
  },
  addPasteRules() {
    return [
      markPasteRule({
        find: pasteRegex2,
        type: this.type
      })
    ];
  }
});

// ../../node_modules/.pnpm/@tiptap+extension-text@3.15.3_@tiptap+core@3.15.3_@tiptap+pm@3.15.3_/node_modules/@tiptap/extension-text/dist/index.js
var Text2 = Node3.create({
  name: "text",
  group: "inline",
  parseMarkdown: (token) => {
    return {
      type: "text",
      text: token.text || ""
    };
  },
  renderMarkdown: (node) => node.text || ""
});

// ../../node_modules/.pnpm/@tiptap+extension-underline@3.15.3_@tiptap+core@3.15.3_@tiptap+pm@3.15.3_/node_modules/@tiptap/extension-underline/dist/index.js
var Underline = Mark2.create({
  name: "underline",
  addOptions() {
    return {
      HTMLAttributes: {}
    };
  },
  parseHTML() {
    return [
      {
        tag: "u"
      },
      {
        style: "text-decoration",
        consuming: false,
        getAttrs: (style2) => style2.includes("underline") ? {} : false
      }
    ];
  },
  renderHTML({ HTMLAttributes }) {
    return ["u", mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), 0];
  },
  parseMarkdown(token, helpers) {
    return helpers.applyMark(this.name || "underline", helpers.parseInline(token.tokens || []));
  },
  renderMarkdown(node, helpers) {
    return `++${helpers.renderChildren(node)}++`;
  },
  markdownTokenizer: {
    name: "underline",
    level: "inline",
    start(src) {
      return src.indexOf("++");
    },
    tokenize(src, _tokens, lexer) {
      const rule = /^(\+\+)([\s\S]+?)(\+\+)/;
      const match = rule.exec(src);
      if (!match) {
        return void 0;
      }
      const innerContent = match[2].trim();
      return {
        type: "underline",
        raw: match[0],
        text: innerContent,
        tokens: lexer.inlineTokens(innerContent)
      };
    }
  },
  addCommands() {
    return {
      setUnderline: () => ({ commands }) => {
        return commands.setMark(this.name);
      },
      toggleUnderline: () => ({ commands }) => {
        return commands.toggleMark(this.name);
      },
      unsetUnderline: () => ({ commands }) => {
        return commands.unsetMark(this.name);
      }
    };
  },
  addKeyboardShortcuts() {
    return {
      "Mod-u": () => this.editor.commands.toggleUnderline(),
      "Mod-U": () => this.editor.commands.toggleUnderline()
    };
  }
});

// ../../node_modules/.pnpm/prosemirror-dropcursor@1.8.2/node_modules/prosemirror-dropcursor/dist/index.js
function dropCursor(options = {}) {
  return new Plugin({
    view(editorView) {
      return new DropCursorView(editorView, options);
    }
  });
}
var DropCursorView = class {
  constructor(editorView, options) {
    var _a;
    this.editorView = editorView;
    this.cursorPos = null;
    this.element = null;
    this.timeout = -1;
    this.width = (_a = options.width) !== null && _a !== void 0 ? _a : 1;
    this.color = options.color === false ? void 0 : options.color || "black";
    this.class = options.class;
    this.handlers = ["dragover", "dragend", "drop", "dragleave"].map((name) => {
      let handler = (e) => {
        this[name](e);
      };
      editorView.dom.addEventListener(name, handler);
      return { name, handler };
    });
  }
  destroy() {
    this.handlers.forEach(({ name, handler }) => this.editorView.dom.removeEventListener(name, handler));
  }
  update(editorView, prevState) {
    if (this.cursorPos != null && prevState.doc != editorView.state.doc) {
      if (this.cursorPos > editorView.state.doc.content.size)
        this.setCursor(null);
      else
        this.updateOverlay();
    }
  }
  setCursor(pos) {
    if (pos == this.cursorPos)
      return;
    this.cursorPos = pos;
    if (pos == null) {
      this.element.parentNode.removeChild(this.element);
      this.element = null;
    } else {
      this.updateOverlay();
    }
  }
  updateOverlay() {
    let $pos = this.editorView.state.doc.resolve(this.cursorPos);
    let isBlock = !$pos.parent.inlineContent, rect;
    let editorDOM = this.editorView.dom, editorRect = editorDOM.getBoundingClientRect();
    let scaleX = editorRect.width / editorDOM.offsetWidth, scaleY = editorRect.height / editorDOM.offsetHeight;
    if (isBlock) {
      let before = $pos.nodeBefore, after = $pos.nodeAfter;
      if (before || after) {
        let node = this.editorView.nodeDOM(this.cursorPos - (before ? before.nodeSize : 0));
        if (node) {
          let nodeRect = node.getBoundingClientRect();
          let top = before ? nodeRect.bottom : nodeRect.top;
          if (before && after)
            top = (top + this.editorView.nodeDOM(this.cursorPos).getBoundingClientRect().top) / 2;
          let halfWidth = this.width / 2 * scaleY;
          rect = { left: nodeRect.left, right: nodeRect.right, top: top - halfWidth, bottom: top + halfWidth };
        }
      }
    }
    if (!rect) {
      let coords = this.editorView.coordsAtPos(this.cursorPos);
      let halfWidth = this.width / 2 * scaleX;
      rect = { left: coords.left - halfWidth, right: coords.left + halfWidth, top: coords.top, bottom: coords.bottom };
    }
    let parent = this.editorView.dom.offsetParent;
    if (!this.element) {
      this.element = parent.appendChild(document.createElement("div"));
      if (this.class)
        this.element.className = this.class;
      this.element.style.cssText = "position: absolute; z-index: 50; pointer-events: none;";
      if (this.color) {
        this.element.style.backgroundColor = this.color;
      }
    }
    this.element.classList.toggle("prosemirror-dropcursor-block", isBlock);
    this.element.classList.toggle("prosemirror-dropcursor-inline", !isBlock);
    let parentLeft, parentTop;
    if (!parent || parent == document.body && getComputedStyle(parent).position == "static") {
      parentLeft = -pageXOffset;
      parentTop = -pageYOffset;
    } else {
      let rect2 = parent.getBoundingClientRect();
      let parentScaleX = rect2.width / parent.offsetWidth, parentScaleY = rect2.height / parent.offsetHeight;
      parentLeft = rect2.left - parent.scrollLeft * parentScaleX;
      parentTop = rect2.top - parent.scrollTop * parentScaleY;
    }
    this.element.style.left = (rect.left - parentLeft) / scaleX + "px";
    this.element.style.top = (rect.top - parentTop) / scaleY + "px";
    this.element.style.width = (rect.right - rect.left) / scaleX + "px";
    this.element.style.height = (rect.bottom - rect.top) / scaleY + "px";
  }
  scheduleRemoval(timeout) {
    clearTimeout(this.timeout);
    this.timeout = setTimeout(() => this.setCursor(null), timeout);
  }
  dragover(event) {
    if (!this.editorView.editable)
      return;
    let pos = this.editorView.posAtCoords({ left: event.clientX, top: event.clientY });
    let node = pos && pos.inside >= 0 && this.editorView.state.doc.nodeAt(pos.inside);
    let disableDropCursor = node && node.type.spec.disableDropCursor;
    let disabled = typeof disableDropCursor == "function" ? disableDropCursor(this.editorView, pos, event) : disableDropCursor;
    if (pos && !disabled) {
      let target2 = pos.pos;
      if (this.editorView.dragging && this.editorView.dragging.slice) {
        let point = dropPoint(this.editorView.state.doc, target2, this.editorView.dragging.slice);
        if (point != null)
          target2 = point;
      }
      this.setCursor(target2);
      this.scheduleRemoval(5e3);
    }
  }
  dragend() {
    this.scheduleRemoval(20);
  }
  drop() {
    this.scheduleRemoval(20);
  }
  dragleave(event) {
    if (!this.editorView.dom.contains(event.relatedTarget))
      this.setCursor(null);
  }
};

// ../../node_modules/.pnpm/prosemirror-gapcursor@1.4.0/node_modules/prosemirror-gapcursor/dist/index.js
var GapCursor = class _GapCursor extends Selection {
  /**
  Create a gap cursor.
  */
  constructor($pos) {
    super($pos, $pos);
  }
  map(doc3, mapping) {
    let $pos = doc3.resolve(mapping.map(this.head));
    return _GapCursor.valid($pos) ? new _GapCursor($pos) : Selection.near($pos);
  }
  content() {
    return Slice.empty;
  }
  eq(other) {
    return other instanceof _GapCursor && other.head == this.head;
  }
  toJSON() {
    return { type: "gapcursor", pos: this.head };
  }
  /**
  @internal
  */
  static fromJSON(doc3, json) {
    if (typeof json.pos != "number")
      throw new RangeError("Invalid input for GapCursor.fromJSON");
    return new _GapCursor(doc3.resolve(json.pos));
  }
  /**
  @internal
  */
  getBookmark() {
    return new GapBookmark(this.anchor);
  }
  /**
  @internal
  */
  static valid($pos) {
    let parent = $pos.parent;
    if (parent.isTextblock || !closedBefore($pos) || !closedAfter($pos))
      return false;
    let override = parent.type.spec.allowGapCursor;
    if (override != null)
      return override;
    let deflt3 = parent.contentMatchAt($pos.index()).defaultType;
    return deflt3 && deflt3.isTextblock;
  }
  /**
  @internal
  */
  static findGapCursorFrom($pos, dir, mustMove = false) {
    search: for (; ; ) {
      if (!mustMove && _GapCursor.valid($pos))
        return $pos;
      let pos = $pos.pos, next = null;
      for (let d2 = $pos.depth; ; d2--) {
        let parent = $pos.node(d2);
        if (dir > 0 ? $pos.indexAfter(d2) < parent.childCount : $pos.index(d2) > 0) {
          next = parent.child(dir > 0 ? $pos.indexAfter(d2) : $pos.index(d2) - 1);
          break;
        } else if (d2 == 0) {
          return null;
        }
        pos += dir;
        let $cur = $pos.doc.resolve(pos);
        if (_GapCursor.valid($cur))
          return $cur;
      }
      for (; ; ) {
        let inside = dir > 0 ? next.firstChild : next.lastChild;
        if (!inside) {
          if (next.isAtom && !next.isText && !NodeSelection.isSelectable(next)) {
            $pos = $pos.doc.resolve(pos + next.nodeSize * dir);
            mustMove = false;
            continue search;
          }
          break;
        }
        next = inside;
        pos += dir;
        let $cur = $pos.doc.resolve(pos);
        if (_GapCursor.valid($cur))
          return $cur;
      }
      return null;
    }
  }
};
GapCursor.prototype.visible = false;
GapCursor.findFrom = GapCursor.findGapCursorFrom;
Selection.jsonID("gapcursor", GapCursor);
var GapBookmark = class _GapBookmark {
  constructor(pos) {
    this.pos = pos;
  }
  map(mapping) {
    return new _GapBookmark(mapping.map(this.pos));
  }
  resolve(doc3) {
    let $pos = doc3.resolve(this.pos);
    return GapCursor.valid($pos) ? new GapCursor($pos) : Selection.near($pos);
  }
};
function needsGap(type) {
  return type.isAtom || type.spec.isolating || type.spec.createGapCursor;
}
function closedBefore($pos) {
  for (let d2 = $pos.depth; d2 >= 0; d2--) {
    let index = $pos.index(d2), parent = $pos.node(d2);
    if (index == 0) {
      if (parent.type.spec.isolating)
        return true;
      continue;
    }
    for (let before = parent.child(index - 1); ; before = before.lastChild) {
      if (before.childCount == 0 && !before.inlineContent || needsGap(before.type))
        return true;
      if (before.inlineContent)
        return false;
    }
  }
  return true;
}
function closedAfter($pos) {
  for (let d2 = $pos.depth; d2 >= 0; d2--) {
    let index = $pos.indexAfter(d2), parent = $pos.node(d2);
    if (index == parent.childCount) {
      if (parent.type.spec.isolating)
        return true;
      continue;
    }
    for (let after = parent.child(index); ; after = after.firstChild) {
      if (after.childCount == 0 && !after.inlineContent || needsGap(after.type))
        return true;
      if (after.inlineContent)
        return false;
    }
  }
  return true;
}
function gapCursor() {
  return new Plugin({
    props: {
      decorations: drawGapCursor,
      createSelectionBetween(_view, $anchor, $head) {
        return $anchor.pos == $head.pos && GapCursor.valid($head) ? new GapCursor($head) : null;
      },
      handleClick,
      handleKeyDown,
      handleDOMEvents: { beforeinput }
    }
  });
}
var handleKeyDown = keydownHandler({
  "ArrowLeft": arrow("horiz", -1),
  "ArrowRight": arrow("horiz", 1),
  "ArrowUp": arrow("vert", -1),
  "ArrowDown": arrow("vert", 1)
});
function arrow(axis, dir) {
  const dirStr = axis == "vert" ? dir > 0 ? "down" : "up" : dir > 0 ? "right" : "left";
  return function(state, dispatch, view) {
    let sel = state.selection;
    let $start = dir > 0 ? sel.$to : sel.$from, mustMove = sel.empty;
    if (sel instanceof TextSelection) {
      if (!view.endOfTextblock(dirStr) || $start.depth == 0)
        return false;
      mustMove = false;
      $start = state.doc.resolve(dir > 0 ? $start.after() : $start.before());
    }
    let $found = GapCursor.findGapCursorFrom($start, dir, mustMove);
    if (!$found)
      return false;
    if (dispatch)
      dispatch(state.tr.setSelection(new GapCursor($found)));
    return true;
  };
}
function handleClick(view, pos, event) {
  if (!view || !view.editable)
    return false;
  let $pos = view.state.doc.resolve(pos);
  if (!GapCursor.valid($pos))
    return false;
  let clickPos = view.posAtCoords({ left: event.clientX, top: event.clientY });
  if (clickPos && clickPos.inside > -1 && NodeSelection.isSelectable(view.state.doc.nodeAt(clickPos.inside)))
    return false;
  view.dispatch(view.state.tr.setSelection(new GapCursor($pos)));
  return true;
}
function beforeinput(view, event) {
  if (event.inputType != "insertCompositionText" || !(view.state.selection instanceof GapCursor))
    return false;
  let { $from } = view.state.selection;
  let insert2 = $from.parent.contentMatchAt($from.index()).findWrapping(view.state.schema.nodes.text);
  if (!insert2)
    return false;
  let frag = Fragment.empty;
  for (let i = insert2.length - 1; i >= 0; i--)
    frag = Fragment.from(insert2[i].createAndFill(null, frag));
  let tr2 = view.state.tr.replace($from.pos, $from.pos, new Slice(frag, 0, 0));
  tr2.setSelection(TextSelection.near(tr2.doc.resolve($from.pos + 1)));
  view.dispatch(tr2);
  return false;
}
function drawGapCursor(state) {
  if (!(state.selection instanceof GapCursor))
    return null;
  let node = document.createElement("div");
  node.className = "ProseMirror-gapcursor";
  return DecorationSet.create(state.doc, [Decoration.widget(state.selection.head, node, { key: "gapcursor" })]);
}

// ../../node_modules/.pnpm/rope-sequence@1.3.4/node_modules/rope-sequence/dist/index.js
var GOOD_LEAF_SIZE = 200;
var RopeSequence = function RopeSequence2() {
};
RopeSequence.prototype.append = function append(other) {
  if (!other.length) {
    return this;
  }
  other = RopeSequence.from(other);
  return !this.length && other || other.length < GOOD_LEAF_SIZE && this.leafAppend(other) || this.length < GOOD_LEAF_SIZE && other.leafPrepend(this) || this.appendInner(other);
};
RopeSequence.prototype.prepend = function prepend(other) {
  if (!other.length) {
    return this;
  }
  return RopeSequence.from(other).append(this);
};
RopeSequence.prototype.appendInner = function appendInner(other) {
  return new Append(this, other);
};
RopeSequence.prototype.slice = function slice(from2, to) {
  if (from2 === void 0) from2 = 0;
  if (to === void 0) to = this.length;
  if (from2 >= to) {
    return RopeSequence.empty;
  }
  return this.sliceInner(Math.max(0, from2), Math.min(this.length, to));
};
RopeSequence.prototype.get = function get(i) {
  if (i < 0 || i >= this.length) {
    return void 0;
  }
  return this.getInner(i);
};
RopeSequence.prototype.forEach = function forEach2(f, from2, to) {
  if (from2 === void 0) from2 = 0;
  if (to === void 0) to = this.length;
  if (from2 <= to) {
    this.forEachInner(f, from2, to, 0);
  } else {
    this.forEachInvertedInner(f, from2, to, 0);
  }
};
RopeSequence.prototype.map = function map(f, from2, to) {
  if (from2 === void 0) from2 = 0;
  if (to === void 0) to = this.length;
  var result = [];
  this.forEach(function(elt, i) {
    return result.push(f(elt, i));
  }, from2, to);
  return result;
};
RopeSequence.from = function from(values) {
  if (values instanceof RopeSequence) {
    return values;
  }
  return values && values.length ? new Leaf(values) : RopeSequence.empty;
};
var Leaf = /* @__PURE__ */ (function(RopeSequence3) {
  function Leaf2(values) {
    RopeSequence3.call(this);
    this.values = values;
  }
  if (RopeSequence3) Leaf2.__proto__ = RopeSequence3;
  Leaf2.prototype = Object.create(RopeSequence3 && RopeSequence3.prototype);
  Leaf2.prototype.constructor = Leaf2;
  var prototypeAccessors = { length: { configurable: true }, depth: { configurable: true } };
  Leaf2.prototype.flatten = function flatten() {
    return this.values;
  };
  Leaf2.prototype.sliceInner = function sliceInner(from2, to) {
    if (from2 == 0 && to == this.length) {
      return this;
    }
    return new Leaf2(this.values.slice(from2, to));
  };
  Leaf2.prototype.getInner = function getInner(i) {
    return this.values[i];
  };
  Leaf2.prototype.forEachInner = function forEachInner(f, from2, to, start) {
    for (var i = from2; i < to; i++) {
      if (f(this.values[i], start + i) === false) {
        return false;
      }
    }
  };
  Leaf2.prototype.forEachInvertedInner = function forEachInvertedInner(f, from2, to, start) {
    for (var i = from2 - 1; i >= to; i--) {
      if (f(this.values[i], start + i) === false) {
        return false;
      }
    }
  };
  Leaf2.prototype.leafAppend = function leafAppend(other) {
    if (this.length + other.length <= GOOD_LEAF_SIZE) {
      return new Leaf2(this.values.concat(other.flatten()));
    }
  };
  Leaf2.prototype.leafPrepend = function leafPrepend(other) {
    if (this.length + other.length <= GOOD_LEAF_SIZE) {
      return new Leaf2(other.flatten().concat(this.values));
    }
  };
  prototypeAccessors.length.get = function() {
    return this.values.length;
  };
  prototypeAccessors.depth.get = function() {
    return 0;
  };
  Object.defineProperties(Leaf2.prototype, prototypeAccessors);
  return Leaf2;
})(RopeSequence);
RopeSequence.empty = new Leaf([]);
var Append = /* @__PURE__ */ (function(RopeSequence3) {
  function Append2(left, right) {
    RopeSequence3.call(this);
    this.left = left;
    this.right = right;
    this.length = left.length + right.length;
    this.depth = Math.max(left.depth, right.depth) + 1;
  }
  if (RopeSequence3) Append2.__proto__ = RopeSequence3;
  Append2.prototype = Object.create(RopeSequence3 && RopeSequence3.prototype);
  Append2.prototype.constructor = Append2;
  Append2.prototype.flatten = function flatten() {
    return this.left.flatten().concat(this.right.flatten());
  };
  Append2.prototype.getInner = function getInner(i) {
    return i < this.left.length ? this.left.get(i) : this.right.get(i - this.left.length);
  };
  Append2.prototype.forEachInner = function forEachInner(f, from2, to, start) {
    var leftLen = this.left.length;
    if (from2 < leftLen && this.left.forEachInner(f, from2, Math.min(to, leftLen), start) === false) {
      return false;
    }
    if (to > leftLen && this.right.forEachInner(f, Math.max(from2 - leftLen, 0), Math.min(this.length, to) - leftLen, start + leftLen) === false) {
      return false;
    }
  };
  Append2.prototype.forEachInvertedInner = function forEachInvertedInner(f, from2, to, start) {
    var leftLen = this.left.length;
    if (from2 > leftLen && this.right.forEachInvertedInner(f, from2 - leftLen, Math.max(to, leftLen) - leftLen, start + leftLen) === false) {
      return false;
    }
    if (to < leftLen && this.left.forEachInvertedInner(f, Math.min(from2, leftLen), to, start) === false) {
      return false;
    }
  };
  Append2.prototype.sliceInner = function sliceInner(from2, to) {
    if (from2 == 0 && to == this.length) {
      return this;
    }
    var leftLen = this.left.length;
    if (to <= leftLen) {
      return this.left.slice(from2, to);
    }
    if (from2 >= leftLen) {
      return this.right.slice(from2 - leftLen, to - leftLen);
    }
    return this.left.slice(from2, leftLen).append(this.right.slice(0, to - leftLen));
  };
  Append2.prototype.leafAppend = function leafAppend(other) {
    var inner2 = this.right.leafAppend(other);
    if (inner2) {
      return new Append2(this.left, inner2);
    }
  };
  Append2.prototype.leafPrepend = function leafPrepend(other) {
    var inner2 = this.left.leafPrepend(other);
    if (inner2) {
      return new Append2(inner2, this.right);
    }
  };
  Append2.prototype.appendInner = function appendInner2(other) {
    if (this.left.depth >= Math.max(this.right.depth, other.depth) + 1) {
      return new Append2(this.left, new Append2(this.right, other));
    }
    return new Append2(this, other);
  };
  return Append2;
})(RopeSequence);
var dist_default2 = RopeSequence;

// ../../node_modules/.pnpm/prosemirror-history@1.5.0/node_modules/prosemirror-history/dist/index.js
var max_empty_items = 500;
var Branch = class _Branch {
  constructor(items, eventCount) {
    this.items = items;
    this.eventCount = eventCount;
  }
  // Pop the latest event off the branch's history and apply it
  // to a document transform.
  popEvent(state, preserveItems) {
    if (this.eventCount == 0)
      return null;
    let end = this.items.length;
    for (; ; end--) {
      let next = this.items.get(end - 1);
      if (next.selection) {
        --end;
        break;
      }
    }
    let remap, mapFrom;
    if (preserveItems) {
      remap = this.remapping(end, this.items.length);
      mapFrom = remap.maps.length;
    }
    let transform = state.tr;
    let selection, remaining;
    let addAfter = [], addBefore = [];
    this.items.forEach((item, i) => {
      if (!item.step) {
        if (!remap) {
          remap = this.remapping(end, i + 1);
          mapFrom = remap.maps.length;
        }
        mapFrom--;
        addBefore.push(item);
        return;
      }
      if (remap) {
        addBefore.push(new Item(item.map));
        let step = item.step.map(remap.slice(mapFrom)), map2;
        if (step && transform.maybeStep(step).doc) {
          map2 = transform.mapping.maps[transform.mapping.maps.length - 1];
          addAfter.push(new Item(map2, void 0, void 0, addAfter.length + addBefore.length));
        }
        mapFrom--;
        if (map2)
          remap.appendMap(map2, mapFrom);
      } else {
        transform.maybeStep(item.step);
      }
      if (item.selection) {
        selection = remap ? item.selection.map(remap.slice(mapFrom)) : item.selection;
        remaining = new _Branch(this.items.slice(0, end).append(addBefore.reverse().concat(addAfter)), this.eventCount - 1);
        return false;
      }
    }, this.items.length, 0);
    return { remaining, transform, selection };
  }
  // Create a new branch with the given transform added.
  addTransform(transform, selection, histOptions, preserveItems) {
    let newItems = [], eventCount = this.eventCount;
    let oldItems = this.items, lastItem = !preserveItems && oldItems.length ? oldItems.get(oldItems.length - 1) : null;
    for (let i = 0; i < transform.steps.length; i++) {
      let step = transform.steps[i].invert(transform.docs[i]);
      let item = new Item(transform.mapping.maps[i], step, selection), merged;
      if (merged = lastItem && lastItem.merge(item)) {
        item = merged;
        if (i)
          newItems.pop();
        else
          oldItems = oldItems.slice(0, oldItems.length - 1);
      }
      newItems.push(item);
      if (selection) {
        eventCount++;
        selection = void 0;
      }
      if (!preserveItems)
        lastItem = item;
    }
    let overflow = eventCount - histOptions.depth;
    if (overflow > DEPTH_OVERFLOW) {
      oldItems = cutOffEvents(oldItems, overflow);
      eventCount -= overflow;
    }
    return new _Branch(oldItems.append(newItems), eventCount);
  }
  remapping(from2, to) {
    let maps = new Mapping();
    this.items.forEach((item, i) => {
      let mirrorPos = item.mirrorOffset != null && i - item.mirrorOffset >= from2 ? maps.maps.length - item.mirrorOffset : void 0;
      maps.appendMap(item.map, mirrorPos);
    }, from2, to);
    return maps;
  }
  addMaps(array) {
    if (this.eventCount == 0)
      return this;
    return new _Branch(this.items.append(array.map((map2) => new Item(map2))), this.eventCount);
  }
  // When the collab module receives remote changes, the history has
  // to know about those, so that it can adjust the steps that were
  // rebased on top of the remote changes, and include the position
  // maps for the remote changes in its array of items.
  rebased(rebasedTransform, rebasedCount) {
    if (!this.eventCount)
      return this;
    let rebasedItems = [], start = Math.max(0, this.items.length - rebasedCount);
    let mapping = rebasedTransform.mapping;
    let newUntil = rebasedTransform.steps.length;
    let eventCount = this.eventCount;
    this.items.forEach((item) => {
      if (item.selection)
        eventCount--;
    }, start);
    let iRebased = rebasedCount;
    this.items.forEach((item) => {
      let pos = mapping.getMirror(--iRebased);
      if (pos == null)
        return;
      newUntil = Math.min(newUntil, pos);
      let map2 = mapping.maps[pos];
      if (item.step) {
        let step = rebasedTransform.steps[pos].invert(rebasedTransform.docs[pos]);
        let selection = item.selection && item.selection.map(mapping.slice(iRebased + 1, pos));
        if (selection)
          eventCount++;
        rebasedItems.push(new Item(map2, step, selection));
      } else {
        rebasedItems.push(new Item(map2));
      }
    }, start);
    let newMaps = [];
    for (let i = rebasedCount; i < newUntil; i++)
      newMaps.push(new Item(mapping.maps[i]));
    let items = this.items.slice(0, start).append(newMaps).append(rebasedItems);
    let branch = new _Branch(items, eventCount);
    if (branch.emptyItemCount() > max_empty_items)
      branch = branch.compress(this.items.length - rebasedItems.length);
    return branch;
  }
  emptyItemCount() {
    let count = 0;
    this.items.forEach((item) => {
      if (!item.step)
        count++;
    });
    return count;
  }
  // Compressing a branch means rewriting it to push the air (map-only
  // items) out. During collaboration, these naturally accumulate
  // because each remote change adds one. The `upto` argument is used
  // to ensure that only the items below a given level are compressed,
  // because `rebased` relies on a clean, untouched set of items in
  // order to associate old items with rebased steps.
  compress(upto = this.items.length) {
    let remap = this.remapping(0, upto), mapFrom = remap.maps.length;
    let items = [], events = 0;
    this.items.forEach((item, i) => {
      if (i >= upto) {
        items.push(item);
        if (item.selection)
          events++;
      } else if (item.step) {
        let step = item.step.map(remap.slice(mapFrom)), map2 = step && step.getMap();
        mapFrom--;
        if (map2)
          remap.appendMap(map2, mapFrom);
        if (step) {
          let selection = item.selection && item.selection.map(remap.slice(mapFrom));
          if (selection)
            events++;
          let newItem = new Item(map2.invert(), step, selection), merged, last = items.length - 1;
          if (merged = items.length && items[last].merge(newItem))
            items[last] = merged;
          else
            items.push(newItem);
        }
      } else if (item.map) {
        mapFrom--;
      }
    }, this.items.length, 0);
    return new _Branch(dist_default2.from(items.reverse()), events);
  }
};
Branch.empty = new Branch(dist_default2.empty, 0);
function cutOffEvents(items, n) {
  let cutPoint;
  items.forEach((item, i) => {
    if (item.selection && n-- == 0) {
      cutPoint = i;
      return false;
    }
  });
  return items.slice(cutPoint);
}
var Item = class _Item {
  constructor(map2, step, selection, mirrorOffset) {
    this.map = map2;
    this.step = step;
    this.selection = selection;
    this.mirrorOffset = mirrorOffset;
  }
  merge(other) {
    if (this.step && other.step && !other.selection) {
      let step = other.step.merge(this.step);
      if (step)
        return new _Item(step.getMap().invert(), step, this.selection);
    }
  }
};
var HistoryState = class {
  constructor(done, undone, prevRanges, prevTime, prevComposition) {
    this.done = done;
    this.undone = undone;
    this.prevRanges = prevRanges;
    this.prevTime = prevTime;
    this.prevComposition = prevComposition;
  }
};
var DEPTH_OVERFLOW = 20;
function applyTransaction(history2, state, tr2, options) {
  let historyTr = tr2.getMeta(historyKey), rebased;
  if (historyTr)
    return historyTr.historyState;
  if (tr2.getMeta(closeHistoryKey))
    history2 = new HistoryState(history2.done, history2.undone, null, 0, -1);
  let appended = tr2.getMeta("appendedTransaction");
  if (tr2.steps.length == 0) {
    return history2;
  } else if (appended && appended.getMeta(historyKey)) {
    if (appended.getMeta(historyKey).redo)
      return new HistoryState(history2.done.addTransform(tr2, void 0, options, mustPreserveItems(state)), history2.undone, rangesFor(tr2.mapping.maps), history2.prevTime, history2.prevComposition);
    else
      return new HistoryState(history2.done, history2.undone.addTransform(tr2, void 0, options, mustPreserveItems(state)), null, history2.prevTime, history2.prevComposition);
  } else if (tr2.getMeta("addToHistory") !== false && !(appended && appended.getMeta("addToHistory") === false)) {
    let composition = tr2.getMeta("composition");
    let newGroup = history2.prevTime == 0 || !appended && history2.prevComposition != composition && (history2.prevTime < (tr2.time || 0) - options.newGroupDelay || !isAdjacentTo(tr2, history2.prevRanges));
    let prevRanges = appended ? mapRanges(history2.prevRanges, tr2.mapping) : rangesFor(tr2.mapping.maps);
    return new HistoryState(history2.done.addTransform(tr2, newGroup ? state.selection.getBookmark() : void 0, options, mustPreserveItems(state)), Branch.empty, prevRanges, tr2.time, composition == null ? history2.prevComposition : composition);
  } else if (rebased = tr2.getMeta("rebased")) {
    return new HistoryState(history2.done.rebased(tr2, rebased), history2.undone.rebased(tr2, rebased), mapRanges(history2.prevRanges, tr2.mapping), history2.prevTime, history2.prevComposition);
  } else {
    return new HistoryState(history2.done.addMaps(tr2.mapping.maps), history2.undone.addMaps(tr2.mapping.maps), mapRanges(history2.prevRanges, tr2.mapping), history2.prevTime, history2.prevComposition);
  }
}
function isAdjacentTo(transform, prevRanges) {
  if (!prevRanges)
    return false;
  if (!transform.docChanged)
    return true;
  let adjacent = false;
  transform.mapping.maps[0].forEach((start, end) => {
    for (let i = 0; i < prevRanges.length; i += 2)
      if (start <= prevRanges[i + 1] && end >= prevRanges[i])
        adjacent = true;
  });
  return adjacent;
}
function rangesFor(maps) {
  let result = [];
  for (let i = maps.length - 1; i >= 0 && result.length == 0; i--)
    maps[i].forEach((_from, _to, from2, to) => result.push(from2, to));
  return result;
}
function mapRanges(ranges, mapping) {
  if (!ranges)
    return null;
  let result = [];
  for (let i = 0; i < ranges.length; i += 2) {
    let from2 = mapping.map(ranges[i], 1), to = mapping.map(ranges[i + 1], -1);
    if (from2 <= to)
      result.push(from2, to);
  }
  return result;
}
function histTransaction(history2, state, redo2) {
  let preserveItems = mustPreserveItems(state);
  let histOptions = historyKey.get(state).spec.config;
  let pop = (redo2 ? history2.undone : history2.done).popEvent(state, preserveItems);
  if (!pop)
    return null;
  let selection = pop.selection.resolve(pop.transform.doc);
  let added = (redo2 ? history2.done : history2.undone).addTransform(pop.transform, state.selection.getBookmark(), histOptions, preserveItems);
  let newHist = new HistoryState(redo2 ? added : pop.remaining, redo2 ? pop.remaining : added, null, 0, -1);
  return pop.transform.setSelection(selection).setMeta(historyKey, { redo: redo2, historyState: newHist });
}
var cachedPreserveItems = false;
var cachedPreserveItemsPlugins = null;
function mustPreserveItems(state) {
  let plugins = state.plugins;
  if (cachedPreserveItemsPlugins != plugins) {
    cachedPreserveItems = false;
    cachedPreserveItemsPlugins = plugins;
    for (let i = 0; i < plugins.length; i++)
      if (plugins[i].spec.historyPreserveItems) {
        cachedPreserveItems = true;
        break;
      }
  }
  return cachedPreserveItems;
}
var historyKey = new PluginKey("history");
var closeHistoryKey = new PluginKey("closeHistory");
function history(config = {}) {
  config = {
    depth: config.depth || 100,
    newGroupDelay: config.newGroupDelay || 500
  };
  return new Plugin({
    key: historyKey,
    state: {
      init() {
        return new HistoryState(Branch.empty, Branch.empty, null, 0, -1);
      },
      apply(tr2, hist, state) {
        return applyTransaction(hist, state, tr2, config);
      }
    },
    config,
    props: {
      handleDOMEvents: {
        beforeinput(view, e) {
          let inputType = e.inputType;
          let command2 = inputType == "historyUndo" ? undo : inputType == "historyRedo" ? redo : null;
          if (!command2 || !view.editable)
            return false;
          e.preventDefault();
          return command2(view.state, view.dispatch);
        }
      }
    }
  });
}
function buildCommand(redo2, scroll) {
  return (state, dispatch) => {
    let hist = historyKey.getState(state);
    if (!hist || (redo2 ? hist.undone : hist.done).eventCount == 0)
      return false;
    if (dispatch) {
      let tr2 = histTransaction(hist, state, redo2);
      if (tr2)
        dispatch(scroll ? tr2.scrollIntoView() : tr2);
    }
    return true;
  };
}
var undo = buildCommand(false, true);
var redo = buildCommand(true, true);
var undoNoScroll = buildCommand(false, false);
var redoNoScroll = buildCommand(true, false);

// ../../node_modules/.pnpm/@tiptap+extensions@3.15.3_@tiptap+core@3.15.3_@tiptap+pm@3.15.3__@tiptap+pm@3.15.3/node_modules/@tiptap/extensions/dist/index.js
var CharacterCount = Extension.create({
  name: "characterCount",
  addOptions() {
    return {
      limit: null,
      mode: "textSize",
      textCounter: (text5) => text5.length,
      wordCounter: (text5) => text5.split(" ").filter((word) => word !== "").length
    };
  },
  addStorage() {
    return {
      characters: () => 0,
      words: () => 0
    };
  },
  onBeforeCreate() {
    this.storage.characters = (options) => {
      const node = (options == null ? void 0 : options.node) || this.editor.state.doc;
      const mode = (options == null ? void 0 : options.mode) || this.options.mode;
      if (mode === "textSize") {
        const text5 = node.textBetween(0, node.content.size, void 0, " ");
        return this.options.textCounter(text5);
      }
      return node.nodeSize;
    };
    this.storage.words = (options) => {
      const node = (options == null ? void 0 : options.node) || this.editor.state.doc;
      const text5 = node.textBetween(0, node.content.size, " ", " ");
      return this.options.wordCounter(text5);
    };
  },
  addProseMirrorPlugins() {
    let initialEvaluationDone = false;
    return [
      new Plugin({
        key: new PluginKey("characterCount"),
        appendTransaction: (transactions, oldState, newState) => {
          if (initialEvaluationDone) {
            return;
          }
          const limit = this.options.limit;
          if (limit === null || limit === void 0 || limit === 0) {
            initialEvaluationDone = true;
            return;
          }
          const initialContentSize = this.storage.characters({ node: newState.doc });
          if (initialContentSize > limit) {
            const over = initialContentSize - limit;
            const from2 = 0;
            const to = over;
            console.warn(
              `[CharacterCount] Initial content exceeded limit of ${limit} characters. Content was automatically trimmed.`
            );
            const tr2 = newState.tr.deleteRange(from2, to);
            initialEvaluationDone = true;
            return tr2;
          }
          initialEvaluationDone = true;
        },
        filterTransaction: (transaction, state) => {
          const limit = this.options.limit;
          if (!transaction.docChanged || limit === 0 || limit === null || limit === void 0) {
            return true;
          }
          const oldSize = this.storage.characters({ node: state.doc });
          const newSize = this.storage.characters({ node: transaction.doc });
          if (newSize <= limit) {
            return true;
          }
          if (oldSize > limit && newSize > limit && newSize <= oldSize) {
            return true;
          }
          if (oldSize > limit && newSize > limit && newSize > oldSize) {
            return false;
          }
          const isPaste = transaction.getMeta("paste");
          if (!isPaste) {
            return false;
          }
          const pos = transaction.selection.$head.pos;
          const over = newSize - limit;
          const from2 = pos - over;
          const to = pos;
          transaction.deleteRange(from2, to);
          const updatedSize = this.storage.characters({ node: transaction.doc });
          if (updatedSize > limit) {
            return false;
          }
          return true;
        }
      })
    ];
  }
});
var Dropcursor = Extension.create({
  name: "dropCursor",
  addOptions() {
    return {
      color: "currentColor",
      width: 1,
      class: void 0
    };
  },
  addProseMirrorPlugins() {
    return [dropCursor(this.options)];
  }
});
var Focus = Extension.create({
  name: "focus",
  addOptions() {
    return {
      className: "has-focus",
      mode: "all"
    };
  },
  addProseMirrorPlugins() {
    return [
      new Plugin({
        key: new PluginKey("focus"),
        props: {
          decorations: ({ doc: doc3, selection }) => {
            const { isEditable, isFocused } = this.editor;
            const { anchor } = selection;
            const decorations = [];
            if (!isEditable || !isFocused) {
              return DecorationSet.create(doc3, []);
            }
            let maxLevels = 0;
            if (this.options.mode === "deepest") {
              doc3.descendants((node, pos) => {
                if (node.isText) {
                  return;
                }
                const isCurrent = anchor >= pos && anchor <= pos + node.nodeSize - 1;
                if (!isCurrent) {
                  return false;
                }
                maxLevels += 1;
              });
            }
            let currentLevel = 0;
            doc3.descendants((node, pos) => {
              if (node.isText) {
                return false;
              }
              const isCurrent = anchor >= pos && anchor <= pos + node.nodeSize - 1;
              if (!isCurrent) {
                return false;
              }
              currentLevel += 1;
              const outOfScope = this.options.mode === "deepest" && maxLevels - currentLevel > 0 || this.options.mode === "shallowest" && currentLevel > 1;
              if (outOfScope) {
                return this.options.mode === "deepest";
              }
              decorations.push(
                Decoration.node(pos, pos + node.nodeSize, {
                  class: this.options.className
                })
              );
            });
            return DecorationSet.create(doc3, decorations);
          }
        }
      })
    ];
  }
});
var Gapcursor = Extension.create({
  name: "gapCursor",
  addProseMirrorPlugins() {
    return [gapCursor()];
  },
  extendNodeSchema(extension) {
    var _a;
    const context = {
      name: extension.name,
      options: extension.options,
      storage: extension.storage
    };
    return {
      allowGapCursor: (_a = callOrReturn(getExtensionField(extension, "allowGapCursor", context))) != null ? _a : null
    };
  }
});
var Placeholder = Extension.create({
  name: "placeholder",
  addOptions() {
    return {
      emptyEditorClass: "is-editor-empty",
      emptyNodeClass: "is-empty",
      placeholder: "Write something \u2026",
      showOnlyWhenEditable: true,
      showOnlyCurrent: true,
      includeChildren: false
    };
  },
  addProseMirrorPlugins() {
    return [
      new Plugin({
        key: new PluginKey("placeholder"),
        props: {
          decorations: ({ doc: doc3, selection }) => {
            const active = this.editor.isEditable || !this.options.showOnlyWhenEditable;
            const { anchor } = selection;
            const decorations = [];
            if (!active) {
              return null;
            }
            const isEmptyDoc = this.editor.isEmpty;
            doc3.descendants((node, pos) => {
              const hasAnchor = anchor >= pos && anchor <= pos + node.nodeSize;
              const isEmpty = !node.isLeaf && isNodeEmpty(node);
              if ((hasAnchor || !this.options.showOnlyCurrent) && isEmpty) {
                const classes = [this.options.emptyNodeClass];
                if (isEmptyDoc) {
                  classes.push(this.options.emptyEditorClass);
                }
                const decoration = Decoration.node(pos, pos + node.nodeSize, {
                  class: classes.join(" "),
                  "data-placeholder": typeof this.options.placeholder === "function" ? this.options.placeholder({
                    editor: this.editor,
                    node,
                    pos,
                    hasAnchor
                  }) : this.options.placeholder
                });
                decorations.push(decoration);
              }
              return this.options.includeChildren;
            });
            return DecorationSet.create(doc3, decorations);
          }
        }
      })
    ];
  }
});
var Selection2 = Extension.create({
  name: "selection",
  addOptions() {
    return {
      className: "selection"
    };
  },
  addProseMirrorPlugins() {
    const { editor, options } = this;
    return [
      new Plugin({
        key: new PluginKey("selection"),
        props: {
          decorations(state) {
            if (state.selection.empty || editor.isFocused || !editor.isEditable || isNodeSelection(state.selection) || editor.view.dragging) {
              return null;
            }
            return DecorationSet.create(state.doc, [
              Decoration.inline(state.selection.from, state.selection.to, {
                class: options.className
              })
            ]);
          }
        }
      })
    ];
  }
});
function nodeEqualsType({ types, node }) {
  return node && Array.isArray(types) && types.includes(node.type) || (node == null ? void 0 : node.type) === types;
}
var TrailingNode = Extension.create({
  name: "trailingNode",
  addOptions() {
    return {
      node: void 0,
      notAfter: []
    };
  },
  addProseMirrorPlugins() {
    var _a;
    const plugin = new PluginKey(this.name);
    const defaultNode = this.options.node || ((_a = this.editor.schema.topNodeType.contentMatch.defaultType) == null ? void 0 : _a.name) || "paragraph";
    const disabledNodes = Object.entries(this.editor.schema.nodes).map(([, value]) => value).filter((node) => (this.options.notAfter || []).concat(defaultNode).includes(node.name));
    return [
      new Plugin({
        key: plugin,
        appendTransaction: (_10, __, state) => {
          const { doc: doc3, tr: tr2, schema } = state;
          const shouldInsertNodeAtEnd = plugin.getState(state);
          const endPosition = doc3.content.size;
          const type = schema.nodes[defaultNode];
          if (!shouldInsertNodeAtEnd) {
            return;
          }
          return tr2.insert(endPosition, type.create());
        },
        state: {
          init: (_10, state) => {
            const lastNode = state.tr.doc.lastChild;
            return !nodeEqualsType({ node: lastNode, types: disabledNodes });
          },
          apply: (tr2, value) => {
            if (!tr2.docChanged) {
              return value;
            }
            if (tr2.getMeta("__uniqueIDTransaction")) {
              return value;
            }
            const lastNode = tr2.doc.lastChild;
            return !nodeEqualsType({ node: lastNode, types: disabledNodes });
          }
        }
      })
    ];
  }
});
var UndoRedo = Extension.create({
  name: "undoRedo",
  addOptions() {
    return {
      depth: 100,
      newGroupDelay: 500
    };
  },
  addCommands() {
    return {
      undo: () => ({ state, dispatch }) => {
        return undo(state, dispatch);
      },
      redo: () => ({ state, dispatch }) => {
        return redo(state, dispatch);
      }
    };
  },
  addProseMirrorPlugins() {
    return [history(this.options)];
  },
  addKeyboardShortcuts() {
    return {
      "Mod-z": () => this.editor.commands.undo(),
      "Shift-Mod-z": () => this.editor.commands.redo(),
      "Mod-y": () => this.editor.commands.redo(),
      // Russian keyboard layouts
      "Mod-\u044F": () => this.editor.commands.undo(),
      "Shift-Mod-\u044F": () => this.editor.commands.redo()
    };
  }
});

// ../../node_modules/.pnpm/@tiptap+starter-kit@3.15.3/node_modules/@tiptap/starter-kit/dist/index.js
var StarterKit = Extension.create({
  name: "starterKit",
  addExtensions() {
    var _a, _b, _c, _d;
    const extensions = [];
    if (this.options.bold !== false) {
      extensions.push(Bold.configure(this.options.bold));
    }
    if (this.options.blockquote !== false) {
      extensions.push(Blockquote.configure(this.options.blockquote));
    }
    if (this.options.bulletList !== false) {
      extensions.push(BulletList.configure(this.options.bulletList));
    }
    if (this.options.code !== false) {
      extensions.push(Code.configure(this.options.code));
    }
    if (this.options.codeBlock !== false) {
      extensions.push(CodeBlock.configure(this.options.codeBlock));
    }
    if (this.options.document !== false) {
      extensions.push(Document.configure(this.options.document));
    }
    if (this.options.dropcursor !== false) {
      extensions.push(Dropcursor.configure(this.options.dropcursor));
    }
    if (this.options.gapcursor !== false) {
      extensions.push(Gapcursor.configure(this.options.gapcursor));
    }
    if (this.options.hardBreak !== false) {
      extensions.push(HardBreak.configure(this.options.hardBreak));
    }
    if (this.options.heading !== false) {
      extensions.push(Heading.configure(this.options.heading));
    }
    if (this.options.undoRedo !== false) {
      extensions.push(UndoRedo.configure(this.options.undoRedo));
    }
    if (this.options.horizontalRule !== false) {
      extensions.push(HorizontalRule.configure(this.options.horizontalRule));
    }
    if (this.options.italic !== false) {
      extensions.push(Italic.configure(this.options.italic));
    }
    if (this.options.listItem !== false) {
      extensions.push(ListItem.configure(this.options.listItem));
    }
    if (this.options.listKeymap !== false) {
      extensions.push(ListKeymap.configure((_a = this.options) == null ? void 0 : _a.listKeymap));
    }
    if (this.options.link !== false) {
      extensions.push(Link.configure((_b = this.options) == null ? void 0 : _b.link));
    }
    if (this.options.orderedList !== false) {
      extensions.push(OrderedList.configure(this.options.orderedList));
    }
    if (this.options.paragraph !== false) {
      extensions.push(Paragraph.configure(this.options.paragraph));
    }
    if (this.options.strike !== false) {
      extensions.push(Strike.configure(this.options.strike));
    }
    if (this.options.text !== false) {
      extensions.push(Text2.configure(this.options.text));
    }
    if (this.options.underline !== false) {
      extensions.push(Underline.configure((_c = this.options) == null ? void 0 : _c.underline));
    }
    if (this.options.trailingNode !== false) {
      extensions.push(TrailingNode.configure((_d = this.options) == null ? void 0 : _d.trailingNode));
    }
    return extensions;
  }
});
var index_default = StarterKit;

// ../editor-tiptap/dist/code-highlight.js
function escapeHtml(text5) {
  return text5.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;").replaceAll("'", "&#039;");
}
function tokenizeJson(code) {
  const tokens = [];
  const pattern = /"(?:\\.|[^"\\])*"(?=\s*:)|"(?:\\.|[^"\\])*"|true|false|null|-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?|[{}[\]:,]/g;
  let lastIndex = 0;
  for (const match of code.matchAll(pattern)) {
    const start = match.index ?? 0;
    const value = match[0] ?? "";
    if (start > lastIndex) {
      tokens.push({ from: lastIndex, to: start, kind: "plain" });
    }
    const kind = (() => {
      if (value[0] === '"') {
        const end = start + value.length;
        let i = end;
        while (i < code.length && /\s/.test(code[i] ?? ""))
          i += 1;
        return code[i] === ":" ? "property" : "string";
      }
      if (value === "true" || value === "false" || value === "null")
        return "keyword";
      if (value.length === 1 && "{}[]:,".includes(value))
        return "punct";
      if (value.match(/^-?\d/))
        return "number";
      return "plain";
    })();
    tokens.push({ from: start, to: start + value.length, kind });
    lastIndex = start + value.length;
  }
  if (lastIndex < code.length)
    tokens.push({ from: lastIndex, to: code.length, kind: "plain" });
  return tokens;
}
function tokenizeJsLike(code) {
  const keywordSet = /* @__PURE__ */ new Set([
    "break",
    "case",
    "catch",
    "class",
    "const",
    "continue",
    "debugger",
    "default",
    "delete",
    "do",
    "else",
    "export",
    "extends",
    "finally",
    "for",
    "function",
    "if",
    "import",
    "in",
    "instanceof",
    "let",
    "new",
    "return",
    "super",
    "switch",
    "this",
    "throw",
    "try",
    "typeof",
    "var",
    "void",
    "while",
    "with",
    "yield",
    "as",
    "async",
    "await",
    "interface",
    "type",
    "implements",
    "private",
    "protected",
    "public",
    "readonly",
    "enum",
    "namespace",
    "declare",
    "from",
    "of"
  ]);
  const tokens = [];
  const pattern = /\/\*[\s\S]*?\*\/|\/\/[^\n]*|`(?:\\.|[^`\\])*`|"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?|[{}()[\];,.]|=>|==={0,1}|!=={0,1}|\b[A-Za-z_$][A-Za-z0-9_$]*\b/g;
  let lastIndex = 0;
  for (const match of code.matchAll(pattern)) {
    const start = match.index ?? 0;
    const value = match[0] ?? "";
    if (start > lastIndex) {
      tokens.push({ from: lastIndex, to: start, kind: "plain" });
    }
    const kind = (() => {
      if (value.startsWith("/*") || value.startsWith("//"))
        return "comment";
      if (value[0] === '"' || value[0] === "'" || value[0] === "`")
        return "string";
      if (value.match(/^-?\d/))
        return "number";
      if (value.length === 1 && "{}()[];,. ".includes(value))
        return "punct";
      if (keywordSet.has(value))
        return "keyword";
      return "plain";
    })();
    tokens.push({ from: start, to: start + value.length, kind });
    lastIndex = start + value.length;
  }
  if (lastIndex < code.length)
    tokens.push({ from: lastIndex, to: code.length, kind: "plain" });
  return tokens;
}
function guessLanguage(code) {
  const trimmed = code.trim();
  if (trimmed.startsWith("{") || trimmed.startsWith("["))
    return "json";
  return "js";
}
function tokenizeKmindCode(args) {
  const code = args.code;
  const hint = typeof args.languageHint === "string" ? args.languageHint.trim().toLowerCase() : "";
  if (hint === "json")
    return tokenizeJson(code);
  if (hint === "js" || hint === "javascript" || hint === "ts" || hint === "typescript")
    return tokenizeJsLike(code);
  const guessed = guessLanguage(code);
  if (guessed === "json")
    return tokenizeJson(code);
  if (guessed === "js")
    return tokenizeJsLike(code);
  return [{ from: 0, to: code.length, kind: "plain" }];
}
function highlightKmindCodeToHtml(code, languageHint) {
  const tokens = tokenizeKmindCode(languageHint === void 0 ? { code } : { code, languageHint });
  let out = "";
  for (const token of tokens) {
    const raw = code.slice(token.from, token.to);
    if (token.kind === "plain") {
      out += escapeHtml(raw);
      continue;
    }
    out += `<span class="km-code-token km-code-token--${token.kind}">${escapeHtml(raw)}</span>`;
  }
  return out;
}

// ../editor-tiptap/dist/code-highlight-extension.js
var pluginKey = new PluginKey("kmindCodeHighlight");
function buildDecorations(doc3) {
  const decorations = [];
  doc3.descendants((node, pos) => {
    if (node.type.name !== "codeBlock")
      return;
    if (node.textContent.length === 0)
      return;
    const code = node.textContent;
    const tokens = tokenizeKmindCode({ code, languageHint: null });
    if (tokens.length === 0)
      return;
    const offsetToDocPos = new Array(code.length + 1);
    let offset = 0;
    node.descendants((child, childPos) => {
      if (!child.isText)
        return;
      const text5 = child.text ?? "";
      const base2 = pos + childPos;
      for (let i = 0; i <= text5.length; i += 1) {
        offsetToDocPos[offset + i] = base2 + i;
      }
      offset += text5.length;
    });
    if (offset !== code.length) {
      for (let i = 0; i <= code.length; i += 1) {
        offsetToDocPos[i] = pos + 1 + i;
      }
    }
    for (const token of tokens) {
      if (token.kind === "plain")
        continue;
      const from2 = offsetToDocPos[token.from];
      const to = offsetToDocPos[token.to];
      if (typeof from2 !== "number" || typeof to !== "number")
        continue;
      if (to <= from2)
        continue;
      decorations.push(Decoration.inline(from2, to, { class: `km-code-token km-code-token--${token.kind}` }));
    }
  });
  return DecorationSet.create(doc3, decorations);
}
var KmCodeHighlight = Extension.create({
  name: "kmindCodeHighlight",
  addProseMirrorPlugins() {
    return [
      new Plugin({
        key: pluginKey,
        state: {
          init: (_config, state) => buildDecorations(state.doc),
          apply: (tr2, prev, _oldState, newState) => {
            if (!tr2.docChanged)
              return prev;
            return buildDecorations(newState.doc);
          }
        },
        props: {
          decorations(state) {
            return pluginKey.getState(state) ?? null;
          }
        }
      })
    ];
  }
});

// ../../node_modules/.pnpm/katex@0.16.22/node_modules/katex/dist/katex.mjs
var SourceLocation = class _SourceLocation {
  // The + prefix indicates that these fields aren't writeable
  // Lexer holding the input string.
  // Start offset, zero-based inclusive.
  // End offset, zero-based exclusive.
  constructor(lexer, start, end) {
    this.lexer = void 0;
    this.start = void 0;
    this.end = void 0;
    this.lexer = lexer;
    this.start = start;
    this.end = end;
  }
  /**
   * Merges two `SourceLocation`s from location providers, given they are
   * provided in order of appearance.
   * - Returns the first one's location if only the first is provided.
   * - Returns a merged range of the first and the last if both are provided
   *   and their lexers match.
   * - Otherwise, returns null.
   */
  static range(first2, second) {
    if (!second) {
      return first2 && first2.loc;
    } else if (!first2 || !first2.loc || !second.loc || first2.loc.lexer !== second.loc.lexer) {
      return null;
    } else {
      return new _SourceLocation(first2.loc.lexer, first2.loc.start, second.loc.end);
    }
  }
};
var Token = class _Token {
  // don't expand the token
  // used in \noexpand
  constructor(text5, loc) {
    this.text = void 0;
    this.loc = void 0;
    this.noexpand = void 0;
    this.treatAsRelax = void 0;
    this.text = text5;
    this.loc = loc;
  }
  /**
   * Given a pair of tokens (this and endToken), compute a `Token` encompassing
   * the whole input range enclosed by these two.
   */
  range(endToken, text5) {
    return new _Token(text5, SourceLocation.range(this, endToken));
  }
};
var ParseError = class _ParseError {
  // Error start position based on passed-in Token or ParseNode.
  // Length of affected text based on passed-in Token or ParseNode.
  // The underlying error message without any context added.
  constructor(message, token) {
    this.name = void 0;
    this.position = void 0;
    this.length = void 0;
    this.rawMessage = void 0;
    var error = "KaTeX parse error: " + message;
    var start;
    var end;
    var loc = token && token.loc;
    if (loc && loc.start <= loc.end) {
      var input = loc.lexer.input;
      start = loc.start;
      end = loc.end;
      if (start === input.length) {
        error += " at end of input: ";
      } else {
        error += " at position " + (start + 1) + ": ";
      }
      var underlined = input.slice(start, end).replace(/[^]/g, "$&\u0332");
      var left;
      if (start > 15) {
        left = "\u2026" + input.slice(start - 15, start);
      } else {
        left = input.slice(0, start);
      }
      var right;
      if (end + 15 < input.length) {
        right = input.slice(end, end + 15) + "\u2026";
      } else {
        right = input.slice(end);
      }
      error += left + underlined + right;
    }
    var self = new Error(error);
    self.name = "ParseError";
    self.__proto__ = _ParseError.prototype;
    self.position = start;
    if (start != null && end != null) {
      self.length = end - start;
    }
    self.rawMessage = message;
    return self;
  }
};
ParseError.prototype.__proto__ = Error.prototype;
var contains = function contains2(list, elem) {
  return list.indexOf(elem) !== -1;
};
var deflt = function deflt2(setting, defaultIfUndefined) {
  return setting === void 0 ? defaultIfUndefined : setting;
};
var uppercase = /([A-Z])/g;
var hyphenate = function hyphenate2(str) {
  return str.replace(uppercase, "-$1").toLowerCase();
};
var ESCAPE_LOOKUP = {
  "&": "&amp;",
  ">": "&gt;",
  "<": "&lt;",
  '"': "&quot;",
  "'": "&#x27;"
};
var ESCAPE_REGEX = /[&><"']/g;
function escape(text5) {
  return String(text5).replace(ESCAPE_REGEX, (match) => ESCAPE_LOOKUP[match]);
}
var getBaseElem = function getBaseElem2(group) {
  if (group.type === "ordgroup") {
    if (group.body.length === 1) {
      return getBaseElem2(group.body[0]);
    } else {
      return group;
    }
  } else if (group.type === "color") {
    if (group.body.length === 1) {
      return getBaseElem2(group.body[0]);
    } else {
      return group;
    }
  } else if (group.type === "font") {
    return getBaseElem2(group.body);
  } else {
    return group;
  }
};
var isCharacterBox = function isCharacterBox2(group) {
  var baseElem = getBaseElem(group);
  return baseElem.type === "mathord" || baseElem.type === "textord" || baseElem.type === "atom";
};
var assert = function assert2(value) {
  if (!value) {
    throw new Error("Expected non-null, but got " + String(value));
  }
  return value;
};
var protocolFromUrl = function protocolFromUrl2(url) {
  var protocol = /^[\x00-\x20]*([^\\/#?]*?)(:|&#0*58|&#x0*3a|&colon)/i.exec(url);
  if (!protocol) {
    return "_relative";
  }
  if (protocol[2] !== ":") {
    return null;
  }
  if (!/^[a-zA-Z][a-zA-Z0-9+\-.]*$/.test(protocol[1])) {
    return null;
  }
  return protocol[1].toLowerCase();
};
var utils = {
  contains,
  deflt,
  escape,
  hyphenate,
  getBaseElem,
  isCharacterBox,
  protocolFromUrl
};
var SETTINGS_SCHEMA = {
  displayMode: {
    type: "boolean",
    description: "Render math in display mode, which puts the math in display style (so \\int and \\sum are large, for example), and centers the math on the page on its own line.",
    cli: "-d, --display-mode"
  },
  output: {
    type: {
      enum: ["htmlAndMathml", "html", "mathml"]
    },
    description: "Determines the markup language of the output.",
    cli: "-F, --format <type>"
  },
  leqno: {
    type: "boolean",
    description: "Render display math in leqno style (left-justified tags)."
  },
  fleqn: {
    type: "boolean",
    description: "Render display math flush left."
  },
  throwOnError: {
    type: "boolean",
    default: true,
    cli: "-t, --no-throw-on-error",
    cliDescription: "Render errors (in the color given by --error-color) instead of throwing a ParseError exception when encountering an error."
  },
  errorColor: {
    type: "string",
    default: "#cc0000",
    cli: "-c, --error-color <color>",
    cliDescription: "A color string given in the format 'rgb' or 'rrggbb' (no #). This option determines the color of errors rendered by the -t option.",
    cliProcessor: (color) => "#" + color
  },
  macros: {
    type: "object",
    cli: "-m, --macro <def>",
    cliDescription: "Define custom macro of the form '\\foo:expansion' (use multiple -m arguments for multiple macros).",
    cliDefault: [],
    cliProcessor: (def, defs) => {
      defs.push(def);
      return defs;
    }
  },
  minRuleThickness: {
    type: "number",
    description: "Specifies a minimum thickness, in ems, for fraction lines, `\\sqrt` top lines, `{array}` vertical lines, `\\hline`, `\\hdashline`, `\\underline`, `\\overline`, and the borders of `\\fbox`, `\\boxed`, and `\\fcolorbox`.",
    processor: (t) => Math.max(0, t),
    cli: "--min-rule-thickness <size>",
    cliProcessor: parseFloat
  },
  colorIsTextColor: {
    type: "boolean",
    description: "Makes \\color behave like LaTeX's 2-argument \\textcolor, instead of LaTeX's one-argument \\color mode change.",
    cli: "-b, --color-is-text-color"
  },
  strict: {
    type: [{
      enum: ["warn", "ignore", "error"]
    }, "boolean", "function"],
    description: "Turn on strict / LaTeX faithfulness mode, which throws an error if the input uses features that are not supported by LaTeX.",
    cli: "-S, --strict",
    cliDefault: false
  },
  trust: {
    type: ["boolean", "function"],
    description: "Trust the input, enabling all HTML features such as \\url.",
    cli: "-T, --trust"
  },
  maxSize: {
    type: "number",
    default: Infinity,
    description: "If non-zero, all user-specified sizes, e.g. in \\rule{500em}{500em}, will be capped to maxSize ems. Otherwise, elements and spaces can be arbitrarily large",
    processor: (s) => Math.max(0, s),
    cli: "-s, --max-size <n>",
    cliProcessor: parseInt
  },
  maxExpand: {
    type: "number",
    default: 1e3,
    description: "Limit the number of macro expansions to the specified number, to prevent e.g. infinite macro loops. If set to Infinity, the macro expander will try to fully expand as in LaTeX.",
    processor: (n) => Math.max(0, n),
    cli: "-e, --max-expand <n>",
    cliProcessor: (n) => n === "Infinity" ? Infinity : parseInt(n)
  },
  globalGroup: {
    type: "boolean",
    cli: false
  }
};
function getDefaultValue(schema) {
  if (schema.default) {
    return schema.default;
  }
  var type = schema.type;
  var defaultType = Array.isArray(type) ? type[0] : type;
  if (typeof defaultType !== "string") {
    return defaultType.enum[0];
  }
  switch (defaultType) {
    case "boolean":
      return false;
    case "string":
      return "";
    case "number":
      return 0;
    case "object":
      return {};
  }
}
var Settings = class {
  constructor(options) {
    this.displayMode = void 0;
    this.output = void 0;
    this.leqno = void 0;
    this.fleqn = void 0;
    this.throwOnError = void 0;
    this.errorColor = void 0;
    this.macros = void 0;
    this.minRuleThickness = void 0;
    this.colorIsTextColor = void 0;
    this.strict = void 0;
    this.trust = void 0;
    this.maxSize = void 0;
    this.maxExpand = void 0;
    this.globalGroup = void 0;
    options = options || {};
    for (var prop in SETTINGS_SCHEMA) {
      if (SETTINGS_SCHEMA.hasOwnProperty(prop)) {
        var schema = SETTINGS_SCHEMA[prop];
        this[prop] = options[prop] !== void 0 ? schema.processor ? schema.processor(options[prop]) : options[prop] : getDefaultValue(schema);
      }
    }
  }
  /**
   * Report nonstrict (non-LaTeX-compatible) input.
   * Can safely not be called if `this.strict` is false in JavaScript.
   */
  reportNonstrict(errorCode, errorMsg, token) {
    var strict = this.strict;
    if (typeof strict === "function") {
      strict = strict(errorCode, errorMsg, token);
    }
    if (!strict || strict === "ignore") {
      return;
    } else if (strict === true || strict === "error") {
      throw new ParseError("LaTeX-incompatible input and strict mode is set to 'error': " + (errorMsg + " [" + errorCode + "]"), token);
    } else if (strict === "warn") {
      typeof console !== "undefined" && console.warn("LaTeX-incompatible input and strict mode is set to 'warn': " + (errorMsg + " [" + errorCode + "]"));
    } else {
      typeof console !== "undefined" && console.warn("LaTeX-incompatible input and strict mode is set to " + ("unrecognized '" + strict + "': " + errorMsg + " [" + errorCode + "]"));
    }
  }
  /**
   * Check whether to apply strict (LaTeX-adhering) behavior for unusual
   * input (like `\\`).  Unlike `nonstrict`, will not throw an error;
   * instead, "error" translates to a return value of `true`, while "ignore"
   * translates to a return value of `false`.  May still print a warning:
   * "warn" prints a warning and returns `false`.
   * This is for the second category of `errorCode`s listed in the README.
   */
  useStrictBehavior(errorCode, errorMsg, token) {
    var strict = this.strict;
    if (typeof strict === "function") {
      try {
        strict = strict(errorCode, errorMsg, token);
      } catch (error) {
        strict = "error";
      }
    }
    if (!strict || strict === "ignore") {
      return false;
    } else if (strict === true || strict === "error") {
      return true;
    } else if (strict === "warn") {
      typeof console !== "undefined" && console.warn("LaTeX-incompatible input and strict mode is set to 'warn': " + (errorMsg + " [" + errorCode + "]"));
      return false;
    } else {
      typeof console !== "undefined" && console.warn("LaTeX-incompatible input and strict mode is set to " + ("unrecognized '" + strict + "': " + errorMsg + " [" + errorCode + "]"));
      return false;
    }
  }
  /**
   * Check whether to test potentially dangerous input, and return
   * `true` (trusted) or `false` (untrusted).  The sole argument `context`
   * should be an object with `command` field specifying the relevant LaTeX
   * command (as a string starting with `\`), and any other arguments, etc.
   * If `context` has a `url` field, a `protocol` field will automatically
   * get added by this function (changing the specified object).
   */
  isTrusted(context) {
    if (context.url && !context.protocol) {
      var protocol = utils.protocolFromUrl(context.url);
      if (protocol == null) {
        return false;
      }
      context.protocol = protocol;
    }
    var trust = typeof this.trust === "function" ? this.trust(context) : this.trust;
    return Boolean(trust);
  }
};
var Style = class {
  constructor(id, size, cramped) {
    this.id = void 0;
    this.size = void 0;
    this.cramped = void 0;
    this.id = id;
    this.size = size;
    this.cramped = cramped;
  }
  /**
   * Get the style of a superscript given a base in the current style.
   */
  sup() {
    return styles[sup[this.id]];
  }
  /**
   * Get the style of a subscript given a base in the current style.
   */
  sub() {
    return styles[sub[this.id]];
  }
  /**
   * Get the style of a fraction numerator given the fraction in the current
   * style.
   */
  fracNum() {
    return styles[fracNum[this.id]];
  }
  /**
   * Get the style of a fraction denominator given the fraction in the current
   * style.
   */
  fracDen() {
    return styles[fracDen[this.id]];
  }
  /**
   * Get the cramped version of a style (in particular, cramping a cramped style
   * doesn't change the style).
   */
  cramp() {
    return styles[cramp[this.id]];
  }
  /**
   * Get a text or display version of this style.
   */
  text() {
    return styles[text$1[this.id]];
  }
  /**
   * Return true if this style is tightly spaced (scriptstyle/scriptscriptstyle)
   */
  isTight() {
    return this.size >= 2;
  }
};
var D = 0;
var Dc = 1;
var T = 2;
var Tc = 3;
var S = 4;
var Sc = 5;
var SS = 6;
var SSc = 7;
var styles = [new Style(D, 0, false), new Style(Dc, 0, true), new Style(T, 1, false), new Style(Tc, 1, true), new Style(S, 2, false), new Style(Sc, 2, true), new Style(SS, 3, false), new Style(SSc, 3, true)];
var sup = [S, Sc, S, Sc, SS, SSc, SS, SSc];
var sub = [Sc, Sc, Sc, Sc, SSc, SSc, SSc, SSc];
var fracNum = [T, Tc, S, Sc, SS, SSc, SS, SSc];
var fracDen = [Tc, Tc, Sc, Sc, SSc, SSc, SSc, SSc];
var cramp = [Dc, Dc, Tc, Tc, Sc, Sc, SSc, SSc];
var text$1 = [D, Dc, T, Tc, T, Tc, T, Tc];
var Style$1 = {
  DISPLAY: styles[D],
  TEXT: styles[T],
  SCRIPT: styles[S],
  SCRIPTSCRIPT: styles[SS]
};
var scriptData = [{
  // Latin characters beyond the Latin-1 characters we have metrics for.
  // Needed for Czech, Hungarian and Turkish text, for example.
  name: "latin",
  blocks: [
    [256, 591],
    // Latin Extended-A and Latin Extended-B
    [768, 879]
    // Combining Diacritical marks
  ]
}, {
  // The Cyrillic script used by Russian and related languages.
  // A Cyrillic subset used to be supported as explicitly defined
  // symbols in symbols.js
  name: "cyrillic",
  blocks: [[1024, 1279]]
}, {
  // Armenian
  name: "armenian",
  blocks: [[1328, 1423]]
}, {
  // The Brahmic scripts of South and Southeast Asia
  // Devanagari (0900–097F)
  // Bengali (0980–09FF)
  // Gurmukhi (0A00–0A7F)
  // Gujarati (0A80–0AFF)
  // Oriya (0B00–0B7F)
  // Tamil (0B80–0BFF)
  // Telugu (0C00–0C7F)
  // Kannada (0C80–0CFF)
  // Malayalam (0D00–0D7F)
  // Sinhala (0D80–0DFF)
  // Thai (0E00–0E7F)
  // Lao (0E80–0EFF)
  // Tibetan (0F00–0FFF)
  // Myanmar (1000–109F)
  name: "brahmic",
  blocks: [[2304, 4255]]
}, {
  name: "georgian",
  blocks: [[4256, 4351]]
}, {
  // Chinese and Japanese.
  // The "k" in cjk is for Korean, but we've separated Korean out
  name: "cjk",
  blocks: [
    [12288, 12543],
    // CJK symbols and punctuation, Hiragana, Katakana
    [19968, 40879],
    // CJK ideograms
    [65280, 65376]
    // Fullwidth punctuation
    // TODO: add halfwidth Katakana and Romanji glyphs
  ]
}, {
  // Korean
  name: "hangul",
  blocks: [[44032, 55215]]
}];
function scriptFromCodepoint(codepoint) {
  for (var i = 0; i < scriptData.length; i++) {
    var script = scriptData[i];
    for (var _i = 0; _i < script.blocks.length; _i++) {
      var block = script.blocks[_i];
      if (codepoint >= block[0] && codepoint <= block[1]) {
        return script.name;
      }
    }
  }
  return null;
}
var allBlocks = [];
scriptData.forEach((s) => s.blocks.forEach((b2) => allBlocks.push(...b2)));
function supportedCodepoint(codepoint) {
  for (var i = 0; i < allBlocks.length; i += 2) {
    if (codepoint >= allBlocks[i] && codepoint <= allBlocks[i + 1]) {
      return true;
    }
  }
  return false;
}
var hLinePad = 80;
var sqrtMain = function sqrtMain2(extraVinculum, hLinePad2) {
  return "M95," + (622 + extraVinculum + hLinePad2) + "\nc-2.7,0,-7.17,-2.7,-13.5,-8c-5.8,-5.3,-9.5,-10,-9.5,-14\nc0,-2,0.3,-3.3,1,-4c1.3,-2.7,23.83,-20.7,67.5,-54\nc44.2,-33.3,65.8,-50.3,66.5,-51c1.3,-1.3,3,-2,5,-2c4.7,0,8.7,3.3,12,10\ns173,378,173,378c0.7,0,35.3,-71,104,-213c68.7,-142,137.5,-285,206.5,-429\nc69,-144,104.5,-217.7,106.5,-221\nl" + extraVinculum / 2.075 + " -" + extraVinculum + "\nc5.3,-9.3,12,-14,20,-14\nH400000v" + (40 + extraVinculum) + "H845.2724\ns-225.272,467,-225.272,467s-235,486,-235,486c-2.7,4.7,-9,7,-19,7\nc-6,0,-10,-1,-12,-3s-194,-422,-194,-422s-65,47,-65,47z\nM" + (834 + extraVinculum) + " " + hLinePad2 + "h400000v" + (40 + extraVinculum) + "h-400000z";
};
var sqrtSize1 = function sqrtSize12(extraVinculum, hLinePad2) {
  return "M263," + (601 + extraVinculum + hLinePad2) + "c0.7,0,18,39.7,52,119\nc34,79.3,68.167,158.7,102.5,238c34.3,79.3,51.8,119.3,52.5,120\nc340,-704.7,510.7,-1060.3,512,-1067\nl" + extraVinculum / 2.084 + " -" + extraVinculum + "\nc4.7,-7.3,11,-11,19,-11\nH40000v" + (40 + extraVinculum) + "H1012.3\ns-271.3,567,-271.3,567c-38.7,80.7,-84,175,-136,283c-52,108,-89.167,185.3,-111.5,232\nc-22.3,46.7,-33.8,70.3,-34.5,71c-4.7,4.7,-12.3,7,-23,7s-12,-1,-12,-1\ns-109,-253,-109,-253c-72.7,-168,-109.3,-252,-110,-252c-10.7,8,-22,16.7,-34,26\nc-22,17.3,-33.3,26,-34,26s-26,-26,-26,-26s76,-59,76,-59s76,-60,76,-60z\nM" + (1001 + extraVinculum) + " " + hLinePad2 + "h400000v" + (40 + extraVinculum) + "h-400000z";
};
var sqrtSize2 = function sqrtSize22(extraVinculum, hLinePad2) {
  return "M983 " + (10 + extraVinculum + hLinePad2) + "\nl" + extraVinculum / 3.13 + " -" + extraVinculum + "\nc4,-6.7,10,-10,18,-10 H400000v" + (40 + extraVinculum) + "\nH1013.1s-83.4,268,-264.1,840c-180.7,572,-277,876.3,-289,913c-4.7,4.7,-12.7,7,-24,7\ns-12,0,-12,0c-1.3,-3.3,-3.7,-11.7,-7,-25c-35.3,-125.3,-106.7,-373.3,-214,-744\nc-10,12,-21,25,-33,39s-32,39,-32,39c-6,-5.3,-15,-14,-27,-26s25,-30,25,-30\nc26.7,-32.7,52,-63,76,-91s52,-60,52,-60s208,722,208,722\nc56,-175.3,126.3,-397.3,211,-666c84.7,-268.7,153.8,-488.2,207.5,-658.5\nc53.7,-170.3,84.5,-266.8,92.5,-289.5z\nM" + (1001 + extraVinculum) + " " + hLinePad2 + "h400000v" + (40 + extraVinculum) + "h-400000z";
};
var sqrtSize3 = function sqrtSize32(extraVinculum, hLinePad2) {
  return "M424," + (2398 + extraVinculum + hLinePad2) + "\nc-1.3,-0.7,-38.5,-172,-111.5,-514c-73,-342,-109.8,-513.3,-110.5,-514\nc0,-2,-10.7,14.3,-32,49c-4.7,7.3,-9.8,15.7,-15.5,25c-5.7,9.3,-9.8,16,-12.5,20\ns-5,7,-5,7c-4,-3.3,-8.3,-7.7,-13,-13s-13,-13,-13,-13s76,-122,76,-122s77,-121,77,-121\ns209,968,209,968c0,-2,84.7,-361.7,254,-1079c169.3,-717.3,254.7,-1077.7,256,-1081\nl" + extraVinculum / 4.223 + " -" + extraVinculum + "c4,-6.7,10,-10,18,-10 H400000\nv" + (40 + extraVinculum) + "H1014.6\ns-87.3,378.7,-272.6,1166c-185.3,787.3,-279.3,1182.3,-282,1185\nc-2,6,-10,9,-24,9\nc-8,0,-12,-0.7,-12,-2z M" + (1001 + extraVinculum) + " " + hLinePad2 + "\nh400000v" + (40 + extraVinculum) + "h-400000z";
};
var sqrtSize4 = function sqrtSize42(extraVinculum, hLinePad2) {
  return "M473," + (2713 + extraVinculum + hLinePad2) + "\nc339.3,-1799.3,509.3,-2700,510,-2702 l" + extraVinculum / 5.298 + " -" + extraVinculum + "\nc3.3,-7.3,9.3,-11,18,-11 H400000v" + (40 + extraVinculum) + "H1017.7\ns-90.5,478,-276.2,1466c-185.7,988,-279.5,1483,-281.5,1485c-2,6,-10,9,-24,9\nc-8,0,-12,-0.7,-12,-2c0,-1.3,-5.3,-32,-16,-92c-50.7,-293.3,-119.7,-693.3,-207,-1200\nc0,-1.3,-5.3,8.7,-16,30c-10.7,21.3,-21.3,42.7,-32,64s-16,33,-16,33s-26,-26,-26,-26\ns76,-153,76,-153s77,-151,77,-151c0.7,0.7,35.7,202,105,604c67.3,400.7,102,602.7,104,\n606zM" + (1001 + extraVinculum) + " " + hLinePad2 + "h400000v" + (40 + extraVinculum) + "H1017.7z";
};
var phasePath = function phasePath2(y) {
  var x5 = y / 2;
  return "M400000 " + y + " H0 L" + x5 + " 0 l65 45 L145 " + (y - 80) + " H400000z";
};
var sqrtTall = function sqrtTall2(extraVinculum, hLinePad2, viewBoxHeight) {
  var vertSegment = viewBoxHeight - 54 - hLinePad2 - extraVinculum;
  return "M702 " + (extraVinculum + hLinePad2) + "H400000" + (40 + extraVinculum) + "\nH742v" + vertSegment + "l-4 4-4 4c-.667.7 -2 1.5-4 2.5s-4.167 1.833-6.5 2.5-5.5 1-9.5 1\nh-12l-28-84c-16.667-52-96.667 -294.333-240-727l-212 -643 -85 170\nc-4-3.333-8.333-7.667-13 -13l-13-13l77-155 77-156c66 199.333 139 419.667\n219 661 l218 661zM702 " + hLinePad2 + "H400000v" + (40 + extraVinculum) + "H742z";
};
var sqrtPath = function sqrtPath2(size, extraVinculum, viewBoxHeight) {
  extraVinculum = 1e3 * extraVinculum;
  var path2 = "";
  switch (size) {
    case "sqrtMain":
      path2 = sqrtMain(extraVinculum, hLinePad);
      break;
    case "sqrtSize1":
      path2 = sqrtSize1(extraVinculum, hLinePad);
      break;
    case "sqrtSize2":
      path2 = sqrtSize2(extraVinculum, hLinePad);
      break;
    case "sqrtSize3":
      path2 = sqrtSize3(extraVinculum, hLinePad);
      break;
    case "sqrtSize4":
      path2 = sqrtSize4(extraVinculum, hLinePad);
      break;
    case "sqrtTall":
      path2 = sqrtTall(extraVinculum, hLinePad, viewBoxHeight);
  }
  return path2;
};
var innerPath = function innerPath2(name, height) {
  switch (name) {
    case "\u239C":
      return "M291 0 H417 V" + height + " H291z M291 0 H417 V" + height + " H291z";
    case "\u2223":
      return "M145 0 H188 V" + height + " H145z M145 0 H188 V" + height + " H145z";
    case "\u2225":
      return "M145 0 H188 V" + height + " H145z M145 0 H188 V" + height + " H145z" + ("M367 0 H410 V" + height + " H367z M367 0 H410 V" + height + " H367z");
    case "\u239F":
      return "M457 0 H583 V" + height + " H457z M457 0 H583 V" + height + " H457z";
    case "\u23A2":
      return "M319 0 H403 V" + height + " H319z M319 0 H403 V" + height + " H319z";
    case "\u23A5":
      return "M263 0 H347 V" + height + " H263z M263 0 H347 V" + height + " H263z";
    case "\u23AA":
      return "M384 0 H504 V" + height + " H384z M384 0 H504 V" + height + " H384z";
    case "\u23D0":
      return "M312 0 H355 V" + height + " H312z M312 0 H355 V" + height + " H312z";
    case "\u2016":
      return "M257 0 H300 V" + height + " H257z M257 0 H300 V" + height + " H257z" + ("M478 0 H521 V" + height + " H478z M478 0 H521 V" + height + " H478z");
    default:
      return "";
  }
};
var path = {
  // The doubleleftarrow geometry is from glyph U+21D0 in the font KaTeX Main
  doubleleftarrow: "M262 157\nl10-10c34-36 62.7-77 86-123 3.3-8 5-13.3 5-16 0-5.3-6.7-8-20-8-7.3\n 0-12.2.5-14.5 1.5-2.3 1-4.8 4.5-7.5 10.5-49.3 97.3-121.7 169.3-217 216-28\n 14-57.3 25-88 33-6.7 2-11 3.8-13 5.5-2 1.7-3 4.2-3 7.5s1 5.8 3 7.5\nc2 1.7 6.3 3.5 13 5.5 68 17.3 128.2 47.8 180.5 91.5 52.3 43.7 93.8 96.2 124.5\n 157.5 9.3 8 15.3 12.3 18 13h6c12-.7 18-4 18-10 0-2-1.7-7-5-15-23.3-46-52-87\n-86-123l-10-10h399738v-40H218c328 0 0 0 0 0l-10-8c-26.7-20-65.7-43-117-69 2.7\n-2 6-3.7 10-5 36.7-16 72.3-37.3 107-64l10-8h399782v-40z\nm8 0v40h399730v-40zm0 194v40h399730v-40z",
  // doublerightarrow is from glyph U+21D2 in font KaTeX Main
  doublerightarrow: "M399738 392l\n-10 10c-34 36-62.7 77-86 123-3.3 8-5 13.3-5 16 0 5.3 6.7 8 20 8 7.3 0 12.2-.5\n 14.5-1.5 2.3-1 4.8-4.5 7.5-10.5 49.3-97.3 121.7-169.3 217-216 28-14 57.3-25 88\n-33 6.7-2 11-3.8 13-5.5 2-1.7 3-4.2 3-7.5s-1-5.8-3-7.5c-2-1.7-6.3-3.5-13-5.5-68\n-17.3-128.2-47.8-180.5-91.5-52.3-43.7-93.8-96.2-124.5-157.5-9.3-8-15.3-12.3-18\n-13h-6c-12 .7-18 4-18 10 0 2 1.7 7 5 15 23.3 46 52 87 86 123l10 10H0v40h399782\nc-328 0 0 0 0 0l10 8c26.7 20 65.7 43 117 69-2.7 2-6 3.7-10 5-36.7 16-72.3 37.3\n-107 64l-10 8H0v40zM0 157v40h399730v-40zm0 194v40h399730v-40z",
  // leftarrow is from glyph U+2190 in font KaTeX Main
  leftarrow: "M400000 241H110l3-3c68.7-52.7 113.7-120\n 135-202 4-14.7 6-23 6-25 0-7.3-7-11-21-11-8 0-13.2.8-15.5 2.5-2.3 1.7-4.2 5.8\n-5.5 12.5-1.3 4.7-2.7 10.3-4 17-12 48.7-34.8 92-68.5 130S65.3 228.3 18 247\nc-10 4-16 7.7-18 11 0 8.7 6 14.3 18 17 47.3 18.7 87.8 47 121.5 85S196 441.3 208\n 490c.7 2 1.3 5 2 9s1.2 6.7 1.5 8c.3 1.3 1 3.3 2 6s2.2 4.5 3.5 5.5c1.3 1 3.3\n 1.8 6 2.5s6 1 10 1c14 0 21-3.7 21-11 0-2-2-10.3-6-25-20-79.3-65-146.7-135-202\n l-3-3h399890zM100 241v40h399900v-40z",
  // overbrace is from glyphs U+23A9/23A8/23A7 in font KaTeX_Size4-Regular
  leftbrace: "M6 548l-6-6v-35l6-11c56-104 135.3-181.3 238-232 57.3-28.7 117\n-45 179-50h399577v120H403c-43.3 7-81 15-113 26-100.7 33-179.7 91-237 174-2.7\n 5-6 9-10 13-.7 1-7.3 1-20 1H6z",
  leftbraceunder: "M0 6l6-6h17c12.688 0 19.313.3 20 1 4 4 7.313 8.3 10 13\n 35.313 51.3 80.813 93.8 136.5 127.5 55.688 33.7 117.188 55.8 184.5 66.5.688\n 0 2 .3 4 1 18.688 2.7 76 4.3 172 5h399450v120H429l-6-1c-124.688-8-235-61.7\n-331-161C60.687 138.7 32.312 99.3 7 54L0 41V6z",
  // overgroup is from the MnSymbol package (public domain)
  leftgroup: "M400000 80\nH435C64 80 168.3 229.4 21 260c-5.9 1.2-18 0-18 0-2 0-3-1-3-3v-38C76 61 257 0\n 435 0h399565z",
  leftgroupunder: "M400000 262\nH435C64 262 168.3 112.6 21 82c-5.9-1.2-18 0-18 0-2 0-3 1-3 3v38c76 158 257 219\n 435 219h399565z",
  // Harpoons are from glyph U+21BD in font KaTeX Main
  leftharpoon: "M0 267c.7 5.3 3 10 7 14h399993v-40H93c3.3\n-3.3 10.2-9.5 20.5-18.5s17.8-15.8 22.5-20.5c50.7-52 88-110.3 112-175 4-11.3 5\n-18.3 3-21-1.3-4-7.3-6-18-6-8 0-13 .7-15 2s-4.7 6.7-8 16c-42 98.7-107.3 174.7\n-196 228-6.7 4.7-10.7 8-12 10-1.3 2-2 5.7-2 11zm100-26v40h399900v-40z",
  leftharpoonplus: "M0 267c.7 5.3 3 10 7 14h399993v-40H93c3.3-3.3 10.2-9.5\n 20.5-18.5s17.8-15.8 22.5-20.5c50.7-52 88-110.3 112-175 4-11.3 5-18.3 3-21-1.3\n-4-7.3-6-18-6-8 0-13 .7-15 2s-4.7 6.7-8 16c-42 98.7-107.3 174.7-196 228-6.7 4.7\n-10.7 8-12 10-1.3 2-2 5.7-2 11zm100-26v40h399900v-40zM0 435v40h400000v-40z\nm0 0v40h400000v-40z",
  leftharpoondown: "M7 241c-4 4-6.333 8.667-7 14 0 5.333.667 9 2 11s5.333\n 5.333 12 10c90.667 54 156 130 196 228 3.333 10.667 6.333 16.333 9 17 2 .667 5\n 1 9 1h5c10.667 0 16.667-2 18-6 2-2.667 1-9.667-3-21-32-87.333-82.667-157.667\n-152-211l-3-3h399907v-40zM93 281 H400000 v-40L7 241z",
  leftharpoondownplus: "M7 435c-4 4-6.3 8.7-7 14 0 5.3.7 9 2 11s5.3 5.3 12\n 10c90.7 54 156 130 196 228 3.3 10.7 6.3 16.3 9 17 2 .7 5 1 9 1h5c10.7 0 16.7\n-2 18-6 2-2.7 1-9.7-3-21-32-87.3-82.7-157.7-152-211l-3-3h399907v-40H7zm93 0\nv40h399900v-40zM0 241v40h399900v-40zm0 0v40h399900v-40z",
  // hook is from glyph U+21A9 in font KaTeX Main
  lefthook: "M400000 281 H103s-33-11.2-61-33.5S0 197.3 0 164s14.2-61.2 42.5\n-83.5C70.8 58.2 104 47 142 47 c16.7 0 25 6.7 25 20 0 12-8.7 18.7-26 20-40 3.3\n-68.7 15.7-86 37-10 12-15 25.3-15 40 0 22.7 9.8 40.7 29.5 54 19.7 13.3 43.5 21\n 71.5 23h399859zM103 281v-40h399897v40z",
  leftlinesegment: "M40 281 V428 H0 V94 H40 V241 H400000 v40z\nM40 281 V428 H0 V94 H40 V241 H400000 v40z",
  leftmapsto: "M40 281 V448H0V74H40V241H400000v40z\nM40 281 V448H0V74H40V241H400000v40z",
  // tofrom is from glyph U+21C4 in font KaTeX AMS Regular
  leftToFrom: "M0 147h400000v40H0zm0 214c68 40 115.7 95.7 143 167h22c15.3 0 23\n-.3 23-1 0-1.3-5.3-13.7-16-37-18-35.3-41.3-69-70-101l-7-8h399905v-40H95l7-8\nc28.7-32 52-65.7 70-101 10.7-23.3 16-35.7 16-37 0-.7-7.7-1-23-1h-22C115.7 265.3\n 68 321 0 361zm0-174v-40h399900v40zm100 154v40h399900v-40z",
  longequal: "M0 50 h400000 v40H0z m0 194h40000v40H0z\nM0 50 h400000 v40H0z m0 194h40000v40H0z",
  midbrace: "M200428 334\nc-100.7-8.3-195.3-44-280-108-55.3-42-101.7-93-139-153l-9-14c-2.7 4-5.7 8.7-9 14\n-53.3 86.7-123.7 153-211 199-66.7 36-137.3 56.3-212 62H0V214h199568c178.3-11.7\n 311.7-78.3 403-201 6-8 9.7-12 11-12 .7-.7 6.7-1 18-1s17.3.3 18 1c1.3 0 5 4 11\n 12 44.7 59.3 101.3 106.3 170 141s145.3 54.3 229 60h199572v120z",
  midbraceunder: "M199572 214\nc100.7 8.3 195.3 44 280 108 55.3 42 101.7 93 139 153l9 14c2.7-4 5.7-8.7 9-14\n 53.3-86.7 123.7-153 211-199 66.7-36 137.3-56.3 212-62h199568v120H200432c-178.3\n 11.7-311.7 78.3-403 201-6 8-9.7 12-11 12-.7.7-6.7 1-18 1s-17.3-.3-18-1c-1.3 0\n-5-4-11-12-44.7-59.3-101.3-106.3-170-141s-145.3-54.3-229-60H0V214z",
  oiintSize1: "M512.6 71.6c272.6 0 320.3 106.8 320.3 178.2 0 70.8-47.7 177.6\n-320.3 177.6S193.1 320.6 193.1 249.8c0-71.4 46.9-178.2 319.5-178.2z\nm368.1 178.2c0-86.4-60.9-215.4-368.1-215.4-306.4 0-367.3 129-367.3 215.4 0 85.8\n60.9 214.8 367.3 214.8 307.2 0 368.1-129 368.1-214.8z",
  oiintSize2: "M757.8 100.1c384.7 0 451.1 137.6 451.1 230 0 91.3-66.4 228.8\n-451.1 228.8-386.3 0-452.7-137.5-452.7-228.8 0-92.4 66.4-230 452.7-230z\nm502.4 230c0-111.2-82.4-277.2-502.4-277.2s-504 166-504 277.2\nc0 110 84 276 504 276s502.4-166 502.4-276z",
  oiiintSize1: "M681.4 71.6c408.9 0 480.5 106.8 480.5 178.2 0 70.8-71.6 177.6\n-480.5 177.6S202.1 320.6 202.1 249.8c0-71.4 70.5-178.2 479.3-178.2z\nm525.8 178.2c0-86.4-86.8-215.4-525.7-215.4-437.9 0-524.7 129-524.7 215.4 0\n85.8 86.8 214.8 524.7 214.8 438.9 0 525.7-129 525.7-214.8z",
  oiiintSize2: "M1021.2 53c603.6 0 707.8 165.8 707.8 277.2 0 110-104.2 275.8\n-707.8 275.8-606 0-710.2-165.8-710.2-275.8C311 218.8 415.2 53 1021.2 53z\nm770.4 277.1c0-131.2-126.4-327.6-770.5-327.6S248.4 198.9 248.4 330.1\nc0 130 128.8 326.4 772.7 326.4s770.5-196.4 770.5-326.4z",
  rightarrow: "M0 241v40h399891c-47.3 35.3-84 78-110 128\n-16.7 32-27.7 63.7-33 95 0 1.3-.2 2.7-.5 4-.3 1.3-.5 2.3-.5 3 0 7.3 6.7 11 20\n 11 8 0 13.2-.8 15.5-2.5 2.3-1.7 4.2-5.5 5.5-11.5 2-13.3 5.7-27 11-41 14.7-44.7\n 39-84.5 73-119.5s73.7-60.2 119-75.5c6-2 9-5.7 9-11s-3-9-9-11c-45.3-15.3-85\n-40.5-119-75.5s-58.3-74.8-73-119.5c-4.7-14-8.3-27.3-11-40-1.3-6.7-3.2-10.8-5.5\n-12.5-2.3-1.7-7.5-2.5-15.5-2.5-14 0-21 3.7-21 11 0 2 2 10.3 6 25 20.7 83.3 67\n 151.7 139 205zm0 0v40h399900v-40z",
  rightbrace: "M400000 542l\n-6 6h-17c-12.7 0-19.3-.3-20-1-4-4-7.3-8.3-10-13-35.3-51.3-80.8-93.8-136.5-127.5\ns-117.2-55.8-184.5-66.5c-.7 0-2-.3-4-1-18.7-2.7-76-4.3-172-5H0V214h399571l6 1\nc124.7 8 235 61.7 331 161 31.3 33.3 59.7 72.7 85 118l7 13v35z",
  rightbraceunder: "M399994 0l6 6v35l-6 11c-56 104-135.3 181.3-238 232-57.3\n 28.7-117 45-179 50H-300V214h399897c43.3-7 81-15 113-26 100.7-33 179.7-91 237\n-174 2.7-5 6-9 10-13 .7-1 7.3-1 20-1h17z",
  rightgroup: "M0 80h399565c371 0 266.7 149.4 414 180 5.9 1.2 18 0 18 0 2 0\n 3-1 3-3v-38c-76-158-257-219-435-219H0z",
  rightgroupunder: "M0 262h399565c371 0 266.7-149.4 414-180 5.9-1.2 18 0 18\n 0 2 0 3 1 3 3v38c-76 158-257 219-435 219H0z",
  rightharpoon: "M0 241v40h399993c4.7-4.7 7-9.3 7-14 0-9.3\n-3.7-15.3-11-18-92.7-56.7-159-133.7-199-231-3.3-9.3-6-14.7-8-16-2-1.3-7-2-15-2\n-10.7 0-16.7 2-18 6-2 2.7-1 9.7 3 21 15.3 42 36.7 81.8 64 119.5 27.3 37.7 58\n 69.2 92 94.5zm0 0v40h399900v-40z",
  rightharpoonplus: "M0 241v40h399993c4.7-4.7 7-9.3 7-14 0-9.3-3.7-15.3-11\n-18-92.7-56.7-159-133.7-199-231-3.3-9.3-6-14.7-8-16-2-1.3-7-2-15-2-10.7 0-16.7\n 2-18 6-2 2.7-1 9.7 3 21 15.3 42 36.7 81.8 64 119.5 27.3 37.7 58 69.2 92 94.5z\nm0 0v40h399900v-40z m100 194v40h399900v-40zm0 0v40h399900v-40z",
  rightharpoondown: "M399747 511c0 7.3 6.7 11 20 11 8 0 13-.8 15-2.5s4.7-6.8\n 8-15.5c40-94 99.3-166.3 178-217 13.3-8 20.3-12.3 21-13 5.3-3.3 8.5-5.8 9.5\n-7.5 1-1.7 1.5-5.2 1.5-10.5s-2.3-10.3-7-15H0v40h399908c-34 25.3-64.7 57-92 95\n-27.3 38-48.7 77.7-64 119-3.3 8.7-5 14-5 16zM0 241v40h399900v-40z",
  rightharpoondownplus: "M399747 705c0 7.3 6.7 11 20 11 8 0 13-.8\n 15-2.5s4.7-6.8 8-15.5c40-94 99.3-166.3 178-217 13.3-8 20.3-12.3 21-13 5.3-3.3\n 8.5-5.8 9.5-7.5 1-1.7 1.5-5.2 1.5-10.5s-2.3-10.3-7-15H0v40h399908c-34 25.3\n-64.7 57-92 95-27.3 38-48.7 77.7-64 119-3.3 8.7-5 14-5 16zM0 435v40h399900v-40z\nm0-194v40h400000v-40zm0 0v40h400000v-40z",
  righthook: "M399859 241c-764 0 0 0 0 0 40-3.3 68.7-15.7 86-37 10-12 15-25.3\n 15-40 0-22.7-9.8-40.7-29.5-54-19.7-13.3-43.5-21-71.5-23-17.3-1.3-26-8-26-20 0\n-13.3 8.7-20 26-20 38 0 71 11.2 99 33.5 0 0 7 5.6 21 16.7 14 11.2 21 33.5 21\n 66.8s-14 61.2-42 83.5c-28 22.3-61 33.5-99 33.5L0 241z M0 281v-40h399859v40z",
  rightlinesegment: "M399960 241 V94 h40 V428 h-40 V281 H0 v-40z\nM399960 241 V94 h40 V428 h-40 V281 H0 v-40z",
  rightToFrom: "M400000 167c-70.7-42-118-97.7-142-167h-23c-15.3 0-23 .3-23\n 1 0 1.3 5.3 13.7 16 37 18 35.3 41.3 69 70 101l7 8H0v40h399905l-7 8c-28.7 32\n-52 65.7-70 101-10.7 23.3-16 35.7-16 37 0 .7 7.7 1 23 1h23c24-69.3 71.3-125 142\n-167z M100 147v40h399900v-40zM0 341v40h399900v-40z",
  // twoheadleftarrow is from glyph U+219E in font KaTeX AMS Regular
  twoheadleftarrow: "M0 167c68 40\n 115.7 95.7 143 167h22c15.3 0 23-.3 23-1 0-1.3-5.3-13.7-16-37-18-35.3-41.3-69\n-70-101l-7-8h125l9 7c50.7 39.3 85 86 103 140h46c0-4.7-6.3-18.7-19-42-18-35.3\n-40-67.3-66-96l-9-9h399716v-40H284l9-9c26-28.7 48-60.7 66-96 12.7-23.333 19\n-37.333 19-42h-46c-18 54-52.3 100.7-103 140l-9 7H95l7-8c28.7-32 52-65.7 70-101\n 10.7-23.333 16-35.7 16-37 0-.7-7.7-1-23-1h-22C115.7 71.3 68 127 0 167z",
  twoheadrightarrow: "M400000 167\nc-68-40-115.7-95.7-143-167h-22c-15.3 0-23 .3-23 1 0 1.3 5.3 13.7 16 37 18 35.3\n 41.3 69 70 101l7 8h-125l-9-7c-50.7-39.3-85-86-103-140h-46c0 4.7 6.3 18.7 19 42\n 18 35.3 40 67.3 66 96l9 9H0v40h399716l-9 9c-26 28.7-48 60.7-66 96-12.7 23.333\n-19 37.333-19 42h46c18-54 52.3-100.7 103-140l9-7h125l-7 8c-28.7 32-52 65.7-70\n 101-10.7 23.333-16 35.7-16 37 0 .7 7.7 1 23 1h22c27.3-71.3 75-127 143-167z",
  // tilde1 is a modified version of a glyph from the MnSymbol package
  tilde1: "M200 55.538c-77 0-168 73.953-177 73.953-3 0-7\n-2.175-9-5.437L2 97c-1-2-2-4-2-6 0-4 2-7 5-9l20-12C116 12 171 0 207 0c86 0\n 114 68 191 68 78 0 168-68 177-68 4 0 7 2 9 5l12 19c1 2.175 2 4.35 2 6.525 0\n 4.35-2 7.613-5 9.788l-19 13.05c-92 63.077-116.937 75.308-183 76.128\n-68.267.847-113-73.952-191-73.952z",
  // ditto tilde2, tilde3, & tilde4
  tilde2: "M344 55.266c-142 0-300.638 81.316-311.5 86.418\n-8.01 3.762-22.5 10.91-23.5 5.562L1 120c-1-2-1-3-1-4 0-5 3-9 8-10l18.4-9C160.9\n 31.9 283 0 358 0c148 0 188 122 331 122s314-97 326-97c4 0 8 2 10 7l7 21.114\nc1 2.14 1 3.21 1 4.28 0 5.347-3 9.626-7 10.696l-22.3 12.622C852.6 158.372 751\n 181.476 676 181.476c-149 0-189-126.21-332-126.21z",
  tilde3: "M786 59C457 59 32 175.242 13 175.242c-6 0-10-3.457\n-11-10.37L.15 138c-1-7 3-12 10-13l19.2-6.4C378.4 40.7 634.3 0 804.3 0c337 0\n 411.8 157 746.8 157 328 0 754-112 773-112 5 0 10 3 11 9l1 14.075c1 8.066-.697\n 16.595-6.697 17.492l-21.052 7.31c-367.9 98.146-609.15 122.696-778.15 122.696\n -338 0-409-156.573-744-156.573z",
  tilde4: "M786 58C457 58 32 177.487 13 177.487c-6 0-10-3.345\n-11-10.035L.15 143c-1-7 3-12 10-13l22-6.7C381.2 35 637.15 0 807.15 0c337 0 409\n 177 744 177 328 0 754-127 773-127 5 0 10 3 11 9l1 14.794c1 7.805-3 13.38-9\n 14.495l-20.7 5.574c-366.85 99.79-607.3 139.372-776.3 139.372-338 0-409\n -175.236-744-175.236z",
  // vec is from glyph U+20D7 in font KaTeX Main
  vec: "M377 20c0-5.333 1.833-10 5.5-14S391 0 397 0c4.667 0 8.667 1.667 12 5\n3.333 2.667 6.667 9 10 19 6.667 24.667 20.333 43.667 41 57 7.333 4.667 11\n10.667 11 18 0 6-1 10-3 12s-6.667 5-14 9c-28.667 14.667-53.667 35.667-75 63\n-1.333 1.333-3.167 3.5-5.5 6.5s-4 4.833-5 5.5c-1 .667-2.5 1.333-4.5 2s-4.333 1\n-7 1c-4.667 0-9.167-1.833-13.5-5.5S337 184 337 178c0-12.667 15.667-32.333 47-59\nH213l-171-1c-8.667-6-13-12.333-13-19 0-4.667 4.333-11.333 13-20h359\nc-16-25.333-24-45-24-59z",
  // widehat1 is a modified version of a glyph from the MnSymbol package
  widehat1: "M529 0h5l519 115c5 1 9 5 9 10 0 1-1 2-1 3l-4 22\nc-1 5-5 9-11 9h-2L532 67 19 159h-2c-5 0-9-4-11-9l-5-22c-1-6 2-12 8-13z",
  // ditto widehat2, widehat3, & widehat4
  widehat2: "M1181 0h2l1171 176c6 0 10 5 10 11l-2 23c-1 6-5 10\n-11 10h-1L1182 67 15 220h-1c-6 0-10-4-11-10l-2-23c-1-6 4-11 10-11z",
  widehat3: "M1181 0h2l1171 236c6 0 10 5 10 11l-2 23c-1 6-5 10\n-11 10h-1L1182 67 15 280h-1c-6 0-10-4-11-10l-2-23c-1-6 4-11 10-11z",
  widehat4: "M1181 0h2l1171 296c6 0 10 5 10 11l-2 23c-1 6-5 10\n-11 10h-1L1182 67 15 340h-1c-6 0-10-4-11-10l-2-23c-1-6 4-11 10-11z",
  // widecheck paths are all inverted versions of widehat
  widecheck1: "M529,159h5l519,-115c5,-1,9,-5,9,-10c0,-1,-1,-2,-1,-3l-4,-22c-1,\n-5,-5,-9,-11,-9h-2l-512,92l-513,-92h-2c-5,0,-9,4,-11,9l-5,22c-1,6,2,12,8,13z",
  widecheck2: "M1181,220h2l1171,-176c6,0,10,-5,10,-11l-2,-23c-1,-6,-5,-10,\n-11,-10h-1l-1168,153l-1167,-153h-1c-6,0,-10,4,-11,10l-2,23c-1,6,4,11,10,11z",
  widecheck3: "M1181,280h2l1171,-236c6,0,10,-5,10,-11l-2,-23c-1,-6,-5,-10,\n-11,-10h-1l-1168,213l-1167,-213h-1c-6,0,-10,4,-11,10l-2,23c-1,6,4,11,10,11z",
  widecheck4: "M1181,340h2l1171,-296c6,0,10,-5,10,-11l-2,-23c-1,-6,-5,-10,\n-11,-10h-1l-1168,273l-1167,-273h-1c-6,0,-10,4,-11,10l-2,23c-1,6,4,11,10,11z",
  // The next ten paths support reaction arrows from the mhchem package.
  // Arrows for \ce{<-->} are offset from xAxis by 0.22ex, per mhchem in LaTeX
  // baraboveleftarrow is mostly from glyph U+2190 in font KaTeX Main
  baraboveleftarrow: "M400000 620h-399890l3 -3c68.7 -52.7 113.7 -120 135 -202\nc4 -14.7 6 -23 6 -25c0 -7.3 -7 -11 -21 -11c-8 0 -13.2 0.8 -15.5 2.5\nc-2.3 1.7 -4.2 5.8 -5.5 12.5c-1.3 4.7 -2.7 10.3 -4 17c-12 48.7 -34.8 92 -68.5 130\ns-74.2 66.3 -121.5 85c-10 4 -16 7.7 -18 11c0 8.7 6 14.3 18 17c47.3 18.7 87.8 47\n121.5 85s56.5 81.3 68.5 130c0.7 2 1.3 5 2 9s1.2 6.7 1.5 8c0.3 1.3 1 3.3 2 6\ns2.2 4.5 3.5 5.5c1.3 1 3.3 1.8 6 2.5s6 1 10 1c14 0 21 -3.7 21 -11\nc0 -2 -2 -10.3 -6 -25c-20 -79.3 -65 -146.7 -135 -202l-3 -3h399890z\nM100 620v40h399900v-40z M0 241v40h399900v-40zM0 241v40h399900v-40z",
  // rightarrowabovebar is mostly from glyph U+2192, KaTeX Main
  rightarrowabovebar: "M0 241v40h399891c-47.3 35.3-84 78-110 128-16.7 32\n-27.7 63.7-33 95 0 1.3-.2 2.7-.5 4-.3 1.3-.5 2.3-.5 3 0 7.3 6.7 11 20 11 8 0\n13.2-.8 15.5-2.5 2.3-1.7 4.2-5.5 5.5-11.5 2-13.3 5.7-27 11-41 14.7-44.7 39\n-84.5 73-119.5s73.7-60.2 119-75.5c6-2 9-5.7 9-11s-3-9-9-11c-45.3-15.3-85-40.5\n-119-75.5s-58.3-74.8-73-119.5c-4.7-14-8.3-27.3-11-40-1.3-6.7-3.2-10.8-5.5\n-12.5-2.3-1.7-7.5-2.5-15.5-2.5-14 0-21 3.7-21 11 0 2 2 10.3 6 25 20.7 83.3 67\n151.7 139 205zm96 379h399894v40H0zm0 0h399904v40H0z",
  // The short left harpoon has 0.5em (i.e. 500 units) kern on the left end.
  // Ref from mhchem.sty: \rlap{\raisebox{-.22ex}{$\kern0.5em
  baraboveshortleftharpoon: "M507,435c-4,4,-6.3,8.7,-7,14c0,5.3,0.7,9,2,11\nc1.3,2,5.3,5.3,12,10c90.7,54,156,130,196,228c3.3,10.7,6.3,16.3,9,17\nc2,0.7,5,1,9,1c0,0,5,0,5,0c10.7,0,16.7,-2,18,-6c2,-2.7,1,-9.7,-3,-21\nc-32,-87.3,-82.7,-157.7,-152,-211c0,0,-3,-3,-3,-3l399351,0l0,-40\nc-398570,0,-399437,0,-399437,0z M593 435 v40 H399500 v-40z\nM0 281 v-40 H399908 v40z M0 281 v-40 H399908 v40z",
  rightharpoonaboveshortbar: "M0,241 l0,40c399126,0,399993,0,399993,0\nc4.7,-4.7,7,-9.3,7,-14c0,-9.3,-3.7,-15.3,-11,-18c-92.7,-56.7,-159,-133.7,-199,\n-231c-3.3,-9.3,-6,-14.7,-8,-16c-2,-1.3,-7,-2,-15,-2c-10.7,0,-16.7,2,-18,6\nc-2,2.7,-1,9.7,3,21c15.3,42,36.7,81.8,64,119.5c27.3,37.7,58,69.2,92,94.5z\nM0 241 v40 H399908 v-40z M0 475 v-40 H399500 v40z M0 475 v-40 H399500 v40z",
  shortbaraboveleftharpoon: "M7,435c-4,4,-6.3,8.7,-7,14c0,5.3,0.7,9,2,11\nc1.3,2,5.3,5.3,12,10c90.7,54,156,130,196,228c3.3,10.7,6.3,16.3,9,17c2,0.7,5,1,9,\n1c0,0,5,0,5,0c10.7,0,16.7,-2,18,-6c2,-2.7,1,-9.7,-3,-21c-32,-87.3,-82.7,-157.7,\n-152,-211c0,0,-3,-3,-3,-3l399907,0l0,-40c-399126,0,-399993,0,-399993,0z\nM93 435 v40 H400000 v-40z M500 241 v40 H400000 v-40z M500 241 v40 H400000 v-40z",
  shortrightharpoonabovebar: "M53,241l0,40c398570,0,399437,0,399437,0\nc4.7,-4.7,7,-9.3,7,-14c0,-9.3,-3.7,-15.3,-11,-18c-92.7,-56.7,-159,-133.7,-199,\n-231c-3.3,-9.3,-6,-14.7,-8,-16c-2,-1.3,-7,-2,-15,-2c-10.7,0,-16.7,2,-18,6\nc-2,2.7,-1,9.7,3,21c15.3,42,36.7,81.8,64,119.5c27.3,37.7,58,69.2,92,94.5z\nM500 241 v40 H399408 v-40z M500 435 v40 H400000 v-40z"
};
var tallDelim = function tallDelim2(label, midHeight) {
  switch (label) {
    case "lbrack":
      return "M403 1759 V84 H666 V0 H319 V1759 v" + midHeight + " v1759 h347 v-84\nH403z M403 1759 V0 H319 V1759 v" + midHeight + " v1759 h84z";
    case "rbrack":
      return "M347 1759 V0 H0 V84 H263 V1759 v" + midHeight + " v1759 H0 v84 H347z\nM347 1759 V0 H263 V1759 v" + midHeight + " v1759 h84z";
    case "vert":
      return "M145 15 v585 v" + midHeight + " v585 c2.667,10,9.667,15,21,15\nc10,0,16.667,-5,20,-15 v-585 v" + -midHeight + " v-585 c-2.667,-10,-9.667,-15,-21,-15\nc-10,0,-16.667,5,-20,15z M188 15 H145 v585 v" + midHeight + " v585 h43z";
    case "doublevert":
      return "M145 15 v585 v" + midHeight + " v585 c2.667,10,9.667,15,21,15\nc10,0,16.667,-5,20,-15 v-585 v" + -midHeight + " v-585 c-2.667,-10,-9.667,-15,-21,-15\nc-10,0,-16.667,5,-20,15z M188 15 H145 v585 v" + midHeight + " v585 h43z\nM367 15 v585 v" + midHeight + " v585 c2.667,10,9.667,15,21,15\nc10,0,16.667,-5,20,-15 v-585 v" + -midHeight + " v-585 c-2.667,-10,-9.667,-15,-21,-15\nc-10,0,-16.667,5,-20,15z M410 15 H367 v585 v" + midHeight + " v585 h43z";
    case "lfloor":
      return "M319 602 V0 H403 V602 v" + midHeight + " v1715 h263 v84 H319z\nMM319 602 V0 H403 V602 v" + midHeight + " v1715 H319z";
    case "rfloor":
      return "M319 602 V0 H403 V602 v" + midHeight + " v1799 H0 v-84 H319z\nMM319 602 V0 H403 V602 v" + midHeight + " v1715 H319z";
    case "lceil":
      return "M403 1759 V84 H666 V0 H319 V1759 v" + midHeight + " v602 h84z\nM403 1759 V0 H319 V1759 v" + midHeight + " v602 h84z";
    case "rceil":
      return "M347 1759 V0 H0 V84 H263 V1759 v" + midHeight + " v602 h84z\nM347 1759 V0 h-84 V1759 v" + midHeight + " v602 h84z";
    case "lparen":
      return "M863,9c0,-2,-2,-5,-6,-9c0,0,-17,0,-17,0c-12.7,0,-19.3,0.3,-20,1\nc-5.3,5.3,-10.3,11,-15,17c-242.7,294.7,-395.3,682,-458,1162c-21.3,163.3,-33.3,349,\n-36,557 l0," + (midHeight + 84) + "c0.2,6,0,26,0,60c2,159.3,10,310.7,24,454c53.3,528,210,\n949.7,470,1265c4.7,6,9.7,11.7,15,17c0.7,0.7,7,1,19,1c0,0,18,0,18,0c4,-4,6,-7,6,-9\nc0,-2.7,-3.3,-8.7,-10,-18c-135.3,-192.7,-235.5,-414.3,-300.5,-665c-65,-250.7,-102.5,\n-544.7,-112.5,-882c-2,-104,-3,-167,-3,-189\nl0,-" + (midHeight + 92) + "c0,-162.7,5.7,-314,17,-454c20.7,-272,63.7,-513,129,-723c65.3,\n-210,155.3,-396.3,270,-559c6.7,-9.3,10,-15.3,10,-18z";
    case "rparen":
      return "M76,0c-16.7,0,-25,3,-25,9c0,2,2,6.3,6,13c21.3,28.7,42.3,60.3,\n63,95c96.7,156.7,172.8,332.5,228.5,527.5c55.7,195,92.8,416.5,111.5,664.5\nc11.3,139.3,17,290.7,17,454c0,28,1.7,43,3.3,45l0," + (midHeight + 9) + "\nc-3,4,-3.3,16.7,-3.3,38c0,162,-5.7,313.7,-17,455c-18.7,248,-55.8,469.3,-111.5,664\nc-55.7,194.7,-131.8,370.3,-228.5,527c-20.7,34.7,-41.7,66.3,-63,95c-2,3.3,-4,7,-6,11\nc0,7.3,5.7,11,17,11c0,0,11,0,11,0c9.3,0,14.3,-0.3,15,-1c5.3,-5.3,10.3,-11,15,-17\nc242.7,-294.7,395.3,-681.7,458,-1161c21.3,-164.7,33.3,-350.7,36,-558\nl0,-" + (midHeight + 144) + "c-2,-159.3,-10,-310.7,-24,-454c-53.3,-528,-210,-949.7,\n-470,-1265c-4.7,-6,-9.7,-11.7,-15,-17c-0.7,-0.7,-6.7,-1,-18,-1z";
    default:
      throw new Error("Unknown stretchy delimiter.");
  }
};
var DocumentFragment = class {
  // HtmlDomNode
  // Never used; needed for satisfying interface.
  constructor(children) {
    this.children = void 0;
    this.classes = void 0;
    this.height = void 0;
    this.depth = void 0;
    this.maxFontSize = void 0;
    this.style = void 0;
    this.children = children;
    this.classes = [];
    this.height = 0;
    this.depth = 0;
    this.maxFontSize = 0;
    this.style = {};
  }
  hasClass(className) {
    return utils.contains(this.classes, className);
  }
  /** Convert the fragment into a node. */
  toNode() {
    var frag = document.createDocumentFragment();
    for (var i = 0; i < this.children.length; i++) {
      frag.appendChild(this.children[i].toNode());
    }
    return frag;
  }
  /** Convert the fragment into HTML markup. */
  toMarkup() {
    var markup = "";
    for (var i = 0; i < this.children.length; i++) {
      markup += this.children[i].toMarkup();
    }
    return markup;
  }
  /**
   * Converts the math node into a string, similar to innerText. Applies to
   * MathDomNode's only.
   */
  toText() {
    var toText = (child) => child.toText();
    return this.children.map(toText).join("");
  }
};
var fontMetricsData = {
  "AMS-Regular": {
    "32": [0, 0, 0, 0, 0.25],
    "65": [0, 0.68889, 0, 0, 0.72222],
    "66": [0, 0.68889, 0, 0, 0.66667],
    "67": [0, 0.68889, 0, 0, 0.72222],
    "68": [0, 0.68889, 0, 0, 0.72222],
    "69": [0, 0.68889, 0, 0, 0.66667],
    "70": [0, 0.68889, 0, 0, 0.61111],
    "71": [0, 0.68889, 0, 0, 0.77778],
    "72": [0, 0.68889, 0, 0, 0.77778],
    "73": [0, 0.68889, 0, 0, 0.38889],
    "74": [0.16667, 0.68889, 0, 0, 0.5],
    "75": [0, 0.68889, 0, 0, 0.77778],
    "76": [0, 0.68889, 0, 0, 0.66667],
    "77": [0, 0.68889, 0, 0, 0.94445],
    "78": [0, 0.68889, 0, 0, 0.72222],
    "79": [0.16667, 0.68889, 0, 0, 0.77778],
    "80": [0, 0.68889, 0, 0, 0.61111],
    "81": [0.16667, 0.68889, 0, 0, 0.77778],
    "82": [0, 0.68889, 0, 0, 0.72222],
    "83": [0, 0.68889, 0, 0, 0.55556],
    "84": [0, 0.68889, 0, 0, 0.66667],
    "85": [0, 0.68889, 0, 0, 0.72222],
    "86": [0, 0.68889, 0, 0, 0.72222],
    "87": [0, 0.68889, 0, 0, 1],
    "88": [0, 0.68889, 0, 0, 0.72222],
    "89": [0, 0.68889, 0, 0, 0.72222],
    "90": [0, 0.68889, 0, 0, 0.66667],
    "107": [0, 0.68889, 0, 0, 0.55556],
    "160": [0, 0, 0, 0, 0.25],
    "165": [0, 0.675, 0.025, 0, 0.75],
    "174": [0.15559, 0.69224, 0, 0, 0.94666],
    "240": [0, 0.68889, 0, 0, 0.55556],
    "295": [0, 0.68889, 0, 0, 0.54028],
    "710": [0, 0.825, 0, 0, 2.33334],
    "732": [0, 0.9, 0, 0, 2.33334],
    "770": [0, 0.825, 0, 0, 2.33334],
    "771": [0, 0.9, 0, 0, 2.33334],
    "989": [0.08167, 0.58167, 0, 0, 0.77778],
    "1008": [0, 0.43056, 0.04028, 0, 0.66667],
    "8245": [0, 0.54986, 0, 0, 0.275],
    "8463": [0, 0.68889, 0, 0, 0.54028],
    "8487": [0, 0.68889, 0, 0, 0.72222],
    "8498": [0, 0.68889, 0, 0, 0.55556],
    "8502": [0, 0.68889, 0, 0, 0.66667],
    "8503": [0, 0.68889, 0, 0, 0.44445],
    "8504": [0, 0.68889, 0, 0, 0.66667],
    "8513": [0, 0.68889, 0, 0, 0.63889],
    "8592": [-0.03598, 0.46402, 0, 0, 0.5],
    "8594": [-0.03598, 0.46402, 0, 0, 0.5],
    "8602": [-0.13313, 0.36687, 0, 0, 1],
    "8603": [-0.13313, 0.36687, 0, 0, 1],
    "8606": [0.01354, 0.52239, 0, 0, 1],
    "8608": [0.01354, 0.52239, 0, 0, 1],
    "8610": [0.01354, 0.52239, 0, 0, 1.11111],
    "8611": [0.01354, 0.52239, 0, 0, 1.11111],
    "8619": [0, 0.54986, 0, 0, 1],
    "8620": [0, 0.54986, 0, 0, 1],
    "8621": [-0.13313, 0.37788, 0, 0, 1.38889],
    "8622": [-0.13313, 0.36687, 0, 0, 1],
    "8624": [0, 0.69224, 0, 0, 0.5],
    "8625": [0, 0.69224, 0, 0, 0.5],
    "8630": [0, 0.43056, 0, 0, 1],
    "8631": [0, 0.43056, 0, 0, 1],
    "8634": [0.08198, 0.58198, 0, 0, 0.77778],
    "8635": [0.08198, 0.58198, 0, 0, 0.77778],
    "8638": [0.19444, 0.69224, 0, 0, 0.41667],
    "8639": [0.19444, 0.69224, 0, 0, 0.41667],
    "8642": [0.19444, 0.69224, 0, 0, 0.41667],
    "8643": [0.19444, 0.69224, 0, 0, 0.41667],
    "8644": [0.1808, 0.675, 0, 0, 1],
    "8646": [0.1808, 0.675, 0, 0, 1],
    "8647": [0.1808, 0.675, 0, 0, 1],
    "8648": [0.19444, 0.69224, 0, 0, 0.83334],
    "8649": [0.1808, 0.675, 0, 0, 1],
    "8650": [0.19444, 0.69224, 0, 0, 0.83334],
    "8651": [0.01354, 0.52239, 0, 0, 1],
    "8652": [0.01354, 0.52239, 0, 0, 1],
    "8653": [-0.13313, 0.36687, 0, 0, 1],
    "8654": [-0.13313, 0.36687, 0, 0, 1],
    "8655": [-0.13313, 0.36687, 0, 0, 1],
    "8666": [0.13667, 0.63667, 0, 0, 1],
    "8667": [0.13667, 0.63667, 0, 0, 1],
    "8669": [-0.13313, 0.37788, 0, 0, 1],
    "8672": [-0.064, 0.437, 0, 0, 1.334],
    "8674": [-0.064, 0.437, 0, 0, 1.334],
    "8705": [0, 0.825, 0, 0, 0.5],
    "8708": [0, 0.68889, 0, 0, 0.55556],
    "8709": [0.08167, 0.58167, 0, 0, 0.77778],
    "8717": [0, 0.43056, 0, 0, 0.42917],
    "8722": [-0.03598, 0.46402, 0, 0, 0.5],
    "8724": [0.08198, 0.69224, 0, 0, 0.77778],
    "8726": [0.08167, 0.58167, 0, 0, 0.77778],
    "8733": [0, 0.69224, 0, 0, 0.77778],
    "8736": [0, 0.69224, 0, 0, 0.72222],
    "8737": [0, 0.69224, 0, 0, 0.72222],
    "8738": [0.03517, 0.52239, 0, 0, 0.72222],
    "8739": [0.08167, 0.58167, 0, 0, 0.22222],
    "8740": [0.25142, 0.74111, 0, 0, 0.27778],
    "8741": [0.08167, 0.58167, 0, 0, 0.38889],
    "8742": [0.25142, 0.74111, 0, 0, 0.5],
    "8756": [0, 0.69224, 0, 0, 0.66667],
    "8757": [0, 0.69224, 0, 0, 0.66667],
    "8764": [-0.13313, 0.36687, 0, 0, 0.77778],
    "8765": [-0.13313, 0.37788, 0, 0, 0.77778],
    "8769": [-0.13313, 0.36687, 0, 0, 0.77778],
    "8770": [-0.03625, 0.46375, 0, 0, 0.77778],
    "8774": [0.30274, 0.79383, 0, 0, 0.77778],
    "8776": [-0.01688, 0.48312, 0, 0, 0.77778],
    "8778": [0.08167, 0.58167, 0, 0, 0.77778],
    "8782": [0.06062, 0.54986, 0, 0, 0.77778],
    "8783": [0.06062, 0.54986, 0, 0, 0.77778],
    "8785": [0.08198, 0.58198, 0, 0, 0.77778],
    "8786": [0.08198, 0.58198, 0, 0, 0.77778],
    "8787": [0.08198, 0.58198, 0, 0, 0.77778],
    "8790": [0, 0.69224, 0, 0, 0.77778],
    "8791": [0.22958, 0.72958, 0, 0, 0.77778],
    "8796": [0.08198, 0.91667, 0, 0, 0.77778],
    "8806": [0.25583, 0.75583, 0, 0, 0.77778],
    "8807": [0.25583, 0.75583, 0, 0, 0.77778],
    "8808": [0.25142, 0.75726, 0, 0, 0.77778],
    "8809": [0.25142, 0.75726, 0, 0, 0.77778],
    "8812": [0.25583, 0.75583, 0, 0, 0.5],
    "8814": [0.20576, 0.70576, 0, 0, 0.77778],
    "8815": [0.20576, 0.70576, 0, 0, 0.77778],
    "8816": [0.30274, 0.79383, 0, 0, 0.77778],
    "8817": [0.30274, 0.79383, 0, 0, 0.77778],
    "8818": [0.22958, 0.72958, 0, 0, 0.77778],
    "8819": [0.22958, 0.72958, 0, 0, 0.77778],
    "8822": [0.1808, 0.675, 0, 0, 0.77778],
    "8823": [0.1808, 0.675, 0, 0, 0.77778],
    "8828": [0.13667, 0.63667, 0, 0, 0.77778],
    "8829": [0.13667, 0.63667, 0, 0, 0.77778],
    "8830": [0.22958, 0.72958, 0, 0, 0.77778],
    "8831": [0.22958, 0.72958, 0, 0, 0.77778],
    "8832": [0.20576, 0.70576, 0, 0, 0.77778],
    "8833": [0.20576, 0.70576, 0, 0, 0.77778],
    "8840": [0.30274, 0.79383, 0, 0, 0.77778],
    "8841": [0.30274, 0.79383, 0, 0, 0.77778],
    "8842": [0.13597, 0.63597, 0, 0, 0.77778],
    "8843": [0.13597, 0.63597, 0, 0, 0.77778],
    "8847": [0.03517, 0.54986, 0, 0, 0.77778],
    "8848": [0.03517, 0.54986, 0, 0, 0.77778],
    "8858": [0.08198, 0.58198, 0, 0, 0.77778],
    "8859": [0.08198, 0.58198, 0, 0, 0.77778],
    "8861": [0.08198, 0.58198, 0, 0, 0.77778],
    "8862": [0, 0.675, 0, 0, 0.77778],
    "8863": [0, 0.675, 0, 0, 0.77778],
    "8864": [0, 0.675, 0, 0, 0.77778],
    "8865": [0, 0.675, 0, 0, 0.77778],
    "8872": [0, 0.69224, 0, 0, 0.61111],
    "8873": [0, 0.69224, 0, 0, 0.72222],
    "8874": [0, 0.69224, 0, 0, 0.88889],
    "8876": [0, 0.68889, 0, 0, 0.61111],
    "8877": [0, 0.68889, 0, 0, 0.61111],
    "8878": [0, 0.68889, 0, 0, 0.72222],
    "8879": [0, 0.68889, 0, 0, 0.72222],
    "8882": [0.03517, 0.54986, 0, 0, 0.77778],
    "8883": [0.03517, 0.54986, 0, 0, 0.77778],
    "8884": [0.13667, 0.63667, 0, 0, 0.77778],
    "8885": [0.13667, 0.63667, 0, 0, 0.77778],
    "8888": [0, 0.54986, 0, 0, 1.11111],
    "8890": [0.19444, 0.43056, 0, 0, 0.55556],
    "8891": [0.19444, 0.69224, 0, 0, 0.61111],
    "8892": [0.19444, 0.69224, 0, 0, 0.61111],
    "8901": [0, 0.54986, 0, 0, 0.27778],
    "8903": [0.08167, 0.58167, 0, 0, 0.77778],
    "8905": [0.08167, 0.58167, 0, 0, 0.77778],
    "8906": [0.08167, 0.58167, 0, 0, 0.77778],
    "8907": [0, 0.69224, 0, 0, 0.77778],
    "8908": [0, 0.69224, 0, 0, 0.77778],
    "8909": [-0.03598, 0.46402, 0, 0, 0.77778],
    "8910": [0, 0.54986, 0, 0, 0.76042],
    "8911": [0, 0.54986, 0, 0, 0.76042],
    "8912": [0.03517, 0.54986, 0, 0, 0.77778],
    "8913": [0.03517, 0.54986, 0, 0, 0.77778],
    "8914": [0, 0.54986, 0, 0, 0.66667],
    "8915": [0, 0.54986, 0, 0, 0.66667],
    "8916": [0, 0.69224, 0, 0, 0.66667],
    "8918": [0.0391, 0.5391, 0, 0, 0.77778],
    "8919": [0.0391, 0.5391, 0, 0, 0.77778],
    "8920": [0.03517, 0.54986, 0, 0, 1.33334],
    "8921": [0.03517, 0.54986, 0, 0, 1.33334],
    "8922": [0.38569, 0.88569, 0, 0, 0.77778],
    "8923": [0.38569, 0.88569, 0, 0, 0.77778],
    "8926": [0.13667, 0.63667, 0, 0, 0.77778],
    "8927": [0.13667, 0.63667, 0, 0, 0.77778],
    "8928": [0.30274, 0.79383, 0, 0, 0.77778],
    "8929": [0.30274, 0.79383, 0, 0, 0.77778],
    "8934": [0.23222, 0.74111, 0, 0, 0.77778],
    "8935": [0.23222, 0.74111, 0, 0, 0.77778],
    "8936": [0.23222, 0.74111, 0, 0, 0.77778],
    "8937": [0.23222, 0.74111, 0, 0, 0.77778],
    "8938": [0.20576, 0.70576, 0, 0, 0.77778],
    "8939": [0.20576, 0.70576, 0, 0, 0.77778],
    "8940": [0.30274, 0.79383, 0, 0, 0.77778],
    "8941": [0.30274, 0.79383, 0, 0, 0.77778],
    "8994": [0.19444, 0.69224, 0, 0, 0.77778],
    "8995": [0.19444, 0.69224, 0, 0, 0.77778],
    "9416": [0.15559, 0.69224, 0, 0, 0.90222],
    "9484": [0, 0.69224, 0, 0, 0.5],
    "9488": [0, 0.69224, 0, 0, 0.5],
    "9492": [0, 0.37788, 0, 0, 0.5],
    "9496": [0, 0.37788, 0, 0, 0.5],
    "9585": [0.19444, 0.68889, 0, 0, 0.88889],
    "9586": [0.19444, 0.74111, 0, 0, 0.88889],
    "9632": [0, 0.675, 0, 0, 0.77778],
    "9633": [0, 0.675, 0, 0, 0.77778],
    "9650": [0, 0.54986, 0, 0, 0.72222],
    "9651": [0, 0.54986, 0, 0, 0.72222],
    "9654": [0.03517, 0.54986, 0, 0, 0.77778],
    "9660": [0, 0.54986, 0, 0, 0.72222],
    "9661": [0, 0.54986, 0, 0, 0.72222],
    "9664": [0.03517, 0.54986, 0, 0, 0.77778],
    "9674": [0.11111, 0.69224, 0, 0, 0.66667],
    "9733": [0.19444, 0.69224, 0, 0, 0.94445],
    "10003": [0, 0.69224, 0, 0, 0.83334],
    "10016": [0, 0.69224, 0, 0, 0.83334],
    "10731": [0.11111, 0.69224, 0, 0, 0.66667],
    "10846": [0.19444, 0.75583, 0, 0, 0.61111],
    "10877": [0.13667, 0.63667, 0, 0, 0.77778],
    "10878": [0.13667, 0.63667, 0, 0, 0.77778],
    "10885": [0.25583, 0.75583, 0, 0, 0.77778],
    "10886": [0.25583, 0.75583, 0, 0, 0.77778],
    "10887": [0.13597, 0.63597, 0, 0, 0.77778],
    "10888": [0.13597, 0.63597, 0, 0, 0.77778],
    "10889": [0.26167, 0.75726, 0, 0, 0.77778],
    "10890": [0.26167, 0.75726, 0, 0, 0.77778],
    "10891": [0.48256, 0.98256, 0, 0, 0.77778],
    "10892": [0.48256, 0.98256, 0, 0, 0.77778],
    "10901": [0.13667, 0.63667, 0, 0, 0.77778],
    "10902": [0.13667, 0.63667, 0, 0, 0.77778],
    "10933": [0.25142, 0.75726, 0, 0, 0.77778],
    "10934": [0.25142, 0.75726, 0, 0, 0.77778],
    "10935": [0.26167, 0.75726, 0, 0, 0.77778],
    "10936": [0.26167, 0.75726, 0, 0, 0.77778],
    "10937": [0.26167, 0.75726, 0, 0, 0.77778],
    "10938": [0.26167, 0.75726, 0, 0, 0.77778],
    "10949": [0.25583, 0.75583, 0, 0, 0.77778],
    "10950": [0.25583, 0.75583, 0, 0, 0.77778],
    "10955": [0.28481, 0.79383, 0, 0, 0.77778],
    "10956": [0.28481, 0.79383, 0, 0, 0.77778],
    "57350": [0.08167, 0.58167, 0, 0, 0.22222],
    "57351": [0.08167, 0.58167, 0, 0, 0.38889],
    "57352": [0.08167, 0.58167, 0, 0, 0.77778],
    "57353": [0, 0.43056, 0.04028, 0, 0.66667],
    "57356": [0.25142, 0.75726, 0, 0, 0.77778],
    "57357": [0.25142, 0.75726, 0, 0, 0.77778],
    "57358": [0.41951, 0.91951, 0, 0, 0.77778],
    "57359": [0.30274, 0.79383, 0, 0, 0.77778],
    "57360": [0.30274, 0.79383, 0, 0, 0.77778],
    "57361": [0.41951, 0.91951, 0, 0, 0.77778],
    "57366": [0.25142, 0.75726, 0, 0, 0.77778],
    "57367": [0.25142, 0.75726, 0, 0, 0.77778],
    "57368": [0.25142, 0.75726, 0, 0, 0.77778],
    "57369": [0.25142, 0.75726, 0, 0, 0.77778],
    "57370": [0.13597, 0.63597, 0, 0, 0.77778],
    "57371": [0.13597, 0.63597, 0, 0, 0.77778]
  },
  "Caligraphic-Regular": {
    "32": [0, 0, 0, 0, 0.25],
    "65": [0, 0.68333, 0, 0.19445, 0.79847],
    "66": [0, 0.68333, 0.03041, 0.13889, 0.65681],
    "67": [0, 0.68333, 0.05834, 0.13889, 0.52653],
    "68": [0, 0.68333, 0.02778, 0.08334, 0.77139],
    "69": [0, 0.68333, 0.08944, 0.11111, 0.52778],
    "70": [0, 0.68333, 0.09931, 0.11111, 0.71875],
    "71": [0.09722, 0.68333, 0.0593, 0.11111, 0.59487],
    "72": [0, 0.68333, 965e-5, 0.11111, 0.84452],
    "73": [0, 0.68333, 0.07382, 0, 0.54452],
    "74": [0.09722, 0.68333, 0.18472, 0.16667, 0.67778],
    "75": [0, 0.68333, 0.01445, 0.05556, 0.76195],
    "76": [0, 0.68333, 0, 0.13889, 0.68972],
    "77": [0, 0.68333, 0, 0.13889, 1.2009],
    "78": [0, 0.68333, 0.14736, 0.08334, 0.82049],
    "79": [0, 0.68333, 0.02778, 0.11111, 0.79611],
    "80": [0, 0.68333, 0.08222, 0.08334, 0.69556],
    "81": [0.09722, 0.68333, 0, 0.11111, 0.81667],
    "82": [0, 0.68333, 0, 0.08334, 0.8475],
    "83": [0, 0.68333, 0.075, 0.13889, 0.60556],
    "84": [0, 0.68333, 0.25417, 0, 0.54464],
    "85": [0, 0.68333, 0.09931, 0.08334, 0.62583],
    "86": [0, 0.68333, 0.08222, 0, 0.61278],
    "87": [0, 0.68333, 0.08222, 0.08334, 0.98778],
    "88": [0, 0.68333, 0.14643, 0.13889, 0.7133],
    "89": [0.09722, 0.68333, 0.08222, 0.08334, 0.66834],
    "90": [0, 0.68333, 0.07944, 0.13889, 0.72473],
    "160": [0, 0, 0, 0, 0.25]
  },
  "Fraktur-Regular": {
    "32": [0, 0, 0, 0, 0.25],
    "33": [0, 0.69141, 0, 0, 0.29574],
    "34": [0, 0.69141, 0, 0, 0.21471],
    "38": [0, 0.69141, 0, 0, 0.73786],
    "39": [0, 0.69141, 0, 0, 0.21201],
    "40": [0.24982, 0.74947, 0, 0, 0.38865],
    "41": [0.24982, 0.74947, 0, 0, 0.38865],
    "42": [0, 0.62119, 0, 0, 0.27764],
    "43": [0.08319, 0.58283, 0, 0, 0.75623],
    "44": [0, 0.10803, 0, 0, 0.27764],
    "45": [0.08319, 0.58283, 0, 0, 0.75623],
    "46": [0, 0.10803, 0, 0, 0.27764],
    "47": [0.24982, 0.74947, 0, 0, 0.50181],
    "48": [0, 0.47534, 0, 0, 0.50181],
    "49": [0, 0.47534, 0, 0, 0.50181],
    "50": [0, 0.47534, 0, 0, 0.50181],
    "51": [0.18906, 0.47534, 0, 0, 0.50181],
    "52": [0.18906, 0.47534, 0, 0, 0.50181],
    "53": [0.18906, 0.47534, 0, 0, 0.50181],
    "54": [0, 0.69141, 0, 0, 0.50181],
    "55": [0.18906, 0.47534, 0, 0, 0.50181],
    "56": [0, 0.69141, 0, 0, 0.50181],
    "57": [0.18906, 0.47534, 0, 0, 0.50181],
    "58": [0, 0.47534, 0, 0, 0.21606],
    "59": [0.12604, 0.47534, 0, 0, 0.21606],
    "61": [-0.13099, 0.36866, 0, 0, 0.75623],
    "63": [0, 0.69141, 0, 0, 0.36245],
    "65": [0, 0.69141, 0, 0, 0.7176],
    "66": [0, 0.69141, 0, 0, 0.88397],
    "67": [0, 0.69141, 0, 0, 0.61254],
    "68": [0, 0.69141, 0, 0, 0.83158],
    "69": [0, 0.69141, 0, 0, 0.66278],
    "70": [0.12604, 0.69141, 0, 0, 0.61119],
    "71": [0, 0.69141, 0, 0, 0.78539],
    "72": [0.06302, 0.69141, 0, 0, 0.7203],
    "73": [0, 0.69141, 0, 0, 0.55448],
    "74": [0.12604, 0.69141, 0, 0, 0.55231],
    "75": [0, 0.69141, 0, 0, 0.66845],
    "76": [0, 0.69141, 0, 0, 0.66602],
    "77": [0, 0.69141, 0, 0, 1.04953],
    "78": [0, 0.69141, 0, 0, 0.83212],
    "79": [0, 0.69141, 0, 0, 0.82699],
    "80": [0.18906, 0.69141, 0, 0, 0.82753],
    "81": [0.03781, 0.69141, 0, 0, 0.82699],
    "82": [0, 0.69141, 0, 0, 0.82807],
    "83": [0, 0.69141, 0, 0, 0.82861],
    "84": [0, 0.69141, 0, 0, 0.66899],
    "85": [0, 0.69141, 0, 0, 0.64576],
    "86": [0, 0.69141, 0, 0, 0.83131],
    "87": [0, 0.69141, 0, 0, 1.04602],
    "88": [0, 0.69141, 0, 0, 0.71922],
    "89": [0.18906, 0.69141, 0, 0, 0.83293],
    "90": [0.12604, 0.69141, 0, 0, 0.60201],
    "91": [0.24982, 0.74947, 0, 0, 0.27764],
    "93": [0.24982, 0.74947, 0, 0, 0.27764],
    "94": [0, 0.69141, 0, 0, 0.49965],
    "97": [0, 0.47534, 0, 0, 0.50046],
    "98": [0, 0.69141, 0, 0, 0.51315],
    "99": [0, 0.47534, 0, 0, 0.38946],
    "100": [0, 0.62119, 0, 0, 0.49857],
    "101": [0, 0.47534, 0, 0, 0.40053],
    "102": [0.18906, 0.69141, 0, 0, 0.32626],
    "103": [0.18906, 0.47534, 0, 0, 0.5037],
    "104": [0.18906, 0.69141, 0, 0, 0.52126],
    "105": [0, 0.69141, 0, 0, 0.27899],
    "106": [0, 0.69141, 0, 0, 0.28088],
    "107": [0, 0.69141, 0, 0, 0.38946],
    "108": [0, 0.69141, 0, 0, 0.27953],
    "109": [0, 0.47534, 0, 0, 0.76676],
    "110": [0, 0.47534, 0, 0, 0.52666],
    "111": [0, 0.47534, 0, 0, 0.48885],
    "112": [0.18906, 0.52396, 0, 0, 0.50046],
    "113": [0.18906, 0.47534, 0, 0, 0.48912],
    "114": [0, 0.47534, 0, 0, 0.38919],
    "115": [0, 0.47534, 0, 0, 0.44266],
    "116": [0, 0.62119, 0, 0, 0.33301],
    "117": [0, 0.47534, 0, 0, 0.5172],
    "118": [0, 0.52396, 0, 0, 0.5118],
    "119": [0, 0.52396, 0, 0, 0.77351],
    "120": [0.18906, 0.47534, 0, 0, 0.38865],
    "121": [0.18906, 0.47534, 0, 0, 0.49884],
    "122": [0.18906, 0.47534, 0, 0, 0.39054],
    "160": [0, 0, 0, 0, 0.25],
    "8216": [0, 0.69141, 0, 0, 0.21471],
    "8217": [0, 0.69141, 0, 0, 0.21471],
    "58112": [0, 0.62119, 0, 0, 0.49749],
    "58113": [0, 0.62119, 0, 0, 0.4983],
    "58114": [0.18906, 0.69141, 0, 0, 0.33328],
    "58115": [0.18906, 0.69141, 0, 0, 0.32923],
    "58116": [0.18906, 0.47534, 0, 0, 0.50343],
    "58117": [0, 0.69141, 0, 0, 0.33301],
    "58118": [0, 0.62119, 0, 0, 0.33409],
    "58119": [0, 0.47534, 0, 0, 0.50073]
  },
  "Main-Bold": {
    "32": [0, 0, 0, 0, 0.25],
    "33": [0, 0.69444, 0, 0, 0.35],
    "34": [0, 0.69444, 0, 0, 0.60278],
    "35": [0.19444, 0.69444, 0, 0, 0.95833],
    "36": [0.05556, 0.75, 0, 0, 0.575],
    "37": [0.05556, 0.75, 0, 0, 0.95833],
    "38": [0, 0.69444, 0, 0, 0.89444],
    "39": [0, 0.69444, 0, 0, 0.31944],
    "40": [0.25, 0.75, 0, 0, 0.44722],
    "41": [0.25, 0.75, 0, 0, 0.44722],
    "42": [0, 0.75, 0, 0, 0.575],
    "43": [0.13333, 0.63333, 0, 0, 0.89444],
    "44": [0.19444, 0.15556, 0, 0, 0.31944],
    "45": [0, 0.44444, 0, 0, 0.38333],
    "46": [0, 0.15556, 0, 0, 0.31944],
    "47": [0.25, 0.75, 0, 0, 0.575],
    "48": [0, 0.64444, 0, 0, 0.575],
    "49": [0, 0.64444, 0, 0, 0.575],
    "50": [0, 0.64444, 0, 0, 0.575],
    "51": [0, 0.64444, 0, 0, 0.575],
    "52": [0, 0.64444, 0, 0, 0.575],
    "53": [0, 0.64444, 0, 0, 0.575],
    "54": [0, 0.64444, 0, 0, 0.575],
    "55": [0, 0.64444, 0, 0, 0.575],
    "56": [0, 0.64444, 0, 0, 0.575],
    "57": [0, 0.64444, 0, 0, 0.575],
    "58": [0, 0.44444, 0, 0, 0.31944],
    "59": [0.19444, 0.44444, 0, 0, 0.31944],
    "60": [0.08556, 0.58556, 0, 0, 0.89444],
    "61": [-0.10889, 0.39111, 0, 0, 0.89444],
    "62": [0.08556, 0.58556, 0, 0, 0.89444],
    "63": [0, 0.69444, 0, 0, 0.54305],
    "64": [0, 0.69444, 0, 0, 0.89444],
    "65": [0, 0.68611, 0, 0, 0.86944],
    "66": [0, 0.68611, 0, 0, 0.81805],
    "67": [0, 0.68611, 0, 0, 0.83055],
    "68": [0, 0.68611, 0, 0, 0.88194],
    "69": [0, 0.68611, 0, 0, 0.75555],
    "70": [0, 0.68611, 0, 0, 0.72361],
    "71": [0, 0.68611, 0, 0, 0.90416],
    "72": [0, 0.68611, 0, 0, 0.9],
    "73": [0, 0.68611, 0, 0, 0.43611],
    "74": [0, 0.68611, 0, 0, 0.59444],
    "75": [0, 0.68611, 0, 0, 0.90138],
    "76": [0, 0.68611, 0, 0, 0.69166],
    "77": [0, 0.68611, 0, 0, 1.09166],
    "78": [0, 0.68611, 0, 0, 0.9],
    "79": [0, 0.68611, 0, 0, 0.86388],
    "80": [0, 0.68611, 0, 0, 0.78611],
    "81": [0.19444, 0.68611, 0, 0, 0.86388],
    "82": [0, 0.68611, 0, 0, 0.8625],
    "83": [0, 0.68611, 0, 0, 0.63889],
    "84": [0, 0.68611, 0, 0, 0.8],
    "85": [0, 0.68611, 0, 0, 0.88472],
    "86": [0, 0.68611, 0.01597, 0, 0.86944],
    "87": [0, 0.68611, 0.01597, 0, 1.18888],
    "88": [0, 0.68611, 0, 0, 0.86944],
    "89": [0, 0.68611, 0.02875, 0, 0.86944],
    "90": [0, 0.68611, 0, 0, 0.70277],
    "91": [0.25, 0.75, 0, 0, 0.31944],
    "92": [0.25, 0.75, 0, 0, 0.575],
    "93": [0.25, 0.75, 0, 0, 0.31944],
    "94": [0, 0.69444, 0, 0, 0.575],
    "95": [0.31, 0.13444, 0.03194, 0, 0.575],
    "97": [0, 0.44444, 0, 0, 0.55902],
    "98": [0, 0.69444, 0, 0, 0.63889],
    "99": [0, 0.44444, 0, 0, 0.51111],
    "100": [0, 0.69444, 0, 0, 0.63889],
    "101": [0, 0.44444, 0, 0, 0.52708],
    "102": [0, 0.69444, 0.10903, 0, 0.35139],
    "103": [0.19444, 0.44444, 0.01597, 0, 0.575],
    "104": [0, 0.69444, 0, 0, 0.63889],
    "105": [0, 0.69444, 0, 0, 0.31944],
    "106": [0.19444, 0.69444, 0, 0, 0.35139],
    "107": [0, 0.69444, 0, 0, 0.60694],
    "108": [0, 0.69444, 0, 0, 0.31944],
    "109": [0, 0.44444, 0, 0, 0.95833],
    "110": [0, 0.44444, 0, 0, 0.63889],
    "111": [0, 0.44444, 0, 0, 0.575],
    "112": [0.19444, 0.44444, 0, 0, 0.63889],
    "113": [0.19444, 0.44444, 0, 0, 0.60694],
    "114": [0, 0.44444, 0, 0, 0.47361],
    "115": [0, 0.44444, 0, 0, 0.45361],
    "116": [0, 0.63492, 0, 0, 0.44722],
    "117": [0, 0.44444, 0, 0, 0.63889],
    "118": [0, 0.44444, 0.01597, 0, 0.60694],
    "119": [0, 0.44444, 0.01597, 0, 0.83055],
    "120": [0, 0.44444, 0, 0, 0.60694],
    "121": [0.19444, 0.44444, 0.01597, 0, 0.60694],
    "122": [0, 0.44444, 0, 0, 0.51111],
    "123": [0.25, 0.75, 0, 0, 0.575],
    "124": [0.25, 0.75, 0, 0, 0.31944],
    "125": [0.25, 0.75, 0, 0, 0.575],
    "126": [0.35, 0.34444, 0, 0, 0.575],
    "160": [0, 0, 0, 0, 0.25],
    "163": [0, 0.69444, 0, 0, 0.86853],
    "168": [0, 0.69444, 0, 0, 0.575],
    "172": [0, 0.44444, 0, 0, 0.76666],
    "176": [0, 0.69444, 0, 0, 0.86944],
    "177": [0.13333, 0.63333, 0, 0, 0.89444],
    "184": [0.17014, 0, 0, 0, 0.51111],
    "198": [0, 0.68611, 0, 0, 1.04166],
    "215": [0.13333, 0.63333, 0, 0, 0.89444],
    "216": [0.04861, 0.73472, 0, 0, 0.89444],
    "223": [0, 0.69444, 0, 0, 0.59722],
    "230": [0, 0.44444, 0, 0, 0.83055],
    "247": [0.13333, 0.63333, 0, 0, 0.89444],
    "248": [0.09722, 0.54167, 0, 0, 0.575],
    "305": [0, 0.44444, 0, 0, 0.31944],
    "338": [0, 0.68611, 0, 0, 1.16944],
    "339": [0, 0.44444, 0, 0, 0.89444],
    "567": [0.19444, 0.44444, 0, 0, 0.35139],
    "710": [0, 0.69444, 0, 0, 0.575],
    "711": [0, 0.63194, 0, 0, 0.575],
    "713": [0, 0.59611, 0, 0, 0.575],
    "714": [0, 0.69444, 0, 0, 0.575],
    "715": [0, 0.69444, 0, 0, 0.575],
    "728": [0, 0.69444, 0, 0, 0.575],
    "729": [0, 0.69444, 0, 0, 0.31944],
    "730": [0, 0.69444, 0, 0, 0.86944],
    "732": [0, 0.69444, 0, 0, 0.575],
    "733": [0, 0.69444, 0, 0, 0.575],
    "915": [0, 0.68611, 0, 0, 0.69166],
    "916": [0, 0.68611, 0, 0, 0.95833],
    "920": [0, 0.68611, 0, 0, 0.89444],
    "923": [0, 0.68611, 0, 0, 0.80555],
    "926": [0, 0.68611, 0, 0, 0.76666],
    "928": [0, 0.68611, 0, 0, 0.9],
    "931": [0, 0.68611, 0, 0, 0.83055],
    "933": [0, 0.68611, 0, 0, 0.89444],
    "934": [0, 0.68611, 0, 0, 0.83055],
    "936": [0, 0.68611, 0, 0, 0.89444],
    "937": [0, 0.68611, 0, 0, 0.83055],
    "8211": [0, 0.44444, 0.03194, 0, 0.575],
    "8212": [0, 0.44444, 0.03194, 0, 1.14999],
    "8216": [0, 0.69444, 0, 0, 0.31944],
    "8217": [0, 0.69444, 0, 0, 0.31944],
    "8220": [0, 0.69444, 0, 0, 0.60278],
    "8221": [0, 0.69444, 0, 0, 0.60278],
    "8224": [0.19444, 0.69444, 0, 0, 0.51111],
    "8225": [0.19444, 0.69444, 0, 0, 0.51111],
    "8242": [0, 0.55556, 0, 0, 0.34444],
    "8407": [0, 0.72444, 0.15486, 0, 0.575],
    "8463": [0, 0.69444, 0, 0, 0.66759],
    "8465": [0, 0.69444, 0, 0, 0.83055],
    "8467": [0, 0.69444, 0, 0, 0.47361],
    "8472": [0.19444, 0.44444, 0, 0, 0.74027],
    "8476": [0, 0.69444, 0, 0, 0.83055],
    "8501": [0, 0.69444, 0, 0, 0.70277],
    "8592": [-0.10889, 0.39111, 0, 0, 1.14999],
    "8593": [0.19444, 0.69444, 0, 0, 0.575],
    "8594": [-0.10889, 0.39111, 0, 0, 1.14999],
    "8595": [0.19444, 0.69444, 0, 0, 0.575],
    "8596": [-0.10889, 0.39111, 0, 0, 1.14999],
    "8597": [0.25, 0.75, 0, 0, 0.575],
    "8598": [0.19444, 0.69444, 0, 0, 1.14999],
    "8599": [0.19444, 0.69444, 0, 0, 1.14999],
    "8600": [0.19444, 0.69444, 0, 0, 1.14999],
    "8601": [0.19444, 0.69444, 0, 0, 1.14999],
    "8636": [-0.10889, 0.39111, 0, 0, 1.14999],
    "8637": [-0.10889, 0.39111, 0, 0, 1.14999],
    "8640": [-0.10889, 0.39111, 0, 0, 1.14999],
    "8641": [-0.10889, 0.39111, 0, 0, 1.14999],
    "8656": [-0.10889, 0.39111, 0, 0, 1.14999],
    "8657": [0.19444, 0.69444, 0, 0, 0.70277],
    "8658": [-0.10889, 0.39111, 0, 0, 1.14999],
    "8659": [0.19444, 0.69444, 0, 0, 0.70277],
    "8660": [-0.10889, 0.39111, 0, 0, 1.14999],
    "8661": [0.25, 0.75, 0, 0, 0.70277],
    "8704": [0, 0.69444, 0, 0, 0.63889],
    "8706": [0, 0.69444, 0.06389, 0, 0.62847],
    "8707": [0, 0.69444, 0, 0, 0.63889],
    "8709": [0.05556, 0.75, 0, 0, 0.575],
    "8711": [0, 0.68611, 0, 0, 0.95833],
    "8712": [0.08556, 0.58556, 0, 0, 0.76666],
    "8715": [0.08556, 0.58556, 0, 0, 0.76666],
    "8722": [0.13333, 0.63333, 0, 0, 0.89444],
    "8723": [0.13333, 0.63333, 0, 0, 0.89444],
    "8725": [0.25, 0.75, 0, 0, 0.575],
    "8726": [0.25, 0.75, 0, 0, 0.575],
    "8727": [-0.02778, 0.47222, 0, 0, 0.575],
    "8728": [-0.02639, 0.47361, 0, 0, 0.575],
    "8729": [-0.02639, 0.47361, 0, 0, 0.575],
    "8730": [0.18, 0.82, 0, 0, 0.95833],
    "8733": [0, 0.44444, 0, 0, 0.89444],
    "8734": [0, 0.44444, 0, 0, 1.14999],
    "8736": [0, 0.69224, 0, 0, 0.72222],
    "8739": [0.25, 0.75, 0, 0, 0.31944],
    "8741": [0.25, 0.75, 0, 0, 0.575],
    "8743": [0, 0.55556, 0, 0, 0.76666],
    "8744": [0, 0.55556, 0, 0, 0.76666],
    "8745": [0, 0.55556, 0, 0, 0.76666],
    "8746": [0, 0.55556, 0, 0, 0.76666],
    "8747": [0.19444, 0.69444, 0.12778, 0, 0.56875],
    "8764": [-0.10889, 0.39111, 0, 0, 0.89444],
    "8768": [0.19444, 0.69444, 0, 0, 0.31944],
    "8771": [222e-5, 0.50222, 0, 0, 0.89444],
    "8773": [0.027, 0.638, 0, 0, 0.894],
    "8776": [0.02444, 0.52444, 0, 0, 0.89444],
    "8781": [222e-5, 0.50222, 0, 0, 0.89444],
    "8801": [222e-5, 0.50222, 0, 0, 0.89444],
    "8804": [0.19667, 0.69667, 0, 0, 0.89444],
    "8805": [0.19667, 0.69667, 0, 0, 0.89444],
    "8810": [0.08556, 0.58556, 0, 0, 1.14999],
    "8811": [0.08556, 0.58556, 0, 0, 1.14999],
    "8826": [0.08556, 0.58556, 0, 0, 0.89444],
    "8827": [0.08556, 0.58556, 0, 0, 0.89444],
    "8834": [0.08556, 0.58556, 0, 0, 0.89444],
    "8835": [0.08556, 0.58556, 0, 0, 0.89444],
    "8838": [0.19667, 0.69667, 0, 0, 0.89444],
    "8839": [0.19667, 0.69667, 0, 0, 0.89444],
    "8846": [0, 0.55556, 0, 0, 0.76666],
    "8849": [0.19667, 0.69667, 0, 0, 0.89444],
    "8850": [0.19667, 0.69667, 0, 0, 0.89444],
    "8851": [0, 0.55556, 0, 0, 0.76666],
    "8852": [0, 0.55556, 0, 0, 0.76666],
    "8853": [0.13333, 0.63333, 0, 0, 0.89444],
    "8854": [0.13333, 0.63333, 0, 0, 0.89444],
    "8855": [0.13333, 0.63333, 0, 0, 0.89444],
    "8856": [0.13333, 0.63333, 0, 0, 0.89444],
    "8857": [0.13333, 0.63333, 0, 0, 0.89444],
    "8866": [0, 0.69444, 0, 0, 0.70277],
    "8867": [0, 0.69444, 0, 0, 0.70277],
    "8868": [0, 0.69444, 0, 0, 0.89444],
    "8869": [0, 0.69444, 0, 0, 0.89444],
    "8900": [-0.02639, 0.47361, 0, 0, 0.575],
    "8901": [-0.02639, 0.47361, 0, 0, 0.31944],
    "8902": [-0.02778, 0.47222, 0, 0, 0.575],
    "8968": [0.25, 0.75, 0, 0, 0.51111],
    "8969": [0.25, 0.75, 0, 0, 0.51111],
    "8970": [0.25, 0.75, 0, 0, 0.51111],
    "8971": [0.25, 0.75, 0, 0, 0.51111],
    "8994": [-0.13889, 0.36111, 0, 0, 1.14999],
    "8995": [-0.13889, 0.36111, 0, 0, 1.14999],
    "9651": [0.19444, 0.69444, 0, 0, 1.02222],
    "9657": [-0.02778, 0.47222, 0, 0, 0.575],
    "9661": [0.19444, 0.69444, 0, 0, 1.02222],
    "9667": [-0.02778, 0.47222, 0, 0, 0.575],
    "9711": [0.19444, 0.69444, 0, 0, 1.14999],
    "9824": [0.12963, 0.69444, 0, 0, 0.89444],
    "9825": [0.12963, 0.69444, 0, 0, 0.89444],
    "9826": [0.12963, 0.69444, 0, 0, 0.89444],
    "9827": [0.12963, 0.69444, 0, 0, 0.89444],
    "9837": [0, 0.75, 0, 0, 0.44722],
    "9838": [0.19444, 0.69444, 0, 0, 0.44722],
    "9839": [0.19444, 0.69444, 0, 0, 0.44722],
    "10216": [0.25, 0.75, 0, 0, 0.44722],
    "10217": [0.25, 0.75, 0, 0, 0.44722],
    "10815": [0, 0.68611, 0, 0, 0.9],
    "10927": [0.19667, 0.69667, 0, 0, 0.89444],
    "10928": [0.19667, 0.69667, 0, 0, 0.89444],
    "57376": [0.19444, 0.69444, 0, 0, 0]
  },
  "Main-BoldItalic": {
    "32": [0, 0, 0, 0, 0.25],
    "33": [0, 0.69444, 0.11417, 0, 0.38611],
    "34": [0, 0.69444, 0.07939, 0, 0.62055],
    "35": [0.19444, 0.69444, 0.06833, 0, 0.94444],
    "37": [0.05556, 0.75, 0.12861, 0, 0.94444],
    "38": [0, 0.69444, 0.08528, 0, 0.88555],
    "39": [0, 0.69444, 0.12945, 0, 0.35555],
    "40": [0.25, 0.75, 0.15806, 0, 0.47333],
    "41": [0.25, 0.75, 0.03306, 0, 0.47333],
    "42": [0, 0.75, 0.14333, 0, 0.59111],
    "43": [0.10333, 0.60333, 0.03306, 0, 0.88555],
    "44": [0.19444, 0.14722, 0, 0, 0.35555],
    "45": [0, 0.44444, 0.02611, 0, 0.41444],
    "46": [0, 0.14722, 0, 0, 0.35555],
    "47": [0.25, 0.75, 0.15806, 0, 0.59111],
    "48": [0, 0.64444, 0.13167, 0, 0.59111],
    "49": [0, 0.64444, 0.13167, 0, 0.59111],
    "50": [0, 0.64444, 0.13167, 0, 0.59111],
    "51": [0, 0.64444, 0.13167, 0, 0.59111],
    "52": [0.19444, 0.64444, 0.13167, 0, 0.59111],
    "53": [0, 0.64444, 0.13167, 0, 0.59111],
    "54": [0, 0.64444, 0.13167, 0, 0.59111],
    "55": [0.19444, 0.64444, 0.13167, 0, 0.59111],
    "56": [0, 0.64444, 0.13167, 0, 0.59111],
    "57": [0, 0.64444, 0.13167, 0, 0.59111],
    "58": [0, 0.44444, 0.06695, 0, 0.35555],
    "59": [0.19444, 0.44444, 0.06695, 0, 0.35555],
    "61": [-0.10889, 0.39111, 0.06833, 0, 0.88555],
    "63": [0, 0.69444, 0.11472, 0, 0.59111],
    "64": [0, 0.69444, 0.09208, 0, 0.88555],
    "65": [0, 0.68611, 0, 0, 0.86555],
    "66": [0, 0.68611, 0.0992, 0, 0.81666],
    "67": [0, 0.68611, 0.14208, 0, 0.82666],
    "68": [0, 0.68611, 0.09062, 0, 0.87555],
    "69": [0, 0.68611, 0.11431, 0, 0.75666],
    "70": [0, 0.68611, 0.12903, 0, 0.72722],
    "71": [0, 0.68611, 0.07347, 0, 0.89527],
    "72": [0, 0.68611, 0.17208, 0, 0.8961],
    "73": [0, 0.68611, 0.15681, 0, 0.47166],
    "74": [0, 0.68611, 0.145, 0, 0.61055],
    "75": [0, 0.68611, 0.14208, 0, 0.89499],
    "76": [0, 0.68611, 0, 0, 0.69777],
    "77": [0, 0.68611, 0.17208, 0, 1.07277],
    "78": [0, 0.68611, 0.17208, 0, 0.8961],
    "79": [0, 0.68611, 0.09062, 0, 0.85499],
    "80": [0, 0.68611, 0.0992, 0, 0.78721],
    "81": [0.19444, 0.68611, 0.09062, 0, 0.85499],
    "82": [0, 0.68611, 0.02559, 0, 0.85944],
    "83": [0, 0.68611, 0.11264, 0, 0.64999],
    "84": [0, 0.68611, 0.12903, 0, 0.7961],
    "85": [0, 0.68611, 0.17208, 0, 0.88083],
    "86": [0, 0.68611, 0.18625, 0, 0.86555],
    "87": [0, 0.68611, 0.18625, 0, 1.15999],
    "88": [0, 0.68611, 0.15681, 0, 0.86555],
    "89": [0, 0.68611, 0.19803, 0, 0.86555],
    "90": [0, 0.68611, 0.14208, 0, 0.70888],
    "91": [0.25, 0.75, 0.1875, 0, 0.35611],
    "93": [0.25, 0.75, 0.09972, 0, 0.35611],
    "94": [0, 0.69444, 0.06709, 0, 0.59111],
    "95": [0.31, 0.13444, 0.09811, 0, 0.59111],
    "97": [0, 0.44444, 0.09426, 0, 0.59111],
    "98": [0, 0.69444, 0.07861, 0, 0.53222],
    "99": [0, 0.44444, 0.05222, 0, 0.53222],
    "100": [0, 0.69444, 0.10861, 0, 0.59111],
    "101": [0, 0.44444, 0.085, 0, 0.53222],
    "102": [0.19444, 0.69444, 0.21778, 0, 0.4],
    "103": [0.19444, 0.44444, 0.105, 0, 0.53222],
    "104": [0, 0.69444, 0.09426, 0, 0.59111],
    "105": [0, 0.69326, 0.11387, 0, 0.35555],
    "106": [0.19444, 0.69326, 0.1672, 0, 0.35555],
    "107": [0, 0.69444, 0.11111, 0, 0.53222],
    "108": [0, 0.69444, 0.10861, 0, 0.29666],
    "109": [0, 0.44444, 0.09426, 0, 0.94444],
    "110": [0, 0.44444, 0.09426, 0, 0.64999],
    "111": [0, 0.44444, 0.07861, 0, 0.59111],
    "112": [0.19444, 0.44444, 0.07861, 0, 0.59111],
    "113": [0.19444, 0.44444, 0.105, 0, 0.53222],
    "114": [0, 0.44444, 0.11111, 0, 0.50167],
    "115": [0, 0.44444, 0.08167, 0, 0.48694],
    "116": [0, 0.63492, 0.09639, 0, 0.385],
    "117": [0, 0.44444, 0.09426, 0, 0.62055],
    "118": [0, 0.44444, 0.11111, 0, 0.53222],
    "119": [0, 0.44444, 0.11111, 0, 0.76777],
    "120": [0, 0.44444, 0.12583, 0, 0.56055],
    "121": [0.19444, 0.44444, 0.105, 0, 0.56166],
    "122": [0, 0.44444, 0.13889, 0, 0.49055],
    "126": [0.35, 0.34444, 0.11472, 0, 0.59111],
    "160": [0, 0, 0, 0, 0.25],
    "168": [0, 0.69444, 0.11473, 0, 0.59111],
    "176": [0, 0.69444, 0, 0, 0.94888],
    "184": [0.17014, 0, 0, 0, 0.53222],
    "198": [0, 0.68611, 0.11431, 0, 1.02277],
    "216": [0.04861, 0.73472, 0.09062, 0, 0.88555],
    "223": [0.19444, 0.69444, 0.09736, 0, 0.665],
    "230": [0, 0.44444, 0.085, 0, 0.82666],
    "248": [0.09722, 0.54167, 0.09458, 0, 0.59111],
    "305": [0, 0.44444, 0.09426, 0, 0.35555],
    "338": [0, 0.68611, 0.11431, 0, 1.14054],
    "339": [0, 0.44444, 0.085, 0, 0.82666],
    "567": [0.19444, 0.44444, 0.04611, 0, 0.385],
    "710": [0, 0.69444, 0.06709, 0, 0.59111],
    "711": [0, 0.63194, 0.08271, 0, 0.59111],
    "713": [0, 0.59444, 0.10444, 0, 0.59111],
    "714": [0, 0.69444, 0.08528, 0, 0.59111],
    "715": [0, 0.69444, 0, 0, 0.59111],
    "728": [0, 0.69444, 0.10333, 0, 0.59111],
    "729": [0, 0.69444, 0.12945, 0, 0.35555],
    "730": [0, 0.69444, 0, 0, 0.94888],
    "732": [0, 0.69444, 0.11472, 0, 0.59111],
    "733": [0, 0.69444, 0.11472, 0, 0.59111],
    "915": [0, 0.68611, 0.12903, 0, 0.69777],
    "916": [0, 0.68611, 0, 0, 0.94444],
    "920": [0, 0.68611, 0.09062, 0, 0.88555],
    "923": [0, 0.68611, 0, 0, 0.80666],
    "926": [0, 0.68611, 0.15092, 0, 0.76777],
    "928": [0, 0.68611, 0.17208, 0, 0.8961],
    "931": [0, 0.68611, 0.11431, 0, 0.82666],
    "933": [0, 0.68611, 0.10778, 0, 0.88555],
    "934": [0, 0.68611, 0.05632, 0, 0.82666],
    "936": [0, 0.68611, 0.10778, 0, 0.88555],
    "937": [0, 0.68611, 0.0992, 0, 0.82666],
    "8211": [0, 0.44444, 0.09811, 0, 0.59111],
    "8212": [0, 0.44444, 0.09811, 0, 1.18221],
    "8216": [0, 0.69444, 0.12945, 0, 0.35555],
    "8217": [0, 0.69444, 0.12945, 0, 0.35555],
    "8220": [0, 0.69444, 0.16772, 0, 0.62055],
    "8221": [0, 0.69444, 0.07939, 0, 0.62055]
  },
  "Main-Italic": {
    "32": [0, 0, 0, 0, 0.25],
    "33": [0, 0.69444, 0.12417, 0, 0.30667],
    "34": [0, 0.69444, 0.06961, 0, 0.51444],
    "35": [0.19444, 0.69444, 0.06616, 0, 0.81777],
    "37": [0.05556, 0.75, 0.13639, 0, 0.81777],
    "38": [0, 0.69444, 0.09694, 0, 0.76666],
    "39": [0, 0.69444, 0.12417, 0, 0.30667],
    "40": [0.25, 0.75, 0.16194, 0, 0.40889],
    "41": [0.25, 0.75, 0.03694, 0, 0.40889],
    "42": [0, 0.75, 0.14917, 0, 0.51111],
    "43": [0.05667, 0.56167, 0.03694, 0, 0.76666],
    "44": [0.19444, 0.10556, 0, 0, 0.30667],
    "45": [0, 0.43056, 0.02826, 0, 0.35778],
    "46": [0, 0.10556, 0, 0, 0.30667],
    "47": [0.25, 0.75, 0.16194, 0, 0.51111],
    "48": [0, 0.64444, 0.13556, 0, 0.51111],
    "49": [0, 0.64444, 0.13556, 0, 0.51111],
    "50": [0, 0.64444, 0.13556, 0, 0.51111],
    "51": [0, 0.64444, 0.13556, 0, 0.51111],
    "52": [0.19444, 0.64444, 0.13556, 0, 0.51111],
    "53": [0, 0.64444, 0.13556, 0, 0.51111],
    "54": [0, 0.64444, 0.13556, 0, 0.51111],
    "55": [0.19444, 0.64444, 0.13556, 0, 0.51111],
    "56": [0, 0.64444, 0.13556, 0, 0.51111],
    "57": [0, 0.64444, 0.13556, 0, 0.51111],
    "58": [0, 0.43056, 0.0582, 0, 0.30667],
    "59": [0.19444, 0.43056, 0.0582, 0, 0.30667],
    "61": [-0.13313, 0.36687, 0.06616, 0, 0.76666],
    "63": [0, 0.69444, 0.1225, 0, 0.51111],
    "64": [0, 0.69444, 0.09597, 0, 0.76666],
    "65": [0, 0.68333, 0, 0, 0.74333],
    "66": [0, 0.68333, 0.10257, 0, 0.70389],
    "67": [0, 0.68333, 0.14528, 0, 0.71555],
    "68": [0, 0.68333, 0.09403, 0, 0.755],
    "69": [0, 0.68333, 0.12028, 0, 0.67833],
    "70": [0, 0.68333, 0.13305, 0, 0.65277],
    "71": [0, 0.68333, 0.08722, 0, 0.77361],
    "72": [0, 0.68333, 0.16389, 0, 0.74333],
    "73": [0, 0.68333, 0.15806, 0, 0.38555],
    "74": [0, 0.68333, 0.14028, 0, 0.525],
    "75": [0, 0.68333, 0.14528, 0, 0.76888],
    "76": [0, 0.68333, 0, 0, 0.62722],
    "77": [0, 0.68333, 0.16389, 0, 0.89666],
    "78": [0, 0.68333, 0.16389, 0, 0.74333],
    "79": [0, 0.68333, 0.09403, 0, 0.76666],
    "80": [0, 0.68333, 0.10257, 0, 0.67833],
    "81": [0.19444, 0.68333, 0.09403, 0, 0.76666],
    "82": [0, 0.68333, 0.03868, 0, 0.72944],
    "83": [0, 0.68333, 0.11972, 0, 0.56222],
    "84": [0, 0.68333, 0.13305, 0, 0.71555],
    "85": [0, 0.68333, 0.16389, 0, 0.74333],
    "86": [0, 0.68333, 0.18361, 0, 0.74333],
    "87": [0, 0.68333, 0.18361, 0, 0.99888],
    "88": [0, 0.68333, 0.15806, 0, 0.74333],
    "89": [0, 0.68333, 0.19383, 0, 0.74333],
    "90": [0, 0.68333, 0.14528, 0, 0.61333],
    "91": [0.25, 0.75, 0.1875, 0, 0.30667],
    "93": [0.25, 0.75, 0.10528, 0, 0.30667],
    "94": [0, 0.69444, 0.06646, 0, 0.51111],
    "95": [0.31, 0.12056, 0.09208, 0, 0.51111],
    "97": [0, 0.43056, 0.07671, 0, 0.51111],
    "98": [0, 0.69444, 0.06312, 0, 0.46],
    "99": [0, 0.43056, 0.05653, 0, 0.46],
    "100": [0, 0.69444, 0.10333, 0, 0.51111],
    "101": [0, 0.43056, 0.07514, 0, 0.46],
    "102": [0.19444, 0.69444, 0.21194, 0, 0.30667],
    "103": [0.19444, 0.43056, 0.08847, 0, 0.46],
    "104": [0, 0.69444, 0.07671, 0, 0.51111],
    "105": [0, 0.65536, 0.1019, 0, 0.30667],
    "106": [0.19444, 0.65536, 0.14467, 0, 0.30667],
    "107": [0, 0.69444, 0.10764, 0, 0.46],
    "108": [0, 0.69444, 0.10333, 0, 0.25555],
    "109": [0, 0.43056, 0.07671, 0, 0.81777],
    "110": [0, 0.43056, 0.07671, 0, 0.56222],
    "111": [0, 0.43056, 0.06312, 0, 0.51111],
    "112": [0.19444, 0.43056, 0.06312, 0, 0.51111],
    "113": [0.19444, 0.43056, 0.08847, 0, 0.46],
    "114": [0, 0.43056, 0.10764, 0, 0.42166],
    "115": [0, 0.43056, 0.08208, 0, 0.40889],
    "116": [0, 0.61508, 0.09486, 0, 0.33222],
    "117": [0, 0.43056, 0.07671, 0, 0.53666],
    "118": [0, 0.43056, 0.10764, 0, 0.46],
    "119": [0, 0.43056, 0.10764, 0, 0.66444],
    "120": [0, 0.43056, 0.12042, 0, 0.46389],
    "121": [0.19444, 0.43056, 0.08847, 0, 0.48555],
    "122": [0, 0.43056, 0.12292, 0, 0.40889],
    "126": [0.35, 0.31786, 0.11585, 0, 0.51111],
    "160": [0, 0, 0, 0, 0.25],
    "168": [0, 0.66786, 0.10474, 0, 0.51111],
    "176": [0, 0.69444, 0, 0, 0.83129],
    "184": [0.17014, 0, 0, 0, 0.46],
    "198": [0, 0.68333, 0.12028, 0, 0.88277],
    "216": [0.04861, 0.73194, 0.09403, 0, 0.76666],
    "223": [0.19444, 0.69444, 0.10514, 0, 0.53666],
    "230": [0, 0.43056, 0.07514, 0, 0.71555],
    "248": [0.09722, 0.52778, 0.09194, 0, 0.51111],
    "338": [0, 0.68333, 0.12028, 0, 0.98499],
    "339": [0, 0.43056, 0.07514, 0, 0.71555],
    "710": [0, 0.69444, 0.06646, 0, 0.51111],
    "711": [0, 0.62847, 0.08295, 0, 0.51111],
    "713": [0, 0.56167, 0.10333, 0, 0.51111],
    "714": [0, 0.69444, 0.09694, 0, 0.51111],
    "715": [0, 0.69444, 0, 0, 0.51111],
    "728": [0, 0.69444, 0.10806, 0, 0.51111],
    "729": [0, 0.66786, 0.11752, 0, 0.30667],
    "730": [0, 0.69444, 0, 0, 0.83129],
    "732": [0, 0.66786, 0.11585, 0, 0.51111],
    "733": [0, 0.69444, 0.1225, 0, 0.51111],
    "915": [0, 0.68333, 0.13305, 0, 0.62722],
    "916": [0, 0.68333, 0, 0, 0.81777],
    "920": [0, 0.68333, 0.09403, 0, 0.76666],
    "923": [0, 0.68333, 0, 0, 0.69222],
    "926": [0, 0.68333, 0.15294, 0, 0.66444],
    "928": [0, 0.68333, 0.16389, 0, 0.74333],
    "931": [0, 0.68333, 0.12028, 0, 0.71555],
    "933": [0, 0.68333, 0.11111, 0, 0.76666],
    "934": [0, 0.68333, 0.05986, 0, 0.71555],
    "936": [0, 0.68333, 0.11111, 0, 0.76666],
    "937": [0, 0.68333, 0.10257, 0, 0.71555],
    "8211": [0, 0.43056, 0.09208, 0, 0.51111],
    "8212": [0, 0.43056, 0.09208, 0, 1.02222],
    "8216": [0, 0.69444, 0.12417, 0, 0.30667],
    "8217": [0, 0.69444, 0.12417, 0, 0.30667],
    "8220": [0, 0.69444, 0.1685, 0, 0.51444],
    "8221": [0, 0.69444, 0.06961, 0, 0.51444],
    "8463": [0, 0.68889, 0, 0, 0.54028]
  },
  "Main-Regular": {
    "32": [0, 0, 0, 0, 0.25],
    "33": [0, 0.69444, 0, 0, 0.27778],
    "34": [0, 0.69444, 0, 0, 0.5],
    "35": [0.19444, 0.69444, 0, 0, 0.83334],
    "36": [0.05556, 0.75, 0, 0, 0.5],
    "37": [0.05556, 0.75, 0, 0, 0.83334],
    "38": [0, 0.69444, 0, 0, 0.77778],
    "39": [0, 0.69444, 0, 0, 0.27778],
    "40": [0.25, 0.75, 0, 0, 0.38889],
    "41": [0.25, 0.75, 0, 0, 0.38889],
    "42": [0, 0.75, 0, 0, 0.5],
    "43": [0.08333, 0.58333, 0, 0, 0.77778],
    "44": [0.19444, 0.10556, 0, 0, 0.27778],
    "45": [0, 0.43056, 0, 0, 0.33333],
    "46": [0, 0.10556, 0, 0, 0.27778],
    "47": [0.25, 0.75, 0, 0, 0.5],
    "48": [0, 0.64444, 0, 0, 0.5],
    "49": [0, 0.64444, 0, 0, 0.5],
    "50": [0, 0.64444, 0, 0, 0.5],
    "51": [0, 0.64444, 0, 0, 0.5],
    "52": [0, 0.64444, 0, 0, 0.5],
    "53": [0, 0.64444, 0, 0, 0.5],
    "54": [0, 0.64444, 0, 0, 0.5],
    "55": [0, 0.64444, 0, 0, 0.5],
    "56": [0, 0.64444, 0, 0, 0.5],
    "57": [0, 0.64444, 0, 0, 0.5],
    "58": [0, 0.43056, 0, 0, 0.27778],
    "59": [0.19444, 0.43056, 0, 0, 0.27778],
    "60": [0.0391, 0.5391, 0, 0, 0.77778],
    "61": [-0.13313, 0.36687, 0, 0, 0.77778],
    "62": [0.0391, 0.5391, 0, 0, 0.77778],
    "63": [0, 0.69444, 0, 0, 0.47222],
    "64": [0, 0.69444, 0, 0, 0.77778],
    "65": [0, 0.68333, 0, 0, 0.75],
    "66": [0, 0.68333, 0, 0, 0.70834],
    "67": [0, 0.68333, 0, 0, 0.72222],
    "68": [0, 0.68333, 0, 0, 0.76389],
    "69": [0, 0.68333, 0, 0, 0.68056],
    "70": [0, 0.68333, 0, 0, 0.65278],
    "71": [0, 0.68333, 0, 0, 0.78472],
    "72": [0, 0.68333, 0, 0, 0.75],
    "73": [0, 0.68333, 0, 0, 0.36111],
    "74": [0, 0.68333, 0, 0, 0.51389],
    "75": [0, 0.68333, 0, 0, 0.77778],
    "76": [0, 0.68333, 0, 0, 0.625],
    "77": [0, 0.68333, 0, 0, 0.91667],
    "78": [0, 0.68333, 0, 0, 0.75],
    "79": [0, 0.68333, 0, 0, 0.77778],
    "80": [0, 0.68333, 0, 0, 0.68056],
    "81": [0.19444, 0.68333, 0, 0, 0.77778],
    "82": [0, 0.68333, 0, 0, 0.73611],
    "83": [0, 0.68333, 0, 0, 0.55556],
    "84": [0, 0.68333, 0, 0, 0.72222],
    "85": [0, 0.68333, 0, 0, 0.75],
    "86": [0, 0.68333, 0.01389, 0, 0.75],
    "87": [0, 0.68333, 0.01389, 0, 1.02778],
    "88": [0, 0.68333, 0, 0, 0.75],
    "89": [0, 0.68333, 0.025, 0, 0.75],
    "90": [0, 0.68333, 0, 0, 0.61111],
    "91": [0.25, 0.75, 0, 0, 0.27778],
    "92": [0.25, 0.75, 0, 0, 0.5],
    "93": [0.25, 0.75, 0, 0, 0.27778],
    "94": [0, 0.69444, 0, 0, 0.5],
    "95": [0.31, 0.12056, 0.02778, 0, 0.5],
    "97": [0, 0.43056, 0, 0, 0.5],
    "98": [0, 0.69444, 0, 0, 0.55556],
    "99": [0, 0.43056, 0, 0, 0.44445],
    "100": [0, 0.69444, 0, 0, 0.55556],
    "101": [0, 0.43056, 0, 0, 0.44445],
    "102": [0, 0.69444, 0.07778, 0, 0.30556],
    "103": [0.19444, 0.43056, 0.01389, 0, 0.5],
    "104": [0, 0.69444, 0, 0, 0.55556],
    "105": [0, 0.66786, 0, 0, 0.27778],
    "106": [0.19444, 0.66786, 0, 0, 0.30556],
    "107": [0, 0.69444, 0, 0, 0.52778],
    "108": [0, 0.69444, 0, 0, 0.27778],
    "109": [0, 0.43056, 0, 0, 0.83334],
    "110": [0, 0.43056, 0, 0, 0.55556],
    "111": [0, 0.43056, 0, 0, 0.5],
    "112": [0.19444, 0.43056, 0, 0, 0.55556],
    "113": [0.19444, 0.43056, 0, 0, 0.52778],
    "114": [0, 0.43056, 0, 0, 0.39167],
    "115": [0, 0.43056, 0, 0, 0.39445],
    "116": [0, 0.61508, 0, 0, 0.38889],
    "117": [0, 0.43056, 0, 0, 0.55556],
    "118": [0, 0.43056, 0.01389, 0, 0.52778],
    "119": [0, 0.43056, 0.01389, 0, 0.72222],
    "120": [0, 0.43056, 0, 0, 0.52778],
    "121": [0.19444, 0.43056, 0.01389, 0, 0.52778],
    "122": [0, 0.43056, 0, 0, 0.44445],
    "123": [0.25, 0.75, 0, 0, 0.5],
    "124": [0.25, 0.75, 0, 0, 0.27778],
    "125": [0.25, 0.75, 0, 0, 0.5],
    "126": [0.35, 0.31786, 0, 0, 0.5],
    "160": [0, 0, 0, 0, 0.25],
    "163": [0, 0.69444, 0, 0, 0.76909],
    "167": [0.19444, 0.69444, 0, 0, 0.44445],
    "168": [0, 0.66786, 0, 0, 0.5],
    "172": [0, 0.43056, 0, 0, 0.66667],
    "176": [0, 0.69444, 0, 0, 0.75],
    "177": [0.08333, 0.58333, 0, 0, 0.77778],
    "182": [0.19444, 0.69444, 0, 0, 0.61111],
    "184": [0.17014, 0, 0, 0, 0.44445],
    "198": [0, 0.68333, 0, 0, 0.90278],
    "215": [0.08333, 0.58333, 0, 0, 0.77778],
    "216": [0.04861, 0.73194, 0, 0, 0.77778],
    "223": [0, 0.69444, 0, 0, 0.5],
    "230": [0, 0.43056, 0, 0, 0.72222],
    "247": [0.08333, 0.58333, 0, 0, 0.77778],
    "248": [0.09722, 0.52778, 0, 0, 0.5],
    "305": [0, 0.43056, 0, 0, 0.27778],
    "338": [0, 0.68333, 0, 0, 1.01389],
    "339": [0, 0.43056, 0, 0, 0.77778],
    "567": [0.19444, 0.43056, 0, 0, 0.30556],
    "710": [0, 0.69444, 0, 0, 0.5],
    "711": [0, 0.62847, 0, 0, 0.5],
    "713": [0, 0.56778, 0, 0, 0.5],
    "714": [0, 0.69444, 0, 0, 0.5],
    "715": [0, 0.69444, 0, 0, 0.5],
    "728": [0, 0.69444, 0, 0, 0.5],
    "729": [0, 0.66786, 0, 0, 0.27778],
    "730": [0, 0.69444, 0, 0, 0.75],
    "732": [0, 0.66786, 0, 0, 0.5],
    "733": [0, 0.69444, 0, 0, 0.5],
    "915": [0, 0.68333, 0, 0, 0.625],
    "916": [0, 0.68333, 0, 0, 0.83334],
    "920": [0, 0.68333, 0, 0, 0.77778],
    "923": [0, 0.68333, 0, 0, 0.69445],
    "926": [0, 0.68333, 0, 0, 0.66667],
    "928": [0, 0.68333, 0, 0, 0.75],
    "931": [0, 0.68333, 0, 0, 0.72222],
    "933": [0, 0.68333, 0, 0, 0.77778],
    "934": [0, 0.68333, 0, 0, 0.72222],
    "936": [0, 0.68333, 0, 0, 0.77778],
    "937": [0, 0.68333, 0, 0, 0.72222],
    "8211": [0, 0.43056, 0.02778, 0, 0.5],
    "8212": [0, 0.43056, 0.02778, 0, 1],
    "8216": [0, 0.69444, 0, 0, 0.27778],
    "8217": [0, 0.69444, 0, 0, 0.27778],
    "8220": [0, 0.69444, 0, 0, 0.5],
    "8221": [0, 0.69444, 0, 0, 0.5],
    "8224": [0.19444, 0.69444, 0, 0, 0.44445],
    "8225": [0.19444, 0.69444, 0, 0, 0.44445],
    "8230": [0, 0.123, 0, 0, 1.172],
    "8242": [0, 0.55556, 0, 0, 0.275],
    "8407": [0, 0.71444, 0.15382, 0, 0.5],
    "8463": [0, 0.68889, 0, 0, 0.54028],
    "8465": [0, 0.69444, 0, 0, 0.72222],
    "8467": [0, 0.69444, 0, 0.11111, 0.41667],
    "8472": [0.19444, 0.43056, 0, 0.11111, 0.63646],
    "8476": [0, 0.69444, 0, 0, 0.72222],
    "8501": [0, 0.69444, 0, 0, 0.61111],
    "8592": [-0.13313, 0.36687, 0, 0, 1],
    "8593": [0.19444, 0.69444, 0, 0, 0.5],
    "8594": [-0.13313, 0.36687, 0, 0, 1],
    "8595": [0.19444, 0.69444, 0, 0, 0.5],
    "8596": [-0.13313, 0.36687, 0, 0, 1],
    "8597": [0.25, 0.75, 0, 0, 0.5],
    "8598": [0.19444, 0.69444, 0, 0, 1],
    "8599": [0.19444, 0.69444, 0, 0, 1],
    "8600": [0.19444, 0.69444, 0, 0, 1],
    "8601": [0.19444, 0.69444, 0, 0, 1],
    "8614": [0.011, 0.511, 0, 0, 1],
    "8617": [0.011, 0.511, 0, 0, 1.126],
    "8618": [0.011, 0.511, 0, 0, 1.126],
    "8636": [-0.13313, 0.36687, 0, 0, 1],
    "8637": [-0.13313, 0.36687, 0, 0, 1],
    "8640": [-0.13313, 0.36687, 0, 0, 1],
    "8641": [-0.13313, 0.36687, 0, 0, 1],
    "8652": [0.011, 0.671, 0, 0, 1],
    "8656": [-0.13313, 0.36687, 0, 0, 1],
    "8657": [0.19444, 0.69444, 0, 0, 0.61111],
    "8658": [-0.13313, 0.36687, 0, 0, 1],
    "8659": [0.19444, 0.69444, 0, 0, 0.61111],
    "8660": [-0.13313, 0.36687, 0, 0, 1],
    "8661": [0.25, 0.75, 0, 0, 0.61111],
    "8704": [0, 0.69444, 0, 0, 0.55556],
    "8706": [0, 0.69444, 0.05556, 0.08334, 0.5309],
    "8707": [0, 0.69444, 0, 0, 0.55556],
    "8709": [0.05556, 0.75, 0, 0, 0.5],
    "8711": [0, 0.68333, 0, 0, 0.83334],
    "8712": [0.0391, 0.5391, 0, 0, 0.66667],
    "8715": [0.0391, 0.5391, 0, 0, 0.66667],
    "8722": [0.08333, 0.58333, 0, 0, 0.77778],
    "8723": [0.08333, 0.58333, 0, 0, 0.77778],
    "8725": [0.25, 0.75, 0, 0, 0.5],
    "8726": [0.25, 0.75, 0, 0, 0.5],
    "8727": [-0.03472, 0.46528, 0, 0, 0.5],
    "8728": [-0.05555, 0.44445, 0, 0, 0.5],
    "8729": [-0.05555, 0.44445, 0, 0, 0.5],
    "8730": [0.2, 0.8, 0, 0, 0.83334],
    "8733": [0, 0.43056, 0, 0, 0.77778],
    "8734": [0, 0.43056, 0, 0, 1],
    "8736": [0, 0.69224, 0, 0, 0.72222],
    "8739": [0.25, 0.75, 0, 0, 0.27778],
    "8741": [0.25, 0.75, 0, 0, 0.5],
    "8743": [0, 0.55556, 0, 0, 0.66667],
    "8744": [0, 0.55556, 0, 0, 0.66667],
    "8745": [0, 0.55556, 0, 0, 0.66667],
    "8746": [0, 0.55556, 0, 0, 0.66667],
    "8747": [0.19444, 0.69444, 0.11111, 0, 0.41667],
    "8764": [-0.13313, 0.36687, 0, 0, 0.77778],
    "8768": [0.19444, 0.69444, 0, 0, 0.27778],
    "8771": [-0.03625, 0.46375, 0, 0, 0.77778],
    "8773": [-0.022, 0.589, 0, 0, 0.778],
    "8776": [-0.01688, 0.48312, 0, 0, 0.77778],
    "8781": [-0.03625, 0.46375, 0, 0, 0.77778],
    "8784": [-0.133, 0.673, 0, 0, 0.778],
    "8801": [-0.03625, 0.46375, 0, 0, 0.77778],
    "8804": [0.13597, 0.63597, 0, 0, 0.77778],
    "8805": [0.13597, 0.63597, 0, 0, 0.77778],
    "8810": [0.0391, 0.5391, 0, 0, 1],
    "8811": [0.0391, 0.5391, 0, 0, 1],
    "8826": [0.0391, 0.5391, 0, 0, 0.77778],
    "8827": [0.0391, 0.5391, 0, 0, 0.77778],
    "8834": [0.0391, 0.5391, 0, 0, 0.77778],
    "8835": [0.0391, 0.5391, 0, 0, 0.77778],
    "8838": [0.13597, 0.63597, 0, 0, 0.77778],
    "8839": [0.13597, 0.63597, 0, 0, 0.77778],
    "8846": [0, 0.55556, 0, 0, 0.66667],
    "8849": [0.13597, 0.63597, 0, 0, 0.77778],
    "8850": [0.13597, 0.63597, 0, 0, 0.77778],
    "8851": [0, 0.55556, 0, 0, 0.66667],
    "8852": [0, 0.55556, 0, 0, 0.66667],
    "8853": [0.08333, 0.58333, 0, 0, 0.77778],
    "8854": [0.08333, 0.58333, 0, 0, 0.77778],
    "8855": [0.08333, 0.58333, 0, 0, 0.77778],
    "8856": [0.08333, 0.58333, 0, 0, 0.77778],
    "8857": [0.08333, 0.58333, 0, 0, 0.77778],
    "8866": [0, 0.69444, 0, 0, 0.61111],
    "8867": [0, 0.69444, 0, 0, 0.61111],
    "8868": [0, 0.69444, 0, 0, 0.77778],
    "8869": [0, 0.69444, 0, 0, 0.77778],
    "8872": [0.249, 0.75, 0, 0, 0.867],
    "8900": [-0.05555, 0.44445, 0, 0, 0.5],
    "8901": [-0.05555, 0.44445, 0, 0, 0.27778],
    "8902": [-0.03472, 0.46528, 0, 0, 0.5],
    "8904": [5e-3, 0.505, 0, 0, 0.9],
    "8942": [0.03, 0.903, 0, 0, 0.278],
    "8943": [-0.19, 0.313, 0, 0, 1.172],
    "8945": [-0.1, 0.823, 0, 0, 1.282],
    "8968": [0.25, 0.75, 0, 0, 0.44445],
    "8969": [0.25, 0.75, 0, 0, 0.44445],
    "8970": [0.25, 0.75, 0, 0, 0.44445],
    "8971": [0.25, 0.75, 0, 0, 0.44445],
    "8994": [-0.14236, 0.35764, 0, 0, 1],
    "8995": [-0.14236, 0.35764, 0, 0, 1],
    "9136": [0.244, 0.744, 0, 0, 0.412],
    "9137": [0.244, 0.745, 0, 0, 0.412],
    "9651": [0.19444, 0.69444, 0, 0, 0.88889],
    "9657": [-0.03472, 0.46528, 0, 0, 0.5],
    "9661": [0.19444, 0.69444, 0, 0, 0.88889],
    "9667": [-0.03472, 0.46528, 0, 0, 0.5],
    "9711": [0.19444, 0.69444, 0, 0, 1],
    "9824": [0.12963, 0.69444, 0, 0, 0.77778],
    "9825": [0.12963, 0.69444, 0, 0, 0.77778],
    "9826": [0.12963, 0.69444, 0, 0, 0.77778],
    "9827": [0.12963, 0.69444, 0, 0, 0.77778],
    "9837": [0, 0.75, 0, 0, 0.38889],
    "9838": [0.19444, 0.69444, 0, 0, 0.38889],
    "9839": [0.19444, 0.69444, 0, 0, 0.38889],
    "10216": [0.25, 0.75, 0, 0, 0.38889],
    "10217": [0.25, 0.75, 0, 0, 0.38889],
    "10222": [0.244, 0.744, 0, 0, 0.412],
    "10223": [0.244, 0.745, 0, 0, 0.412],
    "10229": [0.011, 0.511, 0, 0, 1.609],
    "10230": [0.011, 0.511, 0, 0, 1.638],
    "10231": [0.011, 0.511, 0, 0, 1.859],
    "10232": [0.024, 0.525, 0, 0, 1.609],
    "10233": [0.024, 0.525, 0, 0, 1.638],
    "10234": [0.024, 0.525, 0, 0, 1.858],
    "10236": [0.011, 0.511, 0, 0, 1.638],
    "10815": [0, 0.68333, 0, 0, 0.75],
    "10927": [0.13597, 0.63597, 0, 0, 0.77778],
    "10928": [0.13597, 0.63597, 0, 0, 0.77778],
    "57376": [0.19444, 0.69444, 0, 0, 0]
  },
  "Math-BoldItalic": {
    "32": [0, 0, 0, 0, 0.25],
    "48": [0, 0.44444, 0, 0, 0.575],
    "49": [0, 0.44444, 0, 0, 0.575],
    "50": [0, 0.44444, 0, 0, 0.575],
    "51": [0.19444, 0.44444, 0, 0, 0.575],
    "52": [0.19444, 0.44444, 0, 0, 0.575],
    "53": [0.19444, 0.44444, 0, 0, 0.575],
    "54": [0, 0.64444, 0, 0, 0.575],
    "55": [0.19444, 0.44444, 0, 0, 0.575],
    "56": [0, 0.64444, 0, 0, 0.575],
    "57": [0.19444, 0.44444, 0, 0, 0.575],
    "65": [0, 0.68611, 0, 0, 0.86944],
    "66": [0, 0.68611, 0.04835, 0, 0.8664],
    "67": [0, 0.68611, 0.06979, 0, 0.81694],
    "68": [0, 0.68611, 0.03194, 0, 0.93812],
    "69": [0, 0.68611, 0.05451, 0, 0.81007],
    "70": [0, 0.68611, 0.15972, 0, 0.68889],
    "71": [0, 0.68611, 0, 0, 0.88673],
    "72": [0, 0.68611, 0.08229, 0, 0.98229],
    "73": [0, 0.68611, 0.07778, 0, 0.51111],
    "74": [0, 0.68611, 0.10069, 0, 0.63125],
    "75": [0, 0.68611, 0.06979, 0, 0.97118],
    "76": [0, 0.68611, 0, 0, 0.75555],
    "77": [0, 0.68611, 0.11424, 0, 1.14201],
    "78": [0, 0.68611, 0.11424, 0, 0.95034],
    "79": [0, 0.68611, 0.03194, 0, 0.83666],
    "80": [0, 0.68611, 0.15972, 0, 0.72309],
    "81": [0.19444, 0.68611, 0, 0, 0.86861],
    "82": [0, 0.68611, 421e-5, 0, 0.87235],
    "83": [0, 0.68611, 0.05382, 0, 0.69271],
    "84": [0, 0.68611, 0.15972, 0, 0.63663],
    "85": [0, 0.68611, 0.11424, 0, 0.80027],
    "86": [0, 0.68611, 0.25555, 0, 0.67778],
    "87": [0, 0.68611, 0.15972, 0, 1.09305],
    "88": [0, 0.68611, 0.07778, 0, 0.94722],
    "89": [0, 0.68611, 0.25555, 0, 0.67458],
    "90": [0, 0.68611, 0.06979, 0, 0.77257],
    "97": [0, 0.44444, 0, 0, 0.63287],
    "98": [0, 0.69444, 0, 0, 0.52083],
    "99": [0, 0.44444, 0, 0, 0.51342],
    "100": [0, 0.69444, 0, 0, 0.60972],
    "101": [0, 0.44444, 0, 0, 0.55361],
    "102": [0.19444, 0.69444, 0.11042, 0, 0.56806],
    "103": [0.19444, 0.44444, 0.03704, 0, 0.5449],
    "104": [0, 0.69444, 0, 0, 0.66759],
    "105": [0, 0.69326, 0, 0, 0.4048],
    "106": [0.19444, 0.69326, 0.0622, 0, 0.47083],
    "107": [0, 0.69444, 0.01852, 0, 0.6037],
    "108": [0, 0.69444, 88e-4, 0, 0.34815],
    "109": [0, 0.44444, 0, 0, 1.0324],
    "110": [0, 0.44444, 0, 0, 0.71296],
    "111": [0, 0.44444, 0, 0, 0.58472],
    "112": [0.19444, 0.44444, 0, 0, 0.60092],
    "113": [0.19444, 0.44444, 0.03704, 0, 0.54213],
    "114": [0, 0.44444, 0.03194, 0, 0.5287],
    "115": [0, 0.44444, 0, 0, 0.53125],
    "116": [0, 0.63492, 0, 0, 0.41528],
    "117": [0, 0.44444, 0, 0, 0.68102],
    "118": [0, 0.44444, 0.03704, 0, 0.56666],
    "119": [0, 0.44444, 0.02778, 0, 0.83148],
    "120": [0, 0.44444, 0, 0, 0.65903],
    "121": [0.19444, 0.44444, 0.03704, 0, 0.59028],
    "122": [0, 0.44444, 0.04213, 0, 0.55509],
    "160": [0, 0, 0, 0, 0.25],
    "915": [0, 0.68611, 0.15972, 0, 0.65694],
    "916": [0, 0.68611, 0, 0, 0.95833],
    "920": [0, 0.68611, 0.03194, 0, 0.86722],
    "923": [0, 0.68611, 0, 0, 0.80555],
    "926": [0, 0.68611, 0.07458, 0, 0.84125],
    "928": [0, 0.68611, 0.08229, 0, 0.98229],
    "931": [0, 0.68611, 0.05451, 0, 0.88507],
    "933": [0, 0.68611, 0.15972, 0, 0.67083],
    "934": [0, 0.68611, 0, 0, 0.76666],
    "936": [0, 0.68611, 0.11653, 0, 0.71402],
    "937": [0, 0.68611, 0.04835, 0, 0.8789],
    "945": [0, 0.44444, 0, 0, 0.76064],
    "946": [0.19444, 0.69444, 0.03403, 0, 0.65972],
    "947": [0.19444, 0.44444, 0.06389, 0, 0.59003],
    "948": [0, 0.69444, 0.03819, 0, 0.52222],
    "949": [0, 0.44444, 0, 0, 0.52882],
    "950": [0.19444, 0.69444, 0.06215, 0, 0.50833],
    "951": [0.19444, 0.44444, 0.03704, 0, 0.6],
    "952": [0, 0.69444, 0.03194, 0, 0.5618],
    "953": [0, 0.44444, 0, 0, 0.41204],
    "954": [0, 0.44444, 0, 0, 0.66759],
    "955": [0, 0.69444, 0, 0, 0.67083],
    "956": [0.19444, 0.44444, 0, 0, 0.70787],
    "957": [0, 0.44444, 0.06898, 0, 0.57685],
    "958": [0.19444, 0.69444, 0.03021, 0, 0.50833],
    "959": [0, 0.44444, 0, 0, 0.58472],
    "960": [0, 0.44444, 0.03704, 0, 0.68241],
    "961": [0.19444, 0.44444, 0, 0, 0.6118],
    "962": [0.09722, 0.44444, 0.07917, 0, 0.42361],
    "963": [0, 0.44444, 0.03704, 0, 0.68588],
    "964": [0, 0.44444, 0.13472, 0, 0.52083],
    "965": [0, 0.44444, 0.03704, 0, 0.63055],
    "966": [0.19444, 0.44444, 0, 0, 0.74722],
    "967": [0.19444, 0.44444, 0, 0, 0.71805],
    "968": [0.19444, 0.69444, 0.03704, 0, 0.75833],
    "969": [0, 0.44444, 0.03704, 0, 0.71782],
    "977": [0, 0.69444, 0, 0, 0.69155],
    "981": [0.19444, 0.69444, 0, 0, 0.7125],
    "982": [0, 0.44444, 0.03194, 0, 0.975],
    "1009": [0.19444, 0.44444, 0, 0, 0.6118],
    "1013": [0, 0.44444, 0, 0, 0.48333],
    "57649": [0, 0.44444, 0, 0, 0.39352],
    "57911": [0.19444, 0.44444, 0, 0, 0.43889]
  },
  "Math-Italic": {
    "32": [0, 0, 0, 0, 0.25],
    "48": [0, 0.43056, 0, 0, 0.5],
    "49": [0, 0.43056, 0, 0, 0.5],
    "50": [0, 0.43056, 0, 0, 0.5],
    "51": [0.19444, 0.43056, 0, 0, 0.5],
    "52": [0.19444, 0.43056, 0, 0, 0.5],
    "53": [0.19444, 0.43056, 0, 0, 0.5],
    "54": [0, 0.64444, 0, 0, 0.5],
    "55": [0.19444, 0.43056, 0, 0, 0.5],
    "56": [0, 0.64444, 0, 0, 0.5],
    "57": [0.19444, 0.43056, 0, 0, 0.5],
    "65": [0, 0.68333, 0, 0.13889, 0.75],
    "66": [0, 0.68333, 0.05017, 0.08334, 0.75851],
    "67": [0, 0.68333, 0.07153, 0.08334, 0.71472],
    "68": [0, 0.68333, 0.02778, 0.05556, 0.82792],
    "69": [0, 0.68333, 0.05764, 0.08334, 0.7382],
    "70": [0, 0.68333, 0.13889, 0.08334, 0.64306],
    "71": [0, 0.68333, 0, 0.08334, 0.78625],
    "72": [0, 0.68333, 0.08125, 0.05556, 0.83125],
    "73": [0, 0.68333, 0.07847, 0.11111, 0.43958],
    "74": [0, 0.68333, 0.09618, 0.16667, 0.55451],
    "75": [0, 0.68333, 0.07153, 0.05556, 0.84931],
    "76": [0, 0.68333, 0, 0.02778, 0.68056],
    "77": [0, 0.68333, 0.10903, 0.08334, 0.97014],
    "78": [0, 0.68333, 0.10903, 0.08334, 0.80347],
    "79": [0, 0.68333, 0.02778, 0.08334, 0.76278],
    "80": [0, 0.68333, 0.13889, 0.08334, 0.64201],
    "81": [0.19444, 0.68333, 0, 0.08334, 0.79056],
    "82": [0, 0.68333, 773e-5, 0.08334, 0.75929],
    "83": [0, 0.68333, 0.05764, 0.08334, 0.6132],
    "84": [0, 0.68333, 0.13889, 0.08334, 0.58438],
    "85": [0, 0.68333, 0.10903, 0.02778, 0.68278],
    "86": [0, 0.68333, 0.22222, 0, 0.58333],
    "87": [0, 0.68333, 0.13889, 0, 0.94445],
    "88": [0, 0.68333, 0.07847, 0.08334, 0.82847],
    "89": [0, 0.68333, 0.22222, 0, 0.58056],
    "90": [0, 0.68333, 0.07153, 0.08334, 0.68264],
    "97": [0, 0.43056, 0, 0, 0.52859],
    "98": [0, 0.69444, 0, 0, 0.42917],
    "99": [0, 0.43056, 0, 0.05556, 0.43276],
    "100": [0, 0.69444, 0, 0.16667, 0.52049],
    "101": [0, 0.43056, 0, 0.05556, 0.46563],
    "102": [0.19444, 0.69444, 0.10764, 0.16667, 0.48959],
    "103": [0.19444, 0.43056, 0.03588, 0.02778, 0.47697],
    "104": [0, 0.69444, 0, 0, 0.57616],
    "105": [0, 0.65952, 0, 0, 0.34451],
    "106": [0.19444, 0.65952, 0.05724, 0, 0.41181],
    "107": [0, 0.69444, 0.03148, 0, 0.5206],
    "108": [0, 0.69444, 0.01968, 0.08334, 0.29838],
    "109": [0, 0.43056, 0, 0, 0.87801],
    "110": [0, 0.43056, 0, 0, 0.60023],
    "111": [0, 0.43056, 0, 0.05556, 0.48472],
    "112": [0.19444, 0.43056, 0, 0.08334, 0.50313],
    "113": [0.19444, 0.43056, 0.03588, 0.08334, 0.44641],
    "114": [0, 0.43056, 0.02778, 0.05556, 0.45116],
    "115": [0, 0.43056, 0, 0.05556, 0.46875],
    "116": [0, 0.61508, 0, 0.08334, 0.36111],
    "117": [0, 0.43056, 0, 0.02778, 0.57246],
    "118": [0, 0.43056, 0.03588, 0.02778, 0.48472],
    "119": [0, 0.43056, 0.02691, 0.08334, 0.71592],
    "120": [0, 0.43056, 0, 0.02778, 0.57153],
    "121": [0.19444, 0.43056, 0.03588, 0.05556, 0.49028],
    "122": [0, 0.43056, 0.04398, 0.05556, 0.46505],
    "160": [0, 0, 0, 0, 0.25],
    "915": [0, 0.68333, 0.13889, 0.08334, 0.61528],
    "916": [0, 0.68333, 0, 0.16667, 0.83334],
    "920": [0, 0.68333, 0.02778, 0.08334, 0.76278],
    "923": [0, 0.68333, 0, 0.16667, 0.69445],
    "926": [0, 0.68333, 0.07569, 0.08334, 0.74236],
    "928": [0, 0.68333, 0.08125, 0.05556, 0.83125],
    "931": [0, 0.68333, 0.05764, 0.08334, 0.77986],
    "933": [0, 0.68333, 0.13889, 0.05556, 0.58333],
    "934": [0, 0.68333, 0, 0.08334, 0.66667],
    "936": [0, 0.68333, 0.11, 0.05556, 0.61222],
    "937": [0, 0.68333, 0.05017, 0.08334, 0.7724],
    "945": [0, 0.43056, 37e-4, 0.02778, 0.6397],
    "946": [0.19444, 0.69444, 0.05278, 0.08334, 0.56563],
    "947": [0.19444, 0.43056, 0.05556, 0, 0.51773],
    "948": [0, 0.69444, 0.03785, 0.05556, 0.44444],
    "949": [0, 0.43056, 0, 0.08334, 0.46632],
    "950": [0.19444, 0.69444, 0.07378, 0.08334, 0.4375],
    "951": [0.19444, 0.43056, 0.03588, 0.05556, 0.49653],
    "952": [0, 0.69444, 0.02778, 0.08334, 0.46944],
    "953": [0, 0.43056, 0, 0.05556, 0.35394],
    "954": [0, 0.43056, 0, 0, 0.57616],
    "955": [0, 0.69444, 0, 0, 0.58334],
    "956": [0.19444, 0.43056, 0, 0.02778, 0.60255],
    "957": [0, 0.43056, 0.06366, 0.02778, 0.49398],
    "958": [0.19444, 0.69444, 0.04601, 0.11111, 0.4375],
    "959": [0, 0.43056, 0, 0.05556, 0.48472],
    "960": [0, 0.43056, 0.03588, 0, 0.57003],
    "961": [0.19444, 0.43056, 0, 0.08334, 0.51702],
    "962": [0.09722, 0.43056, 0.07986, 0.08334, 0.36285],
    "963": [0, 0.43056, 0.03588, 0, 0.57141],
    "964": [0, 0.43056, 0.1132, 0.02778, 0.43715],
    "965": [0, 0.43056, 0.03588, 0.02778, 0.54028],
    "966": [0.19444, 0.43056, 0, 0.08334, 0.65417],
    "967": [0.19444, 0.43056, 0, 0.05556, 0.62569],
    "968": [0.19444, 0.69444, 0.03588, 0.11111, 0.65139],
    "969": [0, 0.43056, 0.03588, 0, 0.62245],
    "977": [0, 0.69444, 0, 0.08334, 0.59144],
    "981": [0.19444, 0.69444, 0, 0.08334, 0.59583],
    "982": [0, 0.43056, 0.02778, 0, 0.82813],
    "1009": [0.19444, 0.43056, 0, 0.08334, 0.51702],
    "1013": [0, 0.43056, 0, 0.05556, 0.4059],
    "57649": [0, 0.43056, 0, 0.02778, 0.32246],
    "57911": [0.19444, 0.43056, 0, 0.08334, 0.38403]
  },
  "SansSerif-Bold": {
    "32": [0, 0, 0, 0, 0.25],
    "33": [0, 0.69444, 0, 0, 0.36667],
    "34": [0, 0.69444, 0, 0, 0.55834],
    "35": [0.19444, 0.69444, 0, 0, 0.91667],
    "36": [0.05556, 0.75, 0, 0, 0.55],
    "37": [0.05556, 0.75, 0, 0, 1.02912],
    "38": [0, 0.69444, 0, 0, 0.83056],
    "39": [0, 0.69444, 0, 0, 0.30556],
    "40": [0.25, 0.75, 0, 0, 0.42778],
    "41": [0.25, 0.75, 0, 0, 0.42778],
    "42": [0, 0.75, 0, 0, 0.55],
    "43": [0.11667, 0.61667, 0, 0, 0.85556],
    "44": [0.10556, 0.13056, 0, 0, 0.30556],
    "45": [0, 0.45833, 0, 0, 0.36667],
    "46": [0, 0.13056, 0, 0, 0.30556],
    "47": [0.25, 0.75, 0, 0, 0.55],
    "48": [0, 0.69444, 0, 0, 0.55],
    "49": [0, 0.69444, 0, 0, 0.55],
    "50": [0, 0.69444, 0, 0, 0.55],
    "51": [0, 0.69444, 0, 0, 0.55],
    "52": [0, 0.69444, 0, 0, 0.55],
    "53": [0, 0.69444, 0, 0, 0.55],
    "54": [0, 0.69444, 0, 0, 0.55],
    "55": [0, 0.69444, 0, 0, 0.55],
    "56": [0, 0.69444, 0, 0, 0.55],
    "57": [0, 0.69444, 0, 0, 0.55],
    "58": [0, 0.45833, 0, 0, 0.30556],
    "59": [0.10556, 0.45833, 0, 0, 0.30556],
    "61": [-0.09375, 0.40625, 0, 0, 0.85556],
    "63": [0, 0.69444, 0, 0, 0.51945],
    "64": [0, 0.69444, 0, 0, 0.73334],
    "65": [0, 0.69444, 0, 0, 0.73334],
    "66": [0, 0.69444, 0, 0, 0.73334],
    "67": [0, 0.69444, 0, 0, 0.70278],
    "68": [0, 0.69444, 0, 0, 0.79445],
    "69": [0, 0.69444, 0, 0, 0.64167],
    "70": [0, 0.69444, 0, 0, 0.61111],
    "71": [0, 0.69444, 0, 0, 0.73334],
    "72": [0, 0.69444, 0, 0, 0.79445],
    "73": [0, 0.69444, 0, 0, 0.33056],
    "74": [0, 0.69444, 0, 0, 0.51945],
    "75": [0, 0.69444, 0, 0, 0.76389],
    "76": [0, 0.69444, 0, 0, 0.58056],
    "77": [0, 0.69444, 0, 0, 0.97778],
    "78": [0, 0.69444, 0, 0, 0.79445],
    "79": [0, 0.69444, 0, 0, 0.79445],
    "80": [0, 0.69444, 0, 0, 0.70278],
    "81": [0.10556, 0.69444, 0, 0, 0.79445],
    "82": [0, 0.69444, 0, 0, 0.70278],
    "83": [0, 0.69444, 0, 0, 0.61111],
    "84": [0, 0.69444, 0, 0, 0.73334],
    "85": [0, 0.69444, 0, 0, 0.76389],
    "86": [0, 0.69444, 0.01528, 0, 0.73334],
    "87": [0, 0.69444, 0.01528, 0, 1.03889],
    "88": [0, 0.69444, 0, 0, 0.73334],
    "89": [0, 0.69444, 0.0275, 0, 0.73334],
    "90": [0, 0.69444, 0, 0, 0.67223],
    "91": [0.25, 0.75, 0, 0, 0.34306],
    "93": [0.25, 0.75, 0, 0, 0.34306],
    "94": [0, 0.69444, 0, 0, 0.55],
    "95": [0.35, 0.10833, 0.03056, 0, 0.55],
    "97": [0, 0.45833, 0, 0, 0.525],
    "98": [0, 0.69444, 0, 0, 0.56111],
    "99": [0, 0.45833, 0, 0, 0.48889],
    "100": [0, 0.69444, 0, 0, 0.56111],
    "101": [0, 0.45833, 0, 0, 0.51111],
    "102": [0, 0.69444, 0.07639, 0, 0.33611],
    "103": [0.19444, 0.45833, 0.01528, 0, 0.55],
    "104": [0, 0.69444, 0, 0, 0.56111],
    "105": [0, 0.69444, 0, 0, 0.25556],
    "106": [0.19444, 0.69444, 0, 0, 0.28611],
    "107": [0, 0.69444, 0, 0, 0.53056],
    "108": [0, 0.69444, 0, 0, 0.25556],
    "109": [0, 0.45833, 0, 0, 0.86667],
    "110": [0, 0.45833, 0, 0, 0.56111],
    "111": [0, 0.45833, 0, 0, 0.55],
    "112": [0.19444, 0.45833, 0, 0, 0.56111],
    "113": [0.19444, 0.45833, 0, 0, 0.56111],
    "114": [0, 0.45833, 0.01528, 0, 0.37222],
    "115": [0, 0.45833, 0, 0, 0.42167],
    "116": [0, 0.58929, 0, 0, 0.40417],
    "117": [0, 0.45833, 0, 0, 0.56111],
    "118": [0, 0.45833, 0.01528, 0, 0.5],
    "119": [0, 0.45833, 0.01528, 0, 0.74445],
    "120": [0, 0.45833, 0, 0, 0.5],
    "121": [0.19444, 0.45833, 0.01528, 0, 0.5],
    "122": [0, 0.45833, 0, 0, 0.47639],
    "126": [0.35, 0.34444, 0, 0, 0.55],
    "160": [0, 0, 0, 0, 0.25],
    "168": [0, 0.69444, 0, 0, 0.55],
    "176": [0, 0.69444, 0, 0, 0.73334],
    "180": [0, 0.69444, 0, 0, 0.55],
    "184": [0.17014, 0, 0, 0, 0.48889],
    "305": [0, 0.45833, 0, 0, 0.25556],
    "567": [0.19444, 0.45833, 0, 0, 0.28611],
    "710": [0, 0.69444, 0, 0, 0.55],
    "711": [0, 0.63542, 0, 0, 0.55],
    "713": [0, 0.63778, 0, 0, 0.55],
    "728": [0, 0.69444, 0, 0, 0.55],
    "729": [0, 0.69444, 0, 0, 0.30556],
    "730": [0, 0.69444, 0, 0, 0.73334],
    "732": [0, 0.69444, 0, 0, 0.55],
    "733": [0, 0.69444, 0, 0, 0.55],
    "915": [0, 0.69444, 0, 0, 0.58056],
    "916": [0, 0.69444, 0, 0, 0.91667],
    "920": [0, 0.69444, 0, 0, 0.85556],
    "923": [0, 0.69444, 0, 0, 0.67223],
    "926": [0, 0.69444, 0, 0, 0.73334],
    "928": [0, 0.69444, 0, 0, 0.79445],
    "931": [0, 0.69444, 0, 0, 0.79445],
    "933": [0, 0.69444, 0, 0, 0.85556],
    "934": [0, 0.69444, 0, 0, 0.79445],
    "936": [0, 0.69444, 0, 0, 0.85556],
    "937": [0, 0.69444, 0, 0, 0.79445],
    "8211": [0, 0.45833, 0.03056, 0, 0.55],
    "8212": [0, 0.45833, 0.03056, 0, 1.10001],
    "8216": [0, 0.69444, 0, 0, 0.30556],
    "8217": [0, 0.69444, 0, 0, 0.30556],
    "8220": [0, 0.69444, 0, 0, 0.55834],
    "8221": [0, 0.69444, 0, 0, 0.55834]
  },
  "SansSerif-Italic": {
    "32": [0, 0, 0, 0, 0.25],
    "33": [0, 0.69444, 0.05733, 0, 0.31945],
    "34": [0, 0.69444, 316e-5, 0, 0.5],
    "35": [0.19444, 0.69444, 0.05087, 0, 0.83334],
    "36": [0.05556, 0.75, 0.11156, 0, 0.5],
    "37": [0.05556, 0.75, 0.03126, 0, 0.83334],
    "38": [0, 0.69444, 0.03058, 0, 0.75834],
    "39": [0, 0.69444, 0.07816, 0, 0.27778],
    "40": [0.25, 0.75, 0.13164, 0, 0.38889],
    "41": [0.25, 0.75, 0.02536, 0, 0.38889],
    "42": [0, 0.75, 0.11775, 0, 0.5],
    "43": [0.08333, 0.58333, 0.02536, 0, 0.77778],
    "44": [0.125, 0.08333, 0, 0, 0.27778],
    "45": [0, 0.44444, 0.01946, 0, 0.33333],
    "46": [0, 0.08333, 0, 0, 0.27778],
    "47": [0.25, 0.75, 0.13164, 0, 0.5],
    "48": [0, 0.65556, 0.11156, 0, 0.5],
    "49": [0, 0.65556, 0.11156, 0, 0.5],
    "50": [0, 0.65556, 0.11156, 0, 0.5],
    "51": [0, 0.65556, 0.11156, 0, 0.5],
    "52": [0, 0.65556, 0.11156, 0, 0.5],
    "53": [0, 0.65556, 0.11156, 0, 0.5],
    "54": [0, 0.65556, 0.11156, 0, 0.5],
    "55": [0, 0.65556, 0.11156, 0, 0.5],
    "56": [0, 0.65556, 0.11156, 0, 0.5],
    "57": [0, 0.65556, 0.11156, 0, 0.5],
    "58": [0, 0.44444, 0.02502, 0, 0.27778],
    "59": [0.125, 0.44444, 0.02502, 0, 0.27778],
    "61": [-0.13, 0.37, 0.05087, 0, 0.77778],
    "63": [0, 0.69444, 0.11809, 0, 0.47222],
    "64": [0, 0.69444, 0.07555, 0, 0.66667],
    "65": [0, 0.69444, 0, 0, 0.66667],
    "66": [0, 0.69444, 0.08293, 0, 0.66667],
    "67": [0, 0.69444, 0.11983, 0, 0.63889],
    "68": [0, 0.69444, 0.07555, 0, 0.72223],
    "69": [0, 0.69444, 0.11983, 0, 0.59722],
    "70": [0, 0.69444, 0.13372, 0, 0.56945],
    "71": [0, 0.69444, 0.11983, 0, 0.66667],
    "72": [0, 0.69444, 0.08094, 0, 0.70834],
    "73": [0, 0.69444, 0.13372, 0, 0.27778],
    "74": [0, 0.69444, 0.08094, 0, 0.47222],
    "75": [0, 0.69444, 0.11983, 0, 0.69445],
    "76": [0, 0.69444, 0, 0, 0.54167],
    "77": [0, 0.69444, 0.08094, 0, 0.875],
    "78": [0, 0.69444, 0.08094, 0, 0.70834],
    "79": [0, 0.69444, 0.07555, 0, 0.73611],
    "80": [0, 0.69444, 0.08293, 0, 0.63889],
    "81": [0.125, 0.69444, 0.07555, 0, 0.73611],
    "82": [0, 0.69444, 0.08293, 0, 0.64584],
    "83": [0, 0.69444, 0.09205, 0, 0.55556],
    "84": [0, 0.69444, 0.13372, 0, 0.68056],
    "85": [0, 0.69444, 0.08094, 0, 0.6875],
    "86": [0, 0.69444, 0.1615, 0, 0.66667],
    "87": [0, 0.69444, 0.1615, 0, 0.94445],
    "88": [0, 0.69444, 0.13372, 0, 0.66667],
    "89": [0, 0.69444, 0.17261, 0, 0.66667],
    "90": [0, 0.69444, 0.11983, 0, 0.61111],
    "91": [0.25, 0.75, 0.15942, 0, 0.28889],
    "93": [0.25, 0.75, 0.08719, 0, 0.28889],
    "94": [0, 0.69444, 0.0799, 0, 0.5],
    "95": [0.35, 0.09444, 0.08616, 0, 0.5],
    "97": [0, 0.44444, 981e-5, 0, 0.48056],
    "98": [0, 0.69444, 0.03057, 0, 0.51667],
    "99": [0, 0.44444, 0.08336, 0, 0.44445],
    "100": [0, 0.69444, 0.09483, 0, 0.51667],
    "101": [0, 0.44444, 0.06778, 0, 0.44445],
    "102": [0, 0.69444, 0.21705, 0, 0.30556],
    "103": [0.19444, 0.44444, 0.10836, 0, 0.5],
    "104": [0, 0.69444, 0.01778, 0, 0.51667],
    "105": [0, 0.67937, 0.09718, 0, 0.23889],
    "106": [0.19444, 0.67937, 0.09162, 0, 0.26667],
    "107": [0, 0.69444, 0.08336, 0, 0.48889],
    "108": [0, 0.69444, 0.09483, 0, 0.23889],
    "109": [0, 0.44444, 0.01778, 0, 0.79445],
    "110": [0, 0.44444, 0.01778, 0, 0.51667],
    "111": [0, 0.44444, 0.06613, 0, 0.5],
    "112": [0.19444, 0.44444, 0.0389, 0, 0.51667],
    "113": [0.19444, 0.44444, 0.04169, 0, 0.51667],
    "114": [0, 0.44444, 0.10836, 0, 0.34167],
    "115": [0, 0.44444, 0.0778, 0, 0.38333],
    "116": [0, 0.57143, 0.07225, 0, 0.36111],
    "117": [0, 0.44444, 0.04169, 0, 0.51667],
    "118": [0, 0.44444, 0.10836, 0, 0.46111],
    "119": [0, 0.44444, 0.10836, 0, 0.68334],
    "120": [0, 0.44444, 0.09169, 0, 0.46111],
    "121": [0.19444, 0.44444, 0.10836, 0, 0.46111],
    "122": [0, 0.44444, 0.08752, 0, 0.43472],
    "126": [0.35, 0.32659, 0.08826, 0, 0.5],
    "160": [0, 0, 0, 0, 0.25],
    "168": [0, 0.67937, 0.06385, 0, 0.5],
    "176": [0, 0.69444, 0, 0, 0.73752],
    "184": [0.17014, 0, 0, 0, 0.44445],
    "305": [0, 0.44444, 0.04169, 0, 0.23889],
    "567": [0.19444, 0.44444, 0.04169, 0, 0.26667],
    "710": [0, 0.69444, 0.0799, 0, 0.5],
    "711": [0, 0.63194, 0.08432, 0, 0.5],
    "713": [0, 0.60889, 0.08776, 0, 0.5],
    "714": [0, 0.69444, 0.09205, 0, 0.5],
    "715": [0, 0.69444, 0, 0, 0.5],
    "728": [0, 0.69444, 0.09483, 0, 0.5],
    "729": [0, 0.67937, 0.07774, 0, 0.27778],
    "730": [0, 0.69444, 0, 0, 0.73752],
    "732": [0, 0.67659, 0.08826, 0, 0.5],
    "733": [0, 0.69444, 0.09205, 0, 0.5],
    "915": [0, 0.69444, 0.13372, 0, 0.54167],
    "916": [0, 0.69444, 0, 0, 0.83334],
    "920": [0, 0.69444, 0.07555, 0, 0.77778],
    "923": [0, 0.69444, 0, 0, 0.61111],
    "926": [0, 0.69444, 0.12816, 0, 0.66667],
    "928": [0, 0.69444, 0.08094, 0, 0.70834],
    "931": [0, 0.69444, 0.11983, 0, 0.72222],
    "933": [0, 0.69444, 0.09031, 0, 0.77778],
    "934": [0, 0.69444, 0.04603, 0, 0.72222],
    "936": [0, 0.69444, 0.09031, 0, 0.77778],
    "937": [0, 0.69444, 0.08293, 0, 0.72222],
    "8211": [0, 0.44444, 0.08616, 0, 0.5],
    "8212": [0, 0.44444, 0.08616, 0, 1],
    "8216": [0, 0.69444, 0.07816, 0, 0.27778],
    "8217": [0, 0.69444, 0.07816, 0, 0.27778],
    "8220": [0, 0.69444, 0.14205, 0, 0.5],
    "8221": [0, 0.69444, 316e-5, 0, 0.5]
  },
  "SansSerif-Regular": {
    "32": [0, 0, 0, 0, 0.25],
    "33": [0, 0.69444, 0, 0, 0.31945],
    "34": [0, 0.69444, 0, 0, 0.5],
    "35": [0.19444, 0.69444, 0, 0, 0.83334],
    "36": [0.05556, 0.75, 0, 0, 0.5],
    "37": [0.05556, 0.75, 0, 0, 0.83334],
    "38": [0, 0.69444, 0, 0, 0.75834],
    "39": [0, 0.69444, 0, 0, 0.27778],
    "40": [0.25, 0.75, 0, 0, 0.38889],
    "41": [0.25, 0.75, 0, 0, 0.38889],
    "42": [0, 0.75, 0, 0, 0.5],
    "43": [0.08333, 0.58333, 0, 0, 0.77778],
    "44": [0.125, 0.08333, 0, 0, 0.27778],
    "45": [0, 0.44444, 0, 0, 0.33333],
    "46": [0, 0.08333, 0, 0, 0.27778],
    "47": [0.25, 0.75, 0, 0, 0.5],
    "48": [0, 0.65556, 0, 0, 0.5],
    "49": [0, 0.65556, 0, 0, 0.5],
    "50": [0, 0.65556, 0, 0, 0.5],
    "51": [0, 0.65556, 0, 0, 0.5],
    "52": [0, 0.65556, 0, 0, 0.5],
    "53": [0, 0.65556, 0, 0, 0.5],
    "54": [0, 0.65556, 0, 0, 0.5],
    "55": [0, 0.65556, 0, 0, 0.5],
    "56": [0, 0.65556, 0, 0, 0.5],
    "57": [0, 0.65556, 0, 0, 0.5],
    "58": [0, 0.44444, 0, 0, 0.27778],
    "59": [0.125, 0.44444, 0, 0, 0.27778],
    "61": [-0.13, 0.37, 0, 0, 0.77778],
    "63": [0, 0.69444, 0, 0, 0.47222],
    "64": [0, 0.69444, 0, 0, 0.66667],
    "65": [0, 0.69444, 0, 0, 0.66667],
    "66": [0, 0.69444, 0, 0, 0.66667],
    "67": [0, 0.69444, 0, 0, 0.63889],
    "68": [0, 0.69444, 0, 0, 0.72223],
    "69": [0, 0.69444, 0, 0, 0.59722],
    "70": [0, 0.69444, 0, 0, 0.56945],
    "71": [0, 0.69444, 0, 0, 0.66667],
    "72": [0, 0.69444, 0, 0, 0.70834],
    "73": [0, 0.69444, 0, 0, 0.27778],
    "74": [0, 0.69444, 0, 0, 0.47222],
    "75": [0, 0.69444, 0, 0, 0.69445],
    "76": [0, 0.69444, 0, 0, 0.54167],
    "77": [0, 0.69444, 0, 0, 0.875],
    "78": [0, 0.69444, 0, 0, 0.70834],
    "79": [0, 0.69444, 0, 0, 0.73611],
    "80": [0, 0.69444, 0, 0, 0.63889],
    "81": [0.125, 0.69444, 0, 0, 0.73611],
    "82": [0, 0.69444, 0, 0, 0.64584],
    "83": [0, 0.69444, 0, 0, 0.55556],
    "84": [0, 0.69444, 0, 0, 0.68056],
    "85": [0, 0.69444, 0, 0, 0.6875],
    "86": [0, 0.69444, 0.01389, 0, 0.66667],
    "87": [0, 0.69444, 0.01389, 0, 0.94445],
    "88": [0, 0.69444, 0, 0, 0.66667],
    "89": [0, 0.69444, 0.025, 0, 0.66667],
    "90": [0, 0.69444, 0, 0, 0.61111],
    "91": [0.25, 0.75, 0, 0, 0.28889],
    "93": [0.25, 0.75, 0, 0, 0.28889],
    "94": [0, 0.69444, 0, 0, 0.5],
    "95": [0.35, 0.09444, 0.02778, 0, 0.5],
    "97": [0, 0.44444, 0, 0, 0.48056],
    "98": [0, 0.69444, 0, 0, 0.51667],
    "99": [0, 0.44444, 0, 0, 0.44445],
    "100": [0, 0.69444, 0, 0, 0.51667],
    "101": [0, 0.44444, 0, 0, 0.44445],
    "102": [0, 0.69444, 0.06944, 0, 0.30556],
    "103": [0.19444, 0.44444, 0.01389, 0, 0.5],
    "104": [0, 0.69444, 0, 0, 0.51667],
    "105": [0, 0.67937, 0, 0, 0.23889],
    "106": [0.19444, 0.67937, 0, 0, 0.26667],
    "107": [0, 0.69444, 0, 0, 0.48889],
    "108": [0, 0.69444, 0, 0, 0.23889],
    "109": [0, 0.44444, 0, 0, 0.79445],
    "110": [0, 0.44444, 0, 0, 0.51667],
    "111": [0, 0.44444, 0, 0, 0.5],
    "112": [0.19444, 0.44444, 0, 0, 0.51667],
    "113": [0.19444, 0.44444, 0, 0, 0.51667],
    "114": [0, 0.44444, 0.01389, 0, 0.34167],
    "115": [0, 0.44444, 0, 0, 0.38333],
    "116": [0, 0.57143, 0, 0, 0.36111],
    "117": [0, 0.44444, 0, 0, 0.51667],
    "118": [0, 0.44444, 0.01389, 0, 0.46111],
    "119": [0, 0.44444, 0.01389, 0, 0.68334],
    "120": [0, 0.44444, 0, 0, 0.46111],
    "121": [0.19444, 0.44444, 0.01389, 0, 0.46111],
    "122": [0, 0.44444, 0, 0, 0.43472],
    "126": [0.35, 0.32659, 0, 0, 0.5],
    "160": [0, 0, 0, 0, 0.25],
    "168": [0, 0.67937, 0, 0, 0.5],
    "176": [0, 0.69444, 0, 0, 0.66667],
    "184": [0.17014, 0, 0, 0, 0.44445],
    "305": [0, 0.44444, 0, 0, 0.23889],
    "567": [0.19444, 0.44444, 0, 0, 0.26667],
    "710": [0, 0.69444, 0, 0, 0.5],
    "711": [0, 0.63194, 0, 0, 0.5],
    "713": [0, 0.60889, 0, 0, 0.5],
    "714": [0, 0.69444, 0, 0, 0.5],
    "715": [0, 0.69444, 0, 0, 0.5],
    "728": [0, 0.69444, 0, 0, 0.5],
    "729": [0, 0.67937, 0, 0, 0.27778],
    "730": [0, 0.69444, 0, 0, 0.66667],
    "732": [0, 0.67659, 0, 0, 0.5],
    "733": [0, 0.69444, 0, 0, 0.5],
    "915": [0, 0.69444, 0, 0, 0.54167],
    "916": [0, 0.69444, 0, 0, 0.83334],
    "920": [0, 0.69444, 0, 0, 0.77778],
    "923": [0, 0.69444, 0, 0, 0.61111],
    "926": [0, 0.69444, 0, 0, 0.66667],
    "928": [0, 0.69444, 0, 0, 0.70834],
    "931": [0, 0.69444, 0, 0, 0.72222],
    "933": [0, 0.69444, 0, 0, 0.77778],
    "934": [0, 0.69444, 0, 0, 0.72222],
    "936": [0, 0.69444, 0, 0, 0.77778],
    "937": [0, 0.69444, 0, 0, 0.72222],
    "8211": [0, 0.44444, 0.02778, 0, 0.5],
    "8212": [0, 0.44444, 0.02778, 0, 1],
    "8216": [0, 0.69444, 0, 0, 0.27778],
    "8217": [0, 0.69444, 0, 0, 0.27778],
    "8220": [0, 0.69444, 0, 0, 0.5],
    "8221": [0, 0.69444, 0, 0, 0.5]
  },
  "Script-Regular": {
    "32": [0, 0, 0, 0, 0.25],
    "65": [0, 0.7, 0.22925, 0, 0.80253],
    "66": [0, 0.7, 0.04087, 0, 0.90757],
    "67": [0, 0.7, 0.1689, 0, 0.66619],
    "68": [0, 0.7, 0.09371, 0, 0.77443],
    "69": [0, 0.7, 0.18583, 0, 0.56162],
    "70": [0, 0.7, 0.13634, 0, 0.89544],
    "71": [0, 0.7, 0.17322, 0, 0.60961],
    "72": [0, 0.7, 0.29694, 0, 0.96919],
    "73": [0, 0.7, 0.19189, 0, 0.80907],
    "74": [0.27778, 0.7, 0.19189, 0, 1.05159],
    "75": [0, 0.7, 0.31259, 0, 0.91364],
    "76": [0, 0.7, 0.19189, 0, 0.87373],
    "77": [0, 0.7, 0.15981, 0, 1.08031],
    "78": [0, 0.7, 0.3525, 0, 0.9015],
    "79": [0, 0.7, 0.08078, 0, 0.73787],
    "80": [0, 0.7, 0.08078, 0, 1.01262],
    "81": [0, 0.7, 0.03305, 0, 0.88282],
    "82": [0, 0.7, 0.06259, 0, 0.85],
    "83": [0, 0.7, 0.19189, 0, 0.86767],
    "84": [0, 0.7, 0.29087, 0, 0.74697],
    "85": [0, 0.7, 0.25815, 0, 0.79996],
    "86": [0, 0.7, 0.27523, 0, 0.62204],
    "87": [0, 0.7, 0.27523, 0, 0.80532],
    "88": [0, 0.7, 0.26006, 0, 0.94445],
    "89": [0, 0.7, 0.2939, 0, 0.70961],
    "90": [0, 0.7, 0.24037, 0, 0.8212],
    "160": [0, 0, 0, 0, 0.25]
  },
  "Size1-Regular": {
    "32": [0, 0, 0, 0, 0.25],
    "40": [0.35001, 0.85, 0, 0, 0.45834],
    "41": [0.35001, 0.85, 0, 0, 0.45834],
    "47": [0.35001, 0.85, 0, 0, 0.57778],
    "91": [0.35001, 0.85, 0, 0, 0.41667],
    "92": [0.35001, 0.85, 0, 0, 0.57778],
    "93": [0.35001, 0.85, 0, 0, 0.41667],
    "123": [0.35001, 0.85, 0, 0, 0.58334],
    "125": [0.35001, 0.85, 0, 0, 0.58334],
    "160": [0, 0, 0, 0, 0.25],
    "710": [0, 0.72222, 0, 0, 0.55556],
    "732": [0, 0.72222, 0, 0, 0.55556],
    "770": [0, 0.72222, 0, 0, 0.55556],
    "771": [0, 0.72222, 0, 0, 0.55556],
    "8214": [-99e-5, 0.601, 0, 0, 0.77778],
    "8593": [1e-5, 0.6, 0, 0, 0.66667],
    "8595": [1e-5, 0.6, 0, 0, 0.66667],
    "8657": [1e-5, 0.6, 0, 0, 0.77778],
    "8659": [1e-5, 0.6, 0, 0, 0.77778],
    "8719": [0.25001, 0.75, 0, 0, 0.94445],
    "8720": [0.25001, 0.75, 0, 0, 0.94445],
    "8721": [0.25001, 0.75, 0, 0, 1.05556],
    "8730": [0.35001, 0.85, 0, 0, 1],
    "8739": [-599e-5, 0.606, 0, 0, 0.33333],
    "8741": [-599e-5, 0.606, 0, 0, 0.55556],
    "8747": [0.30612, 0.805, 0.19445, 0, 0.47222],
    "8748": [0.306, 0.805, 0.19445, 0, 0.47222],
    "8749": [0.306, 0.805, 0.19445, 0, 0.47222],
    "8750": [0.30612, 0.805, 0.19445, 0, 0.47222],
    "8896": [0.25001, 0.75, 0, 0, 0.83334],
    "8897": [0.25001, 0.75, 0, 0, 0.83334],
    "8898": [0.25001, 0.75, 0, 0, 0.83334],
    "8899": [0.25001, 0.75, 0, 0, 0.83334],
    "8968": [0.35001, 0.85, 0, 0, 0.47222],
    "8969": [0.35001, 0.85, 0, 0, 0.47222],
    "8970": [0.35001, 0.85, 0, 0, 0.47222],
    "8971": [0.35001, 0.85, 0, 0, 0.47222],
    "9168": [-99e-5, 0.601, 0, 0, 0.66667],
    "10216": [0.35001, 0.85, 0, 0, 0.47222],
    "10217": [0.35001, 0.85, 0, 0, 0.47222],
    "10752": [0.25001, 0.75, 0, 0, 1.11111],
    "10753": [0.25001, 0.75, 0, 0, 1.11111],
    "10754": [0.25001, 0.75, 0, 0, 1.11111],
    "10756": [0.25001, 0.75, 0, 0, 0.83334],
    "10758": [0.25001, 0.75, 0, 0, 0.83334]
  },
  "Size2-Regular": {
    "32": [0, 0, 0, 0, 0.25],
    "40": [0.65002, 1.15, 0, 0, 0.59722],
    "41": [0.65002, 1.15, 0, 0, 0.59722],
    "47": [0.65002, 1.15, 0, 0, 0.81111],
    "91": [0.65002, 1.15, 0, 0, 0.47222],
    "92": [0.65002, 1.15, 0, 0, 0.81111],
    "93": [0.65002, 1.15, 0, 0, 0.47222],
    "123": [0.65002, 1.15, 0, 0, 0.66667],
    "125": [0.65002, 1.15, 0, 0, 0.66667],
    "160": [0, 0, 0, 0, 0.25],
    "710": [0, 0.75, 0, 0, 1],
    "732": [0, 0.75, 0, 0, 1],
    "770": [0, 0.75, 0, 0, 1],
    "771": [0, 0.75, 0, 0, 1],
    "8719": [0.55001, 1.05, 0, 0, 1.27778],
    "8720": [0.55001, 1.05, 0, 0, 1.27778],
    "8721": [0.55001, 1.05, 0, 0, 1.44445],
    "8730": [0.65002, 1.15, 0, 0, 1],
    "8747": [0.86225, 1.36, 0.44445, 0, 0.55556],
    "8748": [0.862, 1.36, 0.44445, 0, 0.55556],
    "8749": [0.862, 1.36, 0.44445, 0, 0.55556],
    "8750": [0.86225, 1.36, 0.44445, 0, 0.55556],
    "8896": [0.55001, 1.05, 0, 0, 1.11111],
    "8897": [0.55001, 1.05, 0, 0, 1.11111],
    "8898": [0.55001, 1.05, 0, 0, 1.11111],
    "8899": [0.55001, 1.05, 0, 0, 1.11111],
    "8968": [0.65002, 1.15, 0, 0, 0.52778],
    "8969": [0.65002, 1.15, 0, 0, 0.52778],
    "8970": [0.65002, 1.15, 0, 0, 0.52778],
    "8971": [0.65002, 1.15, 0, 0, 0.52778],
    "10216": [0.65002, 1.15, 0, 0, 0.61111],
    "10217": [0.65002, 1.15, 0, 0, 0.61111],
    "10752": [0.55001, 1.05, 0, 0, 1.51112],
    "10753": [0.55001, 1.05, 0, 0, 1.51112],
    "10754": [0.55001, 1.05, 0, 0, 1.51112],
    "10756": [0.55001, 1.05, 0, 0, 1.11111],
    "10758": [0.55001, 1.05, 0, 0, 1.11111]
  },
  "Size3-Regular": {
    "32": [0, 0, 0, 0, 0.25],
    "40": [0.95003, 1.45, 0, 0, 0.73611],
    "41": [0.95003, 1.45, 0, 0, 0.73611],
    "47": [0.95003, 1.45, 0, 0, 1.04445],
    "91": [0.95003, 1.45, 0, 0, 0.52778],
    "92": [0.95003, 1.45, 0, 0, 1.04445],
    "93": [0.95003, 1.45, 0, 0, 0.52778],
    "123": [0.95003, 1.45, 0, 0, 0.75],
    "125": [0.95003, 1.45, 0, 0, 0.75],
    "160": [0, 0, 0, 0, 0.25],
    "710": [0, 0.75, 0, 0, 1.44445],
    "732": [0, 0.75, 0, 0, 1.44445],
    "770": [0, 0.75, 0, 0, 1.44445],
    "771": [0, 0.75, 0, 0, 1.44445],
    "8730": [0.95003, 1.45, 0, 0, 1],
    "8968": [0.95003, 1.45, 0, 0, 0.58334],
    "8969": [0.95003, 1.45, 0, 0, 0.58334],
    "8970": [0.95003, 1.45, 0, 0, 0.58334],
    "8971": [0.95003, 1.45, 0, 0, 0.58334],
    "10216": [0.95003, 1.45, 0, 0, 0.75],
    "10217": [0.95003, 1.45, 0, 0, 0.75]
  },
  "Size4-Regular": {
    "32": [0, 0, 0, 0, 0.25],
    "40": [1.25003, 1.75, 0, 0, 0.79167],
    "41": [1.25003, 1.75, 0, 0, 0.79167],
    "47": [1.25003, 1.75, 0, 0, 1.27778],
    "91": [1.25003, 1.75, 0, 0, 0.58334],
    "92": [1.25003, 1.75, 0, 0, 1.27778],
    "93": [1.25003, 1.75, 0, 0, 0.58334],
    "123": [1.25003, 1.75, 0, 0, 0.80556],
    "125": [1.25003, 1.75, 0, 0, 0.80556],
    "160": [0, 0, 0, 0, 0.25],
    "710": [0, 0.825, 0, 0, 1.8889],
    "732": [0, 0.825, 0, 0, 1.8889],
    "770": [0, 0.825, 0, 0, 1.8889],
    "771": [0, 0.825, 0, 0, 1.8889],
    "8730": [1.25003, 1.75, 0, 0, 1],
    "8968": [1.25003, 1.75, 0, 0, 0.63889],
    "8969": [1.25003, 1.75, 0, 0, 0.63889],
    "8970": [1.25003, 1.75, 0, 0, 0.63889],
    "8971": [1.25003, 1.75, 0, 0, 0.63889],
    "9115": [0.64502, 1.155, 0, 0, 0.875],
    "9116": [1e-5, 0.6, 0, 0, 0.875],
    "9117": [0.64502, 1.155, 0, 0, 0.875],
    "9118": [0.64502, 1.155, 0, 0, 0.875],
    "9119": [1e-5, 0.6, 0, 0, 0.875],
    "9120": [0.64502, 1.155, 0, 0, 0.875],
    "9121": [0.64502, 1.155, 0, 0, 0.66667],
    "9122": [-99e-5, 0.601, 0, 0, 0.66667],
    "9123": [0.64502, 1.155, 0, 0, 0.66667],
    "9124": [0.64502, 1.155, 0, 0, 0.66667],
    "9125": [-99e-5, 0.601, 0, 0, 0.66667],
    "9126": [0.64502, 1.155, 0, 0, 0.66667],
    "9127": [1e-5, 0.9, 0, 0, 0.88889],
    "9128": [0.65002, 1.15, 0, 0, 0.88889],
    "9129": [0.90001, 0, 0, 0, 0.88889],
    "9130": [0, 0.3, 0, 0, 0.88889],
    "9131": [1e-5, 0.9, 0, 0, 0.88889],
    "9132": [0.65002, 1.15, 0, 0, 0.88889],
    "9133": [0.90001, 0, 0, 0, 0.88889],
    "9143": [0.88502, 0.915, 0, 0, 1.05556],
    "10216": [1.25003, 1.75, 0, 0, 0.80556],
    "10217": [1.25003, 1.75, 0, 0, 0.80556],
    "57344": [-499e-5, 0.605, 0, 0, 1.05556],
    "57345": [-499e-5, 0.605, 0, 0, 1.05556],
    "57680": [0, 0.12, 0, 0, 0.45],
    "57681": [0, 0.12, 0, 0, 0.45],
    "57682": [0, 0.12, 0, 0, 0.45],
    "57683": [0, 0.12, 0, 0, 0.45]
  },
  "Typewriter-Regular": {
    "32": [0, 0, 0, 0, 0.525],
    "33": [0, 0.61111, 0, 0, 0.525],
    "34": [0, 0.61111, 0, 0, 0.525],
    "35": [0, 0.61111, 0, 0, 0.525],
    "36": [0.08333, 0.69444, 0, 0, 0.525],
    "37": [0.08333, 0.69444, 0, 0, 0.525],
    "38": [0, 0.61111, 0, 0, 0.525],
    "39": [0, 0.61111, 0, 0, 0.525],
    "40": [0.08333, 0.69444, 0, 0, 0.525],
    "41": [0.08333, 0.69444, 0, 0, 0.525],
    "42": [0, 0.52083, 0, 0, 0.525],
    "43": [-0.08056, 0.53055, 0, 0, 0.525],
    "44": [0.13889, 0.125, 0, 0, 0.525],
    "45": [-0.08056, 0.53055, 0, 0, 0.525],
    "46": [0, 0.125, 0, 0, 0.525],
    "47": [0.08333, 0.69444, 0, 0, 0.525],
    "48": [0, 0.61111, 0, 0, 0.525],
    "49": [0, 0.61111, 0, 0, 0.525],
    "50": [0, 0.61111, 0, 0, 0.525],
    "51": [0, 0.61111, 0, 0, 0.525],
    "52": [0, 0.61111, 0, 0, 0.525],
    "53": [0, 0.61111, 0, 0, 0.525],
    "54": [0, 0.61111, 0, 0, 0.525],
    "55": [0, 0.61111, 0, 0, 0.525],
    "56": [0, 0.61111, 0, 0, 0.525],
    "57": [0, 0.61111, 0, 0, 0.525],
    "58": [0, 0.43056, 0, 0, 0.525],
    "59": [0.13889, 0.43056, 0, 0, 0.525],
    "60": [-0.05556, 0.55556, 0, 0, 0.525],
    "61": [-0.19549, 0.41562, 0, 0, 0.525],
    "62": [-0.05556, 0.55556, 0, 0, 0.525],
    "63": [0, 0.61111, 0, 0, 0.525],
    "64": [0, 0.61111, 0, 0, 0.525],
    "65": [0, 0.61111, 0, 0, 0.525],
    "66": [0, 0.61111, 0, 0, 0.525],
    "67": [0, 0.61111, 0, 0, 0.525],
    "68": [0, 0.61111, 0, 0, 0.525],
    "69": [0, 0.61111, 0, 0, 0.525],
    "70": [0, 0.61111, 0, 0, 0.525],
    "71": [0, 0.61111, 0, 0, 0.525],
    "72": [0, 0.61111, 0, 0, 0.525],
    "73": [0, 0.61111, 0, 0, 0.525],
    "74": [0, 0.61111, 0, 0, 0.525],
    "75": [0, 0.61111, 0, 0, 0.525],
    "76": [0, 0.61111, 0, 0, 0.525],
    "77": [0, 0.61111, 0, 0, 0.525],
    "78": [0, 0.61111, 0, 0, 0.525],
    "79": [0, 0.61111, 0, 0, 0.525],
    "80": [0, 0.61111, 0, 0, 0.525],
    "81": [0.13889, 0.61111, 0, 0, 0.525],
    "82": [0, 0.61111, 0, 0, 0.525],
    "83": [0, 0.61111, 0, 0, 0.525],
    "84": [0, 0.61111, 0, 0, 0.525],
    "85": [0, 0.61111, 0, 0, 0.525],
    "86": [0, 0.61111, 0, 0, 0.525],
    "87": [0, 0.61111, 0, 0, 0.525],
    "88": [0, 0.61111, 0, 0, 0.525],
    "89": [0, 0.61111, 0, 0, 0.525],
    "90": [0, 0.61111, 0, 0, 0.525],
    "91": [0.08333, 0.69444, 0, 0, 0.525],
    "92": [0.08333, 0.69444, 0, 0, 0.525],
    "93": [0.08333, 0.69444, 0, 0, 0.525],
    "94": [0, 0.61111, 0, 0, 0.525],
    "95": [0.09514, 0, 0, 0, 0.525],
    "96": [0, 0.61111, 0, 0, 0.525],
    "97": [0, 0.43056, 0, 0, 0.525],
    "98": [0, 0.61111, 0, 0, 0.525],
    "99": [0, 0.43056, 0, 0, 0.525],
    "100": [0, 0.61111, 0, 0, 0.525],
    "101": [0, 0.43056, 0, 0, 0.525],
    "102": [0, 0.61111, 0, 0, 0.525],
    "103": [0.22222, 0.43056, 0, 0, 0.525],
    "104": [0, 0.61111, 0, 0, 0.525],
    "105": [0, 0.61111, 0, 0, 0.525],
    "106": [0.22222, 0.61111, 0, 0, 0.525],
    "107": [0, 0.61111, 0, 0, 0.525],
    "108": [0, 0.61111, 0, 0, 0.525],
    "109": [0, 0.43056, 0, 0, 0.525],
    "110": [0, 0.43056, 0, 0, 0.525],
    "111": [0, 0.43056, 0, 0, 0.525],
    "112": [0.22222, 0.43056, 0, 0, 0.525],
    "113": [0.22222, 0.43056, 0, 0, 0.525],
    "114": [0, 0.43056, 0, 0, 0.525],
    "115": [0, 0.43056, 0, 0, 0.525],
    "116": [0, 0.55358, 0, 0, 0.525],
    "117": [0, 0.43056, 0, 0, 0.525],
    "118": [0, 0.43056, 0, 0, 0.525],
    "119": [0, 0.43056, 0, 0, 0.525],
    "120": [0, 0.43056, 0, 0, 0.525],
    "121": [0.22222, 0.43056, 0, 0, 0.525],
    "122": [0, 0.43056, 0, 0, 0.525],
    "123": [0.08333, 0.69444, 0, 0, 0.525],
    "124": [0.08333, 0.69444, 0, 0, 0.525],
    "125": [0.08333, 0.69444, 0, 0, 0.525],
    "126": [0, 0.61111, 0, 0, 0.525],
    "127": [0, 0.61111, 0, 0, 0.525],
    "160": [0, 0, 0, 0, 0.525],
    "176": [0, 0.61111, 0, 0, 0.525],
    "184": [0.19445, 0, 0, 0, 0.525],
    "305": [0, 0.43056, 0, 0, 0.525],
    "567": [0.22222, 0.43056, 0, 0, 0.525],
    "711": [0, 0.56597, 0, 0, 0.525],
    "713": [0, 0.56555, 0, 0, 0.525],
    "714": [0, 0.61111, 0, 0, 0.525],
    "715": [0, 0.61111, 0, 0, 0.525],
    "728": [0, 0.61111, 0, 0, 0.525],
    "730": [0, 0.61111, 0, 0, 0.525],
    "770": [0, 0.61111, 0, 0, 0.525],
    "771": [0, 0.61111, 0, 0, 0.525],
    "776": [0, 0.61111, 0, 0, 0.525],
    "915": [0, 0.61111, 0, 0, 0.525],
    "916": [0, 0.61111, 0, 0, 0.525],
    "920": [0, 0.61111, 0, 0, 0.525],
    "923": [0, 0.61111, 0, 0, 0.525],
    "926": [0, 0.61111, 0, 0, 0.525],
    "928": [0, 0.61111, 0, 0, 0.525],
    "931": [0, 0.61111, 0, 0, 0.525],
    "933": [0, 0.61111, 0, 0, 0.525],
    "934": [0, 0.61111, 0, 0, 0.525],
    "936": [0, 0.61111, 0, 0, 0.525],
    "937": [0, 0.61111, 0, 0, 0.525],
    "8216": [0, 0.61111, 0, 0, 0.525],
    "8217": [0, 0.61111, 0, 0, 0.525],
    "8242": [0, 0.61111, 0, 0, 0.525],
    "9251": [0.11111, 0.21944, 0, 0, 0.525]
  }
};
var sigmasAndXis = {
  slant: [0.25, 0.25, 0.25],
  // sigma1
  space: [0, 0, 0],
  // sigma2
  stretch: [0, 0, 0],
  // sigma3
  shrink: [0, 0, 0],
  // sigma4
  xHeight: [0.431, 0.431, 0.431],
  // sigma5
  quad: [1, 1.171, 1.472],
  // sigma6
  extraSpace: [0, 0, 0],
  // sigma7
  num1: [0.677, 0.732, 0.925],
  // sigma8
  num2: [0.394, 0.384, 0.387],
  // sigma9
  num3: [0.444, 0.471, 0.504],
  // sigma10
  denom1: [0.686, 0.752, 1.025],
  // sigma11
  denom2: [0.345, 0.344, 0.532],
  // sigma12
  sup1: [0.413, 0.503, 0.504],
  // sigma13
  sup2: [0.363, 0.431, 0.404],
  // sigma14
  sup3: [0.289, 0.286, 0.294],
  // sigma15
  sub1: [0.15, 0.143, 0.2],
  // sigma16
  sub2: [0.247, 0.286, 0.4],
  // sigma17
  supDrop: [0.386, 0.353, 0.494],
  // sigma18
  subDrop: [0.05, 0.071, 0.1],
  // sigma19
  delim1: [2.39, 1.7, 1.98],
  // sigma20
  delim2: [1.01, 1.157, 1.42],
  // sigma21
  axisHeight: [0.25, 0.25, 0.25],
  // sigma22
  // These font metrics are extracted from TeX by using tftopl on cmex10.tfm;
  // they correspond to the font parameters of the extension fonts (family 3).
  // See the TeXbook, page 441. In AMSTeX, the extension fonts scale; to
  // match cmex7, we'd use cmex7.tfm values for script and scriptscript
  // values.
  defaultRuleThickness: [0.04, 0.049, 0.049],
  // xi8; cmex7: 0.049
  bigOpSpacing1: [0.111, 0.111, 0.111],
  // xi9
  bigOpSpacing2: [0.166, 0.166, 0.166],
  // xi10
  bigOpSpacing3: [0.2, 0.2, 0.2],
  // xi11
  bigOpSpacing4: [0.6, 0.611, 0.611],
  // xi12; cmex7: 0.611
  bigOpSpacing5: [0.1, 0.143, 0.143],
  // xi13; cmex7: 0.143
  // The \sqrt rule width is taken from the height of the surd character.
  // Since we use the same font at all sizes, this thickness doesn't scale.
  sqrtRuleThickness: [0.04, 0.04, 0.04],
  // This value determines how large a pt is, for metrics which are defined
  // in terms of pts.
  // This value is also used in katex.scss; if you change it make sure the
  // values match.
  ptPerEm: [10, 10, 10],
  // The space between adjacent `|` columns in an array definition. From
  // `\showthe\doublerulesep` in LaTeX. Equals 2.0 / ptPerEm.
  doubleRuleSep: [0.2, 0.2, 0.2],
  // The width of separator lines in {array} environments. From
  // `\showthe\arrayrulewidth` in LaTeX. Equals 0.4 / ptPerEm.
  arrayRuleWidth: [0.04, 0.04, 0.04],
  // Two values from LaTeX source2e:
  fboxsep: [0.3, 0.3, 0.3],
  //        3 pt / ptPerEm
  fboxrule: [0.04, 0.04, 0.04]
  // 0.4 pt / ptPerEm
};
var extraCharacterMap = {
  // Latin-1
  "\xC5": "A",
  "\xD0": "D",
  "\xDE": "o",
  "\xE5": "a",
  "\xF0": "d",
  "\xFE": "o",
  // Cyrillic
  "\u0410": "A",
  "\u0411": "B",
  "\u0412": "B",
  "\u0413": "F",
  "\u0414": "A",
  "\u0415": "E",
  "\u0416": "K",
  "\u0417": "3",
  "\u0418": "N",
  "\u0419": "N",
  "\u041A": "K",
  "\u041B": "N",
  "\u041C": "M",
  "\u041D": "H",
  "\u041E": "O",
  "\u041F": "N",
  "\u0420": "P",
  "\u0421": "C",
  "\u0422": "T",
  "\u0423": "y",
  "\u0424": "O",
  "\u0425": "X",
  "\u0426": "U",
  "\u0427": "h",
  "\u0428": "W",
  "\u0429": "W",
  "\u042A": "B",
  "\u042B": "X",
  "\u042C": "B",
  "\u042D": "3",
  "\u042E": "X",
  "\u042F": "R",
  "\u0430": "a",
  "\u0431": "b",
  "\u0432": "a",
  "\u0433": "r",
  "\u0434": "y",
  "\u0435": "e",
  "\u0436": "m",
  "\u0437": "e",
  "\u0438": "n",
  "\u0439": "n",
  "\u043A": "n",
  "\u043B": "n",
  "\u043C": "m",
  "\u043D": "n",
  "\u043E": "o",
  "\u043F": "n",
  "\u0440": "p",
  "\u0441": "c",
  "\u0442": "o",
  "\u0443": "y",
  "\u0444": "b",
  "\u0445": "x",
  "\u0446": "n",
  "\u0447": "n",
  "\u0448": "w",
  "\u0449": "w",
  "\u044A": "a",
  "\u044B": "m",
  "\u044C": "a",
  "\u044D": "e",
  "\u044E": "m",
  "\u044F": "r"
};
function setFontMetrics(fontName, metrics) {
  fontMetricsData[fontName] = metrics;
}
function getCharacterMetrics(character, font, mode) {
  if (!fontMetricsData[font]) {
    throw new Error("Font metrics not found for font: " + font + ".");
  }
  var ch = character.charCodeAt(0);
  var metrics = fontMetricsData[font][ch];
  if (!metrics && character[0] in extraCharacterMap) {
    ch = extraCharacterMap[character[0]].charCodeAt(0);
    metrics = fontMetricsData[font][ch];
  }
  if (!metrics && mode === "text") {
    if (supportedCodepoint(ch)) {
      metrics = fontMetricsData[font][77];
    }
  }
  if (metrics) {
    return {
      depth: metrics[0],
      height: metrics[1],
      italic: metrics[2],
      skew: metrics[3],
      width: metrics[4]
    };
  }
}
var fontMetricsBySizeIndex = {};
function getGlobalMetrics(size) {
  var sizeIndex;
  if (size >= 5) {
    sizeIndex = 0;
  } else if (size >= 3) {
    sizeIndex = 1;
  } else {
    sizeIndex = 2;
  }
  if (!fontMetricsBySizeIndex[sizeIndex]) {
    var metrics = fontMetricsBySizeIndex[sizeIndex] = {
      cssEmPerMu: sigmasAndXis.quad[sizeIndex] / 18
    };
    for (var key in sigmasAndXis) {
      if (sigmasAndXis.hasOwnProperty(key)) {
        metrics[key] = sigmasAndXis[key][sizeIndex];
      }
    }
  }
  return fontMetricsBySizeIndex[sizeIndex];
}
var sizeStyleMap = [
  // Each element contains [textsize, scriptsize, scriptscriptsize].
  // The size mappings are taken from TeX with \normalsize=10pt.
  [1, 1, 1],
  // size1: [5, 5, 5]              \tiny
  [2, 1, 1],
  // size2: [6, 5, 5]
  [3, 1, 1],
  // size3: [7, 5, 5]              \scriptsize
  [4, 2, 1],
  // size4: [8, 6, 5]              \footnotesize
  [5, 2, 1],
  // size5: [9, 6, 5]              \small
  [6, 3, 1],
  // size6: [10, 7, 5]             \normalsize
  [7, 4, 2],
  // size7: [12, 8, 6]             \large
  [8, 6, 3],
  // size8: [14.4, 10, 7]          \Large
  [9, 7, 6],
  // size9: [17.28, 12, 10]        \LARGE
  [10, 8, 7],
  // size10: [20.74, 14.4, 12]     \huge
  [11, 10, 9]
  // size11: [24.88, 20.74, 17.28] \HUGE
];
var sizeMultipliers = [
  // fontMetrics.js:getGlobalMetrics also uses size indexes, so if
  // you change size indexes, change that function.
  0.5,
  0.6,
  0.7,
  0.8,
  0.9,
  1,
  1.2,
  1.44,
  1.728,
  2.074,
  2.488
];
var sizeAtStyle = function sizeAtStyle2(size, style2) {
  return style2.size < 2 ? size : sizeStyleMap[size - 1][style2.size - 1];
};
var Options2 = class _Options {
  // A font family applies to a group of fonts (i.e. SansSerif), while a font
  // represents a specific font (i.e. SansSerif Bold).
  // See: https://tex.stackexchange.com/questions/22350/difference-between-textrm-and-mathrm
  /**
   * The base size index.
   */
  constructor(data) {
    this.style = void 0;
    this.color = void 0;
    this.size = void 0;
    this.textSize = void 0;
    this.phantom = void 0;
    this.font = void 0;
    this.fontFamily = void 0;
    this.fontWeight = void 0;
    this.fontShape = void 0;
    this.sizeMultiplier = void 0;
    this.maxSize = void 0;
    this.minRuleThickness = void 0;
    this._fontMetrics = void 0;
    this.style = data.style;
    this.color = data.color;
    this.size = data.size || _Options.BASESIZE;
    this.textSize = data.textSize || this.size;
    this.phantom = !!data.phantom;
    this.font = data.font || "";
    this.fontFamily = data.fontFamily || "";
    this.fontWeight = data.fontWeight || "";
    this.fontShape = data.fontShape || "";
    this.sizeMultiplier = sizeMultipliers[this.size - 1];
    this.maxSize = data.maxSize;
    this.minRuleThickness = data.minRuleThickness;
    this._fontMetrics = void 0;
  }
  /**
   * Returns a new options object with the same properties as "this".  Properties
   * from "extension" will be copied to the new options object.
   */
  extend(extension) {
    var data = {
      style: this.style,
      size: this.size,
      textSize: this.textSize,
      color: this.color,
      phantom: this.phantom,
      font: this.font,
      fontFamily: this.fontFamily,
      fontWeight: this.fontWeight,
      fontShape: this.fontShape,
      maxSize: this.maxSize,
      minRuleThickness: this.minRuleThickness
    };
    for (var key in extension) {
      if (extension.hasOwnProperty(key)) {
        data[key] = extension[key];
      }
    }
    return new _Options(data);
  }
  /**
   * Return an options object with the given style. If `this.style === style`,
   * returns `this`.
   */
  havingStyle(style2) {
    if (this.style === style2) {
      return this;
    } else {
      return this.extend({
        style: style2,
        size: sizeAtStyle(this.textSize, style2)
      });
    }
  }
  /**
   * Return an options object with a cramped version of the current style. If
   * the current style is cramped, returns `this`.
   */
  havingCrampedStyle() {
    return this.havingStyle(this.style.cramp());
  }
  /**
   * Return an options object with the given size and in at least `\textstyle`.
   * Returns `this` if appropriate.
   */
  havingSize(size) {
    if (this.size === size && this.textSize === size) {
      return this;
    } else {
      return this.extend({
        style: this.style.text(),
        size,
        textSize: size,
        sizeMultiplier: sizeMultipliers[size - 1]
      });
    }
  }
  /**
   * Like `this.havingSize(BASESIZE).havingStyle(style)`. If `style` is omitted,
   * changes to at least `\textstyle`.
   */
  havingBaseStyle(style2) {
    style2 = style2 || this.style.text();
    var wantSize = sizeAtStyle(_Options.BASESIZE, style2);
    if (this.size === wantSize && this.textSize === _Options.BASESIZE && this.style === style2) {
      return this;
    } else {
      return this.extend({
        style: style2,
        size: wantSize
      });
    }
  }
  /**
   * Remove the effect of sizing changes such as \Huge.
   * Keep the effect of the current style, such as \scriptstyle.
   */
  havingBaseSizing() {
    var size;
    switch (this.style.id) {
      case 4:
      case 5:
        size = 3;
        break;
      case 6:
      case 7:
        size = 1;
        break;
      default:
        size = 6;
    }
    return this.extend({
      style: this.style.text(),
      size
    });
  }
  /**
   * Create a new options object with the given color.
   */
  withColor(color) {
    return this.extend({
      color
    });
  }
  /**
   * Create a new options object with "phantom" set to true.
   */
  withPhantom() {
    return this.extend({
      phantom: true
    });
  }
  /**
   * Creates a new options object with the given math font or old text font.
   * @type {[type]}
   */
  withFont(font) {
    return this.extend({
      font
    });
  }
  /**
   * Create a new options objects with the given fontFamily.
   */
  withTextFontFamily(fontFamily) {
    return this.extend({
      fontFamily,
      font: ""
    });
  }
  /**
   * Creates a new options object with the given font weight
   */
  withTextFontWeight(fontWeight) {
    return this.extend({
      fontWeight,
      font: ""
    });
  }
  /**
   * Creates a new options object with the given font weight
   */
  withTextFontShape(fontShape) {
    return this.extend({
      fontShape,
      font: ""
    });
  }
  /**
   * Return the CSS sizing classes required to switch from enclosing options
   * `oldOptions` to `this`. Returns an array of classes.
   */
  sizingClasses(oldOptions) {
    if (oldOptions.size !== this.size) {
      return ["sizing", "reset-size" + oldOptions.size, "size" + this.size];
    } else {
      return [];
    }
  }
  /**
   * Return the CSS sizing classes required to switch to the base size. Like
   * `this.havingSize(BASESIZE).sizingClasses(this)`.
   */
  baseSizingClasses() {
    if (this.size !== _Options.BASESIZE) {
      return ["sizing", "reset-size" + this.size, "size" + _Options.BASESIZE];
    } else {
      return [];
    }
  }
  /**
   * Return the font metrics for this size.
   */
  fontMetrics() {
    if (!this._fontMetrics) {
      this._fontMetrics = getGlobalMetrics(this.size);
    }
    return this._fontMetrics;
  }
  /**
   * Gets the CSS color of the current options object
   */
  getColor() {
    if (this.phantom) {
      return "transparent";
    } else {
      return this.color;
    }
  }
};
Options2.BASESIZE = 6;
var ptPerUnit = {
  // https://en.wikibooks.org/wiki/LaTeX/Lengths and
  // https://tex.stackexchange.com/a/8263
  "pt": 1,
  // TeX point
  "mm": 7227 / 2540,
  // millimeter
  "cm": 7227 / 254,
  // centimeter
  "in": 72.27,
  // inch
  "bp": 803 / 800,
  // big (PostScript) points
  "pc": 12,
  // pica
  "dd": 1238 / 1157,
  // didot
  "cc": 14856 / 1157,
  // cicero (12 didot)
  "nd": 685 / 642,
  // new didot
  "nc": 1370 / 107,
  // new cicero (12 new didot)
  "sp": 1 / 65536,
  // scaled point (TeX's internal smallest unit)
  // https://tex.stackexchange.com/a/41371
  "px": 803 / 800
  // \pdfpxdimen defaults to 1 bp in pdfTeX and LuaTeX
};
var relativeUnit = {
  "ex": true,
  "em": true,
  "mu": true
};
var validUnit = function validUnit2(unit) {
  if (typeof unit !== "string") {
    unit = unit.unit;
  }
  return unit in ptPerUnit || unit in relativeUnit || unit === "ex";
};
var calculateSize = function calculateSize2(sizeValue, options) {
  var scale;
  if (sizeValue.unit in ptPerUnit) {
    scale = ptPerUnit[sizeValue.unit] / options.fontMetrics().ptPerEm / options.sizeMultiplier;
  } else if (sizeValue.unit === "mu") {
    scale = options.fontMetrics().cssEmPerMu;
  } else {
    var unitOptions;
    if (options.style.isTight()) {
      unitOptions = options.havingStyle(options.style.text());
    } else {
      unitOptions = options;
    }
    if (sizeValue.unit === "ex") {
      scale = unitOptions.fontMetrics().xHeight;
    } else if (sizeValue.unit === "em") {
      scale = unitOptions.fontMetrics().quad;
    } else {
      throw new ParseError("Invalid unit: '" + sizeValue.unit + "'");
    }
    if (unitOptions !== options) {
      scale *= unitOptions.sizeMultiplier / options.sizeMultiplier;
    }
  }
  return Math.min(sizeValue.number * scale, options.maxSize);
};
var makeEm = function makeEm2(n) {
  return +n.toFixed(4) + "em";
};
var createClass = function createClass2(classes) {
  return classes.filter((cls) => cls).join(" ");
};
var initNode = function initNode2(classes, options, style2) {
  this.classes = classes || [];
  this.attributes = {};
  this.height = 0;
  this.depth = 0;
  this.maxFontSize = 0;
  this.style = style2 || {};
  if (options) {
    if (options.style.isTight()) {
      this.classes.push("mtight");
    }
    var color = options.getColor();
    if (color) {
      this.style.color = color;
    }
  }
};
var toNode = function toNode2(tagName) {
  var node = document.createElement(tagName);
  node.className = createClass(this.classes);
  for (var style2 in this.style) {
    if (this.style.hasOwnProperty(style2)) {
      node.style[style2] = this.style[style2];
    }
  }
  for (var attr in this.attributes) {
    if (this.attributes.hasOwnProperty(attr)) {
      node.setAttribute(attr, this.attributes[attr]);
    }
  }
  for (var i = 0; i < this.children.length; i++) {
    node.appendChild(this.children[i].toNode());
  }
  return node;
};
var invalidAttributeNameRegex = /[\s"'>/=\x00-\x1f]/;
var toMarkup = function toMarkup2(tagName) {
  var markup = "<" + tagName;
  if (this.classes.length) {
    markup += ' class="' + utils.escape(createClass(this.classes)) + '"';
  }
  var styles2 = "";
  for (var style2 in this.style) {
    if (this.style.hasOwnProperty(style2)) {
      styles2 += utils.hyphenate(style2) + ":" + this.style[style2] + ";";
    }
  }
  if (styles2) {
    markup += ' style="' + utils.escape(styles2) + '"';
  }
  for (var attr in this.attributes) {
    if (this.attributes.hasOwnProperty(attr)) {
      if (invalidAttributeNameRegex.test(attr)) {
        throw new ParseError("Invalid attribute name '" + attr + "'");
      }
      markup += " " + attr + '="' + utils.escape(this.attributes[attr]) + '"';
    }
  }
  markup += ">";
  for (var i = 0; i < this.children.length; i++) {
    markup += this.children[i].toMarkup();
  }
  markup += "</" + tagName + ">";
  return markup;
};
var Span = class {
  constructor(classes, children, options, style2) {
    this.children = void 0;
    this.attributes = void 0;
    this.classes = void 0;
    this.height = void 0;
    this.depth = void 0;
    this.width = void 0;
    this.maxFontSize = void 0;
    this.style = void 0;
    initNode.call(this, classes, options, style2);
    this.children = children || [];
  }
  /**
   * Sets an arbitrary attribute on the span. Warning: use this wisely. Not
   * all browsers support attributes the same, and having too many custom
   * attributes is probably bad.
   */
  setAttribute(attribute, value) {
    this.attributes[attribute] = value;
  }
  hasClass(className) {
    return utils.contains(this.classes, className);
  }
  toNode() {
    return toNode.call(this, "span");
  }
  toMarkup() {
    return toMarkup.call(this, "span");
  }
};
var Anchor = class {
  constructor(href, classes, children, options) {
    this.children = void 0;
    this.attributes = void 0;
    this.classes = void 0;
    this.height = void 0;
    this.depth = void 0;
    this.maxFontSize = void 0;
    this.style = void 0;
    initNode.call(this, classes, options);
    this.children = children || [];
    this.setAttribute("href", href);
  }
  setAttribute(attribute, value) {
    this.attributes[attribute] = value;
  }
  hasClass(className) {
    return utils.contains(this.classes, className);
  }
  toNode() {
    return toNode.call(this, "a");
  }
  toMarkup() {
    return toMarkup.call(this, "a");
  }
};
var Img = class {
  constructor(src, alt, style2) {
    this.src = void 0;
    this.alt = void 0;
    this.classes = void 0;
    this.height = void 0;
    this.depth = void 0;
    this.maxFontSize = void 0;
    this.style = void 0;
    this.alt = alt;
    this.src = src;
    this.classes = ["mord"];
    this.style = style2;
  }
  hasClass(className) {
    return utils.contains(this.classes, className);
  }
  toNode() {
    var node = document.createElement("img");
    node.src = this.src;
    node.alt = this.alt;
    node.className = "mord";
    for (var style2 in this.style) {
      if (this.style.hasOwnProperty(style2)) {
        node.style[style2] = this.style[style2];
      }
    }
    return node;
  }
  toMarkup() {
    var markup = '<img src="' + utils.escape(this.src) + '"' + (' alt="' + utils.escape(this.alt) + '"');
    var styles2 = "";
    for (var style2 in this.style) {
      if (this.style.hasOwnProperty(style2)) {
        styles2 += utils.hyphenate(style2) + ":" + this.style[style2] + ";";
      }
    }
    if (styles2) {
      markup += ' style="' + utils.escape(styles2) + '"';
    }
    markup += "'/>";
    return markup;
  }
};
var iCombinations = {
  "\xEE": "\u0131\u0302",
  "\xEF": "\u0131\u0308",
  "\xED": "\u0131\u0301",
  // 'ī': '\u0131\u0304', // enable when we add Extended Latin
  "\xEC": "\u0131\u0300"
};
var SymbolNode = class {
  constructor(text5, height, depth, italic, skew, width, classes, style2) {
    this.text = void 0;
    this.height = void 0;
    this.depth = void 0;
    this.italic = void 0;
    this.skew = void 0;
    this.width = void 0;
    this.maxFontSize = void 0;
    this.classes = void 0;
    this.style = void 0;
    this.text = text5;
    this.height = height || 0;
    this.depth = depth || 0;
    this.italic = italic || 0;
    this.skew = skew || 0;
    this.width = width || 0;
    this.classes = classes || [];
    this.style = style2 || {};
    this.maxFontSize = 0;
    var script = scriptFromCodepoint(this.text.charCodeAt(0));
    if (script) {
      this.classes.push(script + "_fallback");
    }
    if (/[îïíì]/.test(this.text)) {
      this.text = iCombinations[this.text];
    }
  }
  hasClass(className) {
    return utils.contains(this.classes, className);
  }
  /**
   * Creates a text node or span from a symbol node. Note that a span is only
   * created if it is needed.
   */
  toNode() {
    var node = document.createTextNode(this.text);
    var span = null;
    if (this.italic > 0) {
      span = document.createElement("span");
      span.style.marginRight = makeEm(this.italic);
    }
    if (this.classes.length > 0) {
      span = span || document.createElement("span");
      span.className = createClass(this.classes);
    }
    for (var style2 in this.style) {
      if (this.style.hasOwnProperty(style2)) {
        span = span || document.createElement("span");
        span.style[style2] = this.style[style2];
      }
    }
    if (span) {
      span.appendChild(node);
      return span;
    } else {
      return node;
    }
  }
  /**
   * Creates markup for a symbol node.
   */
  toMarkup() {
    var needsSpan = false;
    var markup = "<span";
    if (this.classes.length) {
      needsSpan = true;
      markup += ' class="';
      markup += utils.escape(createClass(this.classes));
      markup += '"';
    }
    var styles2 = "";
    if (this.italic > 0) {
      styles2 += "margin-right:" + this.italic + "em;";
    }
    for (var style2 in this.style) {
      if (this.style.hasOwnProperty(style2)) {
        styles2 += utils.hyphenate(style2) + ":" + this.style[style2] + ";";
      }
    }
    if (styles2) {
      needsSpan = true;
      markup += ' style="' + utils.escape(styles2) + '"';
    }
    var escaped = utils.escape(this.text);
    if (needsSpan) {
      markup += ">";
      markup += escaped;
      markup += "</span>";
      return markup;
    } else {
      return escaped;
    }
  }
};
var SvgNode = class {
  constructor(children, attributes) {
    this.children = void 0;
    this.attributes = void 0;
    this.children = children || [];
    this.attributes = attributes || {};
  }
  toNode() {
    var svgNS = "http://www.w3.org/2000/svg";
    var node = document.createElementNS(svgNS, "svg");
    for (var attr in this.attributes) {
      if (Object.prototype.hasOwnProperty.call(this.attributes, attr)) {
        node.setAttribute(attr, this.attributes[attr]);
      }
    }
    for (var i = 0; i < this.children.length; i++) {
      node.appendChild(this.children[i].toNode());
    }
    return node;
  }
  toMarkup() {
    var markup = '<svg xmlns="http://www.w3.org/2000/svg"';
    for (var attr in this.attributes) {
      if (Object.prototype.hasOwnProperty.call(this.attributes, attr)) {
        markup += " " + attr + '="' + utils.escape(this.attributes[attr]) + '"';
      }
    }
    markup += ">";
    for (var i = 0; i < this.children.length; i++) {
      markup += this.children[i].toMarkup();
    }
    markup += "</svg>";
    return markup;
  }
};
var PathNode = class {
  constructor(pathName, alternate) {
    this.pathName = void 0;
    this.alternate = void 0;
    this.pathName = pathName;
    this.alternate = alternate;
  }
  toNode() {
    var svgNS = "http://www.w3.org/2000/svg";
    var node = document.createElementNS(svgNS, "path");
    if (this.alternate) {
      node.setAttribute("d", this.alternate);
    } else {
      node.setAttribute("d", path[this.pathName]);
    }
    return node;
  }
  toMarkup() {
    if (this.alternate) {
      return '<path d="' + utils.escape(this.alternate) + '"/>';
    } else {
      return '<path d="' + utils.escape(path[this.pathName]) + '"/>';
    }
  }
};
var LineNode = class {
  constructor(attributes) {
    this.attributes = void 0;
    this.attributes = attributes || {};
  }
  toNode() {
    var svgNS = "http://www.w3.org/2000/svg";
    var node = document.createElementNS(svgNS, "line");
    for (var attr in this.attributes) {
      if (Object.prototype.hasOwnProperty.call(this.attributes, attr)) {
        node.setAttribute(attr, this.attributes[attr]);
      }
    }
    return node;
  }
  toMarkup() {
    var markup = "<line";
    for (var attr in this.attributes) {
      if (Object.prototype.hasOwnProperty.call(this.attributes, attr)) {
        markup += " " + attr + '="' + utils.escape(this.attributes[attr]) + '"';
      }
    }
    markup += "/>";
    return markup;
  }
};
function assertSymbolDomNode(group) {
  if (group instanceof SymbolNode) {
    return group;
  } else {
    throw new Error("Expected symbolNode but got " + String(group) + ".");
  }
}
function assertSpan(group) {
  if (group instanceof Span) {
    return group;
  } else {
    throw new Error("Expected span<HtmlDomNode> but got " + String(group) + ".");
  }
}
var ATOMS = {
  "bin": 1,
  "close": 1,
  "inner": 1,
  "open": 1,
  "punct": 1,
  "rel": 1
};
var NON_ATOMS = {
  "accent-token": 1,
  "mathord": 1,
  "op-token": 1,
  "spacing": 1,
  "textord": 1
};
var symbols = {
  "math": {},
  "text": {}
};
function defineSymbol(mode, font, group, replace2, name, acceptUnicodeChar) {
  symbols[mode][name] = {
    font,
    group,
    replace: replace2
  };
  if (acceptUnicodeChar && replace2) {
    symbols[mode][replace2] = symbols[mode][name];
  }
}
var math = "math";
var text = "text";
var main = "main";
var ams = "ams";
var accent = "accent-token";
var bin = "bin";
var close2 = "close";
var inner = "inner";
var mathord = "mathord";
var op = "op-token";
var open = "open";
var punct = "punct";
var rel = "rel";
var spacing = "spacing";
var textord = "textord";
defineSymbol(math, main, rel, "\u2261", "\\equiv", true);
defineSymbol(math, main, rel, "\u227A", "\\prec", true);
defineSymbol(math, main, rel, "\u227B", "\\succ", true);
defineSymbol(math, main, rel, "\u223C", "\\sim", true);
defineSymbol(math, main, rel, "\u22A5", "\\perp");
defineSymbol(math, main, rel, "\u2AAF", "\\preceq", true);
defineSymbol(math, main, rel, "\u2AB0", "\\succeq", true);
defineSymbol(math, main, rel, "\u2243", "\\simeq", true);
defineSymbol(math, main, rel, "\u2223", "\\mid", true);
defineSymbol(math, main, rel, "\u226A", "\\ll", true);
defineSymbol(math, main, rel, "\u226B", "\\gg", true);
defineSymbol(math, main, rel, "\u224D", "\\asymp", true);
defineSymbol(math, main, rel, "\u2225", "\\parallel");
defineSymbol(math, main, rel, "\u22C8", "\\bowtie", true);
defineSymbol(math, main, rel, "\u2323", "\\smile", true);
defineSymbol(math, main, rel, "\u2291", "\\sqsubseteq", true);
defineSymbol(math, main, rel, "\u2292", "\\sqsupseteq", true);
defineSymbol(math, main, rel, "\u2250", "\\doteq", true);
defineSymbol(math, main, rel, "\u2322", "\\frown", true);
defineSymbol(math, main, rel, "\u220B", "\\ni", true);
defineSymbol(math, main, rel, "\u221D", "\\propto", true);
defineSymbol(math, main, rel, "\u22A2", "\\vdash", true);
defineSymbol(math, main, rel, "\u22A3", "\\dashv", true);
defineSymbol(math, main, rel, "\u220B", "\\owns");
defineSymbol(math, main, punct, ".", "\\ldotp");
defineSymbol(math, main, punct, "\u22C5", "\\cdotp");
defineSymbol(math, main, textord, "#", "\\#");
defineSymbol(text, main, textord, "#", "\\#");
defineSymbol(math, main, textord, "&", "\\&");
defineSymbol(text, main, textord, "&", "\\&");
defineSymbol(math, main, textord, "\u2135", "\\aleph", true);
defineSymbol(math, main, textord, "\u2200", "\\forall", true);
defineSymbol(math, main, textord, "\u210F", "\\hbar", true);
defineSymbol(math, main, textord, "\u2203", "\\exists", true);
defineSymbol(math, main, textord, "\u2207", "\\nabla", true);
defineSymbol(math, main, textord, "\u266D", "\\flat", true);
defineSymbol(math, main, textord, "\u2113", "\\ell", true);
defineSymbol(math, main, textord, "\u266E", "\\natural", true);
defineSymbol(math, main, textord, "\u2663", "\\clubsuit", true);
defineSymbol(math, main, textord, "\u2118", "\\wp", true);
defineSymbol(math, main, textord, "\u266F", "\\sharp", true);
defineSymbol(math, main, textord, "\u2662", "\\diamondsuit", true);
defineSymbol(math, main, textord, "\u211C", "\\Re", true);
defineSymbol(math, main, textord, "\u2661", "\\heartsuit", true);
defineSymbol(math, main, textord, "\u2111", "\\Im", true);
defineSymbol(math, main, textord, "\u2660", "\\spadesuit", true);
defineSymbol(math, main, textord, "\xA7", "\\S", true);
defineSymbol(text, main, textord, "\xA7", "\\S");
defineSymbol(math, main, textord, "\xB6", "\\P", true);
defineSymbol(text, main, textord, "\xB6", "\\P");
defineSymbol(math, main, textord, "\u2020", "\\dag");
defineSymbol(text, main, textord, "\u2020", "\\dag");
defineSymbol(text, main, textord, "\u2020", "\\textdagger");
defineSymbol(math, main, textord, "\u2021", "\\ddag");
defineSymbol(text, main, textord, "\u2021", "\\ddag");
defineSymbol(text, main, textord, "\u2021", "\\textdaggerdbl");
defineSymbol(math, main, close2, "\u23B1", "\\rmoustache", true);
defineSymbol(math, main, open, "\u23B0", "\\lmoustache", true);
defineSymbol(math, main, close2, "\u27EF", "\\rgroup", true);
defineSymbol(math, main, open, "\u27EE", "\\lgroup", true);
defineSymbol(math, main, bin, "\u2213", "\\mp", true);
defineSymbol(math, main, bin, "\u2296", "\\ominus", true);
defineSymbol(math, main, bin, "\u228E", "\\uplus", true);
defineSymbol(math, main, bin, "\u2293", "\\sqcap", true);
defineSymbol(math, main, bin, "\u2217", "\\ast");
defineSymbol(math, main, bin, "\u2294", "\\sqcup", true);
defineSymbol(math, main, bin, "\u25EF", "\\bigcirc", true);
defineSymbol(math, main, bin, "\u2219", "\\bullet", true);
defineSymbol(math, main, bin, "\u2021", "\\ddagger");
defineSymbol(math, main, bin, "\u2240", "\\wr", true);
defineSymbol(math, main, bin, "\u2A3F", "\\amalg");
defineSymbol(math, main, bin, "&", "\\And");
defineSymbol(math, main, rel, "\u27F5", "\\longleftarrow", true);
defineSymbol(math, main, rel, "\u21D0", "\\Leftarrow", true);
defineSymbol(math, main, rel, "\u27F8", "\\Longleftarrow", true);
defineSymbol(math, main, rel, "\u27F6", "\\longrightarrow", true);
defineSymbol(math, main, rel, "\u21D2", "\\Rightarrow", true);
defineSymbol(math, main, rel, "\u27F9", "\\Longrightarrow", true);
defineSymbol(math, main, rel, "\u2194", "\\leftrightarrow", true);
defineSymbol(math, main, rel, "\u27F7", "\\longleftrightarrow", true);
defineSymbol(math, main, rel, "\u21D4", "\\Leftrightarrow", true);
defineSymbol(math, main, rel, "\u27FA", "\\Longleftrightarrow", true);
defineSymbol(math, main, rel, "\u21A6", "\\mapsto", true);
defineSymbol(math, main, rel, "\u27FC", "\\longmapsto", true);
defineSymbol(math, main, rel, "\u2197", "\\nearrow", true);
defineSymbol(math, main, rel, "\u21A9", "\\hookleftarrow", true);
defineSymbol(math, main, rel, "\u21AA", "\\hookrightarrow", true);
defineSymbol(math, main, rel, "\u2198", "\\searrow", true);
defineSymbol(math, main, rel, "\u21BC", "\\leftharpoonup", true);
defineSymbol(math, main, rel, "\u21C0", "\\rightharpoonup", true);
defineSymbol(math, main, rel, "\u2199", "\\swarrow", true);
defineSymbol(math, main, rel, "\u21BD", "\\leftharpoondown", true);
defineSymbol(math, main, rel, "\u21C1", "\\rightharpoondown", true);
defineSymbol(math, main, rel, "\u2196", "\\nwarrow", true);
defineSymbol(math, main, rel, "\u21CC", "\\rightleftharpoons", true);
defineSymbol(math, ams, rel, "\u226E", "\\nless", true);
defineSymbol(math, ams, rel, "\uE010", "\\@nleqslant");
defineSymbol(math, ams, rel, "\uE011", "\\@nleqq");
defineSymbol(math, ams, rel, "\u2A87", "\\lneq", true);
defineSymbol(math, ams, rel, "\u2268", "\\lneqq", true);
defineSymbol(math, ams, rel, "\uE00C", "\\@lvertneqq");
defineSymbol(math, ams, rel, "\u22E6", "\\lnsim", true);
defineSymbol(math, ams, rel, "\u2A89", "\\lnapprox", true);
defineSymbol(math, ams, rel, "\u2280", "\\nprec", true);
defineSymbol(math, ams, rel, "\u22E0", "\\npreceq", true);
defineSymbol(math, ams, rel, "\u22E8", "\\precnsim", true);
defineSymbol(math, ams, rel, "\u2AB9", "\\precnapprox", true);
defineSymbol(math, ams, rel, "\u2241", "\\nsim", true);
defineSymbol(math, ams, rel, "\uE006", "\\@nshortmid");
defineSymbol(math, ams, rel, "\u2224", "\\nmid", true);
defineSymbol(math, ams, rel, "\u22AC", "\\nvdash", true);
defineSymbol(math, ams, rel, "\u22AD", "\\nvDash", true);
defineSymbol(math, ams, rel, "\u22EA", "\\ntriangleleft");
defineSymbol(math, ams, rel, "\u22EC", "\\ntrianglelefteq", true);
defineSymbol(math, ams, rel, "\u228A", "\\subsetneq", true);
defineSymbol(math, ams, rel, "\uE01A", "\\@varsubsetneq");
defineSymbol(math, ams, rel, "\u2ACB", "\\subsetneqq", true);
defineSymbol(math, ams, rel, "\uE017", "\\@varsubsetneqq");
defineSymbol(math, ams, rel, "\u226F", "\\ngtr", true);
defineSymbol(math, ams, rel, "\uE00F", "\\@ngeqslant");
defineSymbol(math, ams, rel, "\uE00E", "\\@ngeqq");
defineSymbol(math, ams, rel, "\u2A88", "\\gneq", true);
defineSymbol(math, ams, rel, "\u2269", "\\gneqq", true);
defineSymbol(math, ams, rel, "\uE00D", "\\@gvertneqq");
defineSymbol(math, ams, rel, "\u22E7", "\\gnsim", true);
defineSymbol(math, ams, rel, "\u2A8A", "\\gnapprox", true);
defineSymbol(math, ams, rel, "\u2281", "\\nsucc", true);
defineSymbol(math, ams, rel, "\u22E1", "\\nsucceq", true);
defineSymbol(math, ams, rel, "\u22E9", "\\succnsim", true);
defineSymbol(math, ams, rel, "\u2ABA", "\\succnapprox", true);
defineSymbol(math, ams, rel, "\u2246", "\\ncong", true);
defineSymbol(math, ams, rel, "\uE007", "\\@nshortparallel");
defineSymbol(math, ams, rel, "\u2226", "\\nparallel", true);
defineSymbol(math, ams, rel, "\u22AF", "\\nVDash", true);
defineSymbol(math, ams, rel, "\u22EB", "\\ntriangleright");
defineSymbol(math, ams, rel, "\u22ED", "\\ntrianglerighteq", true);
defineSymbol(math, ams, rel, "\uE018", "\\@nsupseteqq");
defineSymbol(math, ams, rel, "\u228B", "\\supsetneq", true);
defineSymbol(math, ams, rel, "\uE01B", "\\@varsupsetneq");
defineSymbol(math, ams, rel, "\u2ACC", "\\supsetneqq", true);
defineSymbol(math, ams, rel, "\uE019", "\\@varsupsetneqq");
defineSymbol(math, ams, rel, "\u22AE", "\\nVdash", true);
defineSymbol(math, ams, rel, "\u2AB5", "\\precneqq", true);
defineSymbol(math, ams, rel, "\u2AB6", "\\succneqq", true);
defineSymbol(math, ams, rel, "\uE016", "\\@nsubseteqq");
defineSymbol(math, ams, bin, "\u22B4", "\\unlhd");
defineSymbol(math, ams, bin, "\u22B5", "\\unrhd");
defineSymbol(math, ams, rel, "\u219A", "\\nleftarrow", true);
defineSymbol(math, ams, rel, "\u219B", "\\nrightarrow", true);
defineSymbol(math, ams, rel, "\u21CD", "\\nLeftarrow", true);
defineSymbol(math, ams, rel, "\u21CF", "\\nRightarrow", true);
defineSymbol(math, ams, rel, "\u21AE", "\\nleftrightarrow", true);
defineSymbol(math, ams, rel, "\u21CE", "\\nLeftrightarrow", true);
defineSymbol(math, ams, rel, "\u25B3", "\\vartriangle");
defineSymbol(math, ams, textord, "\u210F", "\\hslash");
defineSymbol(math, ams, textord, "\u25BD", "\\triangledown");
defineSymbol(math, ams, textord, "\u25CA", "\\lozenge");
defineSymbol(math, ams, textord, "\u24C8", "\\circledS");
defineSymbol(math, ams, textord, "\xAE", "\\circledR");
defineSymbol(text, ams, textord, "\xAE", "\\circledR");
defineSymbol(math, ams, textord, "\u2221", "\\measuredangle", true);
defineSymbol(math, ams, textord, "\u2204", "\\nexists");
defineSymbol(math, ams, textord, "\u2127", "\\mho");
defineSymbol(math, ams, textord, "\u2132", "\\Finv", true);
defineSymbol(math, ams, textord, "\u2141", "\\Game", true);
defineSymbol(math, ams, textord, "\u2035", "\\backprime");
defineSymbol(math, ams, textord, "\u25B2", "\\blacktriangle");
defineSymbol(math, ams, textord, "\u25BC", "\\blacktriangledown");
defineSymbol(math, ams, textord, "\u25A0", "\\blacksquare");
defineSymbol(math, ams, textord, "\u29EB", "\\blacklozenge");
defineSymbol(math, ams, textord, "\u2605", "\\bigstar");
defineSymbol(math, ams, textord, "\u2222", "\\sphericalangle", true);
defineSymbol(math, ams, textord, "\u2201", "\\complement", true);
defineSymbol(math, ams, textord, "\xF0", "\\eth", true);
defineSymbol(text, main, textord, "\xF0", "\xF0");
defineSymbol(math, ams, textord, "\u2571", "\\diagup");
defineSymbol(math, ams, textord, "\u2572", "\\diagdown");
defineSymbol(math, ams, textord, "\u25A1", "\\square");
defineSymbol(math, ams, textord, "\u25A1", "\\Box");
defineSymbol(math, ams, textord, "\u25CA", "\\Diamond");
defineSymbol(math, ams, textord, "\xA5", "\\yen", true);
defineSymbol(text, ams, textord, "\xA5", "\\yen", true);
defineSymbol(math, ams, textord, "\u2713", "\\checkmark", true);
defineSymbol(text, ams, textord, "\u2713", "\\checkmark");
defineSymbol(math, ams, textord, "\u2136", "\\beth", true);
defineSymbol(math, ams, textord, "\u2138", "\\daleth", true);
defineSymbol(math, ams, textord, "\u2137", "\\gimel", true);
defineSymbol(math, ams, textord, "\u03DD", "\\digamma", true);
defineSymbol(math, ams, textord, "\u03F0", "\\varkappa");
defineSymbol(math, ams, open, "\u250C", "\\@ulcorner", true);
defineSymbol(math, ams, close2, "\u2510", "\\@urcorner", true);
defineSymbol(math, ams, open, "\u2514", "\\@llcorner", true);
defineSymbol(math, ams, close2, "\u2518", "\\@lrcorner", true);
defineSymbol(math, ams, rel, "\u2266", "\\leqq", true);
defineSymbol(math, ams, rel, "\u2A7D", "\\leqslant", true);
defineSymbol(math, ams, rel, "\u2A95", "\\eqslantless", true);
defineSymbol(math, ams, rel, "\u2272", "\\lesssim", true);
defineSymbol(math, ams, rel, "\u2A85", "\\lessapprox", true);
defineSymbol(math, ams, rel, "\u224A", "\\approxeq", true);
defineSymbol(math, ams, bin, "\u22D6", "\\lessdot");
defineSymbol(math, ams, rel, "\u22D8", "\\lll", true);
defineSymbol(math, ams, rel, "\u2276", "\\lessgtr", true);
defineSymbol(math, ams, rel, "\u22DA", "\\lesseqgtr", true);
defineSymbol(math, ams, rel, "\u2A8B", "\\lesseqqgtr", true);
defineSymbol(math, ams, rel, "\u2251", "\\doteqdot");
defineSymbol(math, ams, rel, "\u2253", "\\risingdotseq", true);
defineSymbol(math, ams, rel, "\u2252", "\\fallingdotseq", true);
defineSymbol(math, ams, rel, "\u223D", "\\backsim", true);
defineSymbol(math, ams, rel, "\u22CD", "\\backsimeq", true);
defineSymbol(math, ams, rel, "\u2AC5", "\\subseteqq", true);
defineSymbol(math, ams, rel, "\u22D0", "\\Subset", true);
defineSymbol(math, ams, rel, "\u228F", "\\sqsubset", true);
defineSymbol(math, ams, rel, "\u227C", "\\preccurlyeq", true);
defineSymbol(math, ams, rel, "\u22DE", "\\curlyeqprec", true);
defineSymbol(math, ams, rel, "\u227E", "\\precsim", true);
defineSymbol(math, ams, rel, "\u2AB7", "\\precapprox", true);
defineSymbol(math, ams, rel, "\u22B2", "\\vartriangleleft");
defineSymbol(math, ams, rel, "\u22B4", "\\trianglelefteq");
defineSymbol(math, ams, rel, "\u22A8", "\\vDash", true);
defineSymbol(math, ams, rel, "\u22AA", "\\Vvdash", true);
defineSymbol(math, ams, rel, "\u2323", "\\smallsmile");
defineSymbol(math, ams, rel, "\u2322", "\\smallfrown");
defineSymbol(math, ams, rel, "\u224F", "\\bumpeq", true);
defineSymbol(math, ams, rel, "\u224E", "\\Bumpeq", true);
defineSymbol(math, ams, rel, "\u2267", "\\geqq", true);
defineSymbol(math, ams, rel, "\u2A7E", "\\geqslant", true);
defineSymbol(math, ams, rel, "\u2A96", "\\eqslantgtr", true);
defineSymbol(math, ams, rel, "\u2273", "\\gtrsim", true);
defineSymbol(math, ams, rel, "\u2A86", "\\gtrapprox", true);
defineSymbol(math, ams, bin, "\u22D7", "\\gtrdot");
defineSymbol(math, ams, rel, "\u22D9", "\\ggg", true);
defineSymbol(math, ams, rel, "\u2277", "\\gtrless", true);
defineSymbol(math, ams, rel, "\u22DB", "\\gtreqless", true);
defineSymbol(math, ams, rel, "\u2A8C", "\\gtreqqless", true);
defineSymbol(math, ams, rel, "\u2256", "\\eqcirc", true);
defineSymbol(math, ams, rel, "\u2257", "\\circeq", true);
defineSymbol(math, ams, rel, "\u225C", "\\triangleq", true);
defineSymbol(math, ams, rel, "\u223C", "\\thicksim");
defineSymbol(math, ams, rel, "\u2248", "\\thickapprox");
defineSymbol(math, ams, rel, "\u2AC6", "\\supseteqq", true);
defineSymbol(math, ams, rel, "\u22D1", "\\Supset", true);
defineSymbol(math, ams, rel, "\u2290", "\\sqsupset", true);
defineSymbol(math, ams, rel, "\u227D", "\\succcurlyeq", true);
defineSymbol(math, ams, rel, "\u22DF", "\\curlyeqsucc", true);
defineSymbol(math, ams, rel, "\u227F", "\\succsim", true);
defineSymbol(math, ams, rel, "\u2AB8", "\\succapprox", true);
defineSymbol(math, ams, rel, "\u22B3", "\\vartriangleright");
defineSymbol(math, ams, rel, "\u22B5", "\\trianglerighteq");
defineSymbol(math, ams, rel, "\u22A9", "\\Vdash", true);
defineSymbol(math, ams, rel, "\u2223", "\\shortmid");
defineSymbol(math, ams, rel, "\u2225", "\\shortparallel");
defineSymbol(math, ams, rel, "\u226C", "\\between", true);
defineSymbol(math, ams, rel, "\u22D4", "\\pitchfork", true);
defineSymbol(math, ams, rel, "\u221D", "\\varpropto");
defineSymbol(math, ams, rel, "\u25C0", "\\blacktriangleleft");
defineSymbol(math, ams, rel, "\u2234", "\\therefore", true);
defineSymbol(math, ams, rel, "\u220D", "\\backepsilon");
defineSymbol(math, ams, rel, "\u25B6", "\\blacktriangleright");
defineSymbol(math, ams, rel, "\u2235", "\\because", true);
defineSymbol(math, ams, rel, "\u22D8", "\\llless");
defineSymbol(math, ams, rel, "\u22D9", "\\gggtr");
defineSymbol(math, ams, bin, "\u22B2", "\\lhd");
defineSymbol(math, ams, bin, "\u22B3", "\\rhd");
defineSymbol(math, ams, rel, "\u2242", "\\eqsim", true);
defineSymbol(math, main, rel, "\u22C8", "\\Join");
defineSymbol(math, ams, rel, "\u2251", "\\Doteq", true);
defineSymbol(math, ams, bin, "\u2214", "\\dotplus", true);
defineSymbol(math, ams, bin, "\u2216", "\\smallsetminus");
defineSymbol(math, ams, bin, "\u22D2", "\\Cap", true);
defineSymbol(math, ams, bin, "\u22D3", "\\Cup", true);
defineSymbol(math, ams, bin, "\u2A5E", "\\doublebarwedge", true);
defineSymbol(math, ams, bin, "\u229F", "\\boxminus", true);
defineSymbol(math, ams, bin, "\u229E", "\\boxplus", true);
defineSymbol(math, ams, bin, "\u22C7", "\\divideontimes", true);
defineSymbol(math, ams, bin, "\u22C9", "\\ltimes", true);
defineSymbol(math, ams, bin, "\u22CA", "\\rtimes", true);
defineSymbol(math, ams, bin, "\u22CB", "\\leftthreetimes", true);
defineSymbol(math, ams, bin, "\u22CC", "\\rightthreetimes", true);
defineSymbol(math, ams, bin, "\u22CF", "\\curlywedge", true);
defineSymbol(math, ams, bin, "\u22CE", "\\curlyvee", true);
defineSymbol(math, ams, bin, "\u229D", "\\circleddash", true);
defineSymbol(math, ams, bin, "\u229B", "\\circledast", true);
defineSymbol(math, ams, bin, "\u22C5", "\\centerdot");
defineSymbol(math, ams, bin, "\u22BA", "\\intercal", true);
defineSymbol(math, ams, bin, "\u22D2", "\\doublecap");
defineSymbol(math, ams, bin, "\u22D3", "\\doublecup");
defineSymbol(math, ams, bin, "\u22A0", "\\boxtimes", true);
defineSymbol(math, ams, rel, "\u21E2", "\\dashrightarrow", true);
defineSymbol(math, ams, rel, "\u21E0", "\\dashleftarrow", true);
defineSymbol(math, ams, rel, "\u21C7", "\\leftleftarrows", true);
defineSymbol(math, ams, rel, "\u21C6", "\\leftrightarrows", true);
defineSymbol(math, ams, rel, "\u21DA", "\\Lleftarrow", true);
defineSymbol(math, ams, rel, "\u219E", "\\twoheadleftarrow", true);
defineSymbol(math, ams, rel, "\u21A2", "\\leftarrowtail", true);
defineSymbol(math, ams, rel, "\u21AB", "\\looparrowleft", true);
defineSymbol(math, ams, rel, "\u21CB", "\\leftrightharpoons", true);
defineSymbol(math, ams, rel, "\u21B6", "\\curvearrowleft", true);
defineSymbol(math, ams, rel, "\u21BA", "\\circlearrowleft", true);
defineSymbol(math, ams, rel, "\u21B0", "\\Lsh", true);
defineSymbol(math, ams, rel, "\u21C8", "\\upuparrows", true);
defineSymbol(math, ams, rel, "\u21BF", "\\upharpoonleft", true);
defineSymbol(math, ams, rel, "\u21C3", "\\downharpoonleft", true);
defineSymbol(math, main, rel, "\u22B6", "\\origof", true);
defineSymbol(math, main, rel, "\u22B7", "\\imageof", true);
defineSymbol(math, ams, rel, "\u22B8", "\\multimap", true);
defineSymbol(math, ams, rel, "\u21AD", "\\leftrightsquigarrow", true);
defineSymbol(math, ams, rel, "\u21C9", "\\rightrightarrows", true);
defineSymbol(math, ams, rel, "\u21C4", "\\rightleftarrows", true);
defineSymbol(math, ams, rel, "\u21A0", "\\twoheadrightarrow", true);
defineSymbol(math, ams, rel, "\u21A3", "\\rightarrowtail", true);
defineSymbol(math, ams, rel, "\u21AC", "\\looparrowright", true);
defineSymbol(math, ams, rel, "\u21B7", "\\curvearrowright", true);
defineSymbol(math, ams, rel, "\u21BB", "\\circlearrowright", true);
defineSymbol(math, ams, rel, "\u21B1", "\\Rsh", true);
defineSymbol(math, ams, rel, "\u21CA", "\\downdownarrows", true);
defineSymbol(math, ams, rel, "\u21BE", "\\upharpoonright", true);
defineSymbol(math, ams, rel, "\u21C2", "\\downharpoonright", true);
defineSymbol(math, ams, rel, "\u21DD", "\\rightsquigarrow", true);
defineSymbol(math, ams, rel, "\u21DD", "\\leadsto");
defineSymbol(math, ams, rel, "\u21DB", "\\Rrightarrow", true);
defineSymbol(math, ams, rel, "\u21BE", "\\restriction");
defineSymbol(math, main, textord, "\u2018", "`");
defineSymbol(math, main, textord, "$", "\\$");
defineSymbol(text, main, textord, "$", "\\$");
defineSymbol(text, main, textord, "$", "\\textdollar");
defineSymbol(math, main, textord, "%", "\\%");
defineSymbol(text, main, textord, "%", "\\%");
defineSymbol(math, main, textord, "_", "\\_");
defineSymbol(text, main, textord, "_", "\\_");
defineSymbol(text, main, textord, "_", "\\textunderscore");
defineSymbol(math, main, textord, "\u2220", "\\angle", true);
defineSymbol(math, main, textord, "\u221E", "\\infty", true);
defineSymbol(math, main, textord, "\u2032", "\\prime");
defineSymbol(math, main, textord, "\u25B3", "\\triangle");
defineSymbol(math, main, textord, "\u0393", "\\Gamma", true);
defineSymbol(math, main, textord, "\u0394", "\\Delta", true);
defineSymbol(math, main, textord, "\u0398", "\\Theta", true);
defineSymbol(math, main, textord, "\u039B", "\\Lambda", true);
defineSymbol(math, main, textord, "\u039E", "\\Xi", true);
defineSymbol(math, main, textord, "\u03A0", "\\Pi", true);
defineSymbol(math, main, textord, "\u03A3", "\\Sigma", true);
defineSymbol(math, main, textord, "\u03A5", "\\Upsilon", true);
defineSymbol(math, main, textord, "\u03A6", "\\Phi", true);
defineSymbol(math, main, textord, "\u03A8", "\\Psi", true);
defineSymbol(math, main, textord, "\u03A9", "\\Omega", true);
defineSymbol(math, main, textord, "A", "\u0391");
defineSymbol(math, main, textord, "B", "\u0392");
defineSymbol(math, main, textord, "E", "\u0395");
defineSymbol(math, main, textord, "Z", "\u0396");
defineSymbol(math, main, textord, "H", "\u0397");
defineSymbol(math, main, textord, "I", "\u0399");
defineSymbol(math, main, textord, "K", "\u039A");
defineSymbol(math, main, textord, "M", "\u039C");
defineSymbol(math, main, textord, "N", "\u039D");
defineSymbol(math, main, textord, "O", "\u039F");
defineSymbol(math, main, textord, "P", "\u03A1");
defineSymbol(math, main, textord, "T", "\u03A4");
defineSymbol(math, main, textord, "X", "\u03A7");
defineSymbol(math, main, textord, "\xAC", "\\neg", true);
defineSymbol(math, main, textord, "\xAC", "\\lnot");
defineSymbol(math, main, textord, "\u22A4", "\\top");
defineSymbol(math, main, textord, "\u22A5", "\\bot");
defineSymbol(math, main, textord, "\u2205", "\\emptyset");
defineSymbol(math, ams, textord, "\u2205", "\\varnothing");
defineSymbol(math, main, mathord, "\u03B1", "\\alpha", true);
defineSymbol(math, main, mathord, "\u03B2", "\\beta", true);
defineSymbol(math, main, mathord, "\u03B3", "\\gamma", true);
defineSymbol(math, main, mathord, "\u03B4", "\\delta", true);
defineSymbol(math, main, mathord, "\u03F5", "\\epsilon", true);
defineSymbol(math, main, mathord, "\u03B6", "\\zeta", true);
defineSymbol(math, main, mathord, "\u03B7", "\\eta", true);
defineSymbol(math, main, mathord, "\u03B8", "\\theta", true);
defineSymbol(math, main, mathord, "\u03B9", "\\iota", true);
defineSymbol(math, main, mathord, "\u03BA", "\\kappa", true);
defineSymbol(math, main, mathord, "\u03BB", "\\lambda", true);
defineSymbol(math, main, mathord, "\u03BC", "\\mu", true);
defineSymbol(math, main, mathord, "\u03BD", "\\nu", true);
defineSymbol(math, main, mathord, "\u03BE", "\\xi", true);
defineSymbol(math, main, mathord, "\u03BF", "\\omicron", true);
defineSymbol(math, main, mathord, "\u03C0", "\\pi", true);
defineSymbol(math, main, mathord, "\u03C1", "\\rho", true);
defineSymbol(math, main, mathord, "\u03C3", "\\sigma", true);
defineSymbol(math, main, mathord, "\u03C4", "\\tau", true);
defineSymbol(math, main, mathord, "\u03C5", "\\upsilon", true);
defineSymbol(math, main, mathord, "\u03D5", "\\phi", true);
defineSymbol(math, main, mathord, "\u03C7", "\\chi", true);
defineSymbol(math, main, mathord, "\u03C8", "\\psi", true);
defineSymbol(math, main, mathord, "\u03C9", "\\omega", true);
defineSymbol(math, main, mathord, "\u03B5", "\\varepsilon", true);
defineSymbol(math, main, mathord, "\u03D1", "\\vartheta", true);
defineSymbol(math, main, mathord, "\u03D6", "\\varpi", true);
defineSymbol(math, main, mathord, "\u03F1", "\\varrho", true);
defineSymbol(math, main, mathord, "\u03C2", "\\varsigma", true);
defineSymbol(math, main, mathord, "\u03C6", "\\varphi", true);
defineSymbol(math, main, bin, "\u2217", "*", true);
defineSymbol(math, main, bin, "+", "+");
defineSymbol(math, main, bin, "\u2212", "-", true);
defineSymbol(math, main, bin, "\u22C5", "\\cdot", true);
defineSymbol(math, main, bin, "\u2218", "\\circ", true);
defineSymbol(math, main, bin, "\xF7", "\\div", true);
defineSymbol(math, main, bin, "\xB1", "\\pm", true);
defineSymbol(math, main, bin, "\xD7", "\\times", true);
defineSymbol(math, main, bin, "\u2229", "\\cap", true);
defineSymbol(math, main, bin, "\u222A", "\\cup", true);
defineSymbol(math, main, bin, "\u2216", "\\setminus", true);
defineSymbol(math, main, bin, "\u2227", "\\land");
defineSymbol(math, main, bin, "\u2228", "\\lor");
defineSymbol(math, main, bin, "\u2227", "\\wedge", true);
defineSymbol(math, main, bin, "\u2228", "\\vee", true);
defineSymbol(math, main, textord, "\u221A", "\\surd");
defineSymbol(math, main, open, "\u27E8", "\\langle", true);
defineSymbol(math, main, open, "\u2223", "\\lvert");
defineSymbol(math, main, open, "\u2225", "\\lVert");
defineSymbol(math, main, close2, "?", "?");
defineSymbol(math, main, close2, "!", "!");
defineSymbol(math, main, close2, "\u27E9", "\\rangle", true);
defineSymbol(math, main, close2, "\u2223", "\\rvert");
defineSymbol(math, main, close2, "\u2225", "\\rVert");
defineSymbol(math, main, rel, "=", "=");
defineSymbol(math, main, rel, ":", ":");
defineSymbol(math, main, rel, "\u2248", "\\approx", true);
defineSymbol(math, main, rel, "\u2245", "\\cong", true);
defineSymbol(math, main, rel, "\u2265", "\\ge");
defineSymbol(math, main, rel, "\u2265", "\\geq", true);
defineSymbol(math, main, rel, "\u2190", "\\gets");
defineSymbol(math, main, rel, ">", "\\gt", true);
defineSymbol(math, main, rel, "\u2208", "\\in", true);
defineSymbol(math, main, rel, "\uE020", "\\@not");
defineSymbol(math, main, rel, "\u2282", "\\subset", true);
defineSymbol(math, main, rel, "\u2283", "\\supset", true);
defineSymbol(math, main, rel, "\u2286", "\\subseteq", true);
defineSymbol(math, main, rel, "\u2287", "\\supseteq", true);
defineSymbol(math, ams, rel, "\u2288", "\\nsubseteq", true);
defineSymbol(math, ams, rel, "\u2289", "\\nsupseteq", true);
defineSymbol(math, main, rel, "\u22A8", "\\models");
defineSymbol(math, main, rel, "\u2190", "\\leftarrow", true);
defineSymbol(math, main, rel, "\u2264", "\\le");
defineSymbol(math, main, rel, "\u2264", "\\leq", true);
defineSymbol(math, main, rel, "<", "\\lt", true);
defineSymbol(math, main, rel, "\u2192", "\\rightarrow", true);
defineSymbol(math, main, rel, "\u2192", "\\to");
defineSymbol(math, ams, rel, "\u2271", "\\ngeq", true);
defineSymbol(math, ams, rel, "\u2270", "\\nleq", true);
defineSymbol(math, main, spacing, "\xA0", "\\ ");
defineSymbol(math, main, spacing, "\xA0", "\\space");
defineSymbol(math, main, spacing, "\xA0", "\\nobreakspace");
defineSymbol(text, main, spacing, "\xA0", "\\ ");
defineSymbol(text, main, spacing, "\xA0", " ");
defineSymbol(text, main, spacing, "\xA0", "\\space");
defineSymbol(text, main, spacing, "\xA0", "\\nobreakspace");
defineSymbol(math, main, spacing, null, "\\nobreak");
defineSymbol(math, main, spacing, null, "\\allowbreak");
defineSymbol(math, main, punct, ",", ",");
defineSymbol(math, main, punct, ";", ";");
defineSymbol(math, ams, bin, "\u22BC", "\\barwedge", true);
defineSymbol(math, ams, bin, "\u22BB", "\\veebar", true);
defineSymbol(math, main, bin, "\u2299", "\\odot", true);
defineSymbol(math, main, bin, "\u2295", "\\oplus", true);
defineSymbol(math, main, bin, "\u2297", "\\otimes", true);
defineSymbol(math, main, textord, "\u2202", "\\partial", true);
defineSymbol(math, main, bin, "\u2298", "\\oslash", true);
defineSymbol(math, ams, bin, "\u229A", "\\circledcirc", true);
defineSymbol(math, ams, bin, "\u22A1", "\\boxdot", true);
defineSymbol(math, main, bin, "\u25B3", "\\bigtriangleup");
defineSymbol(math, main, bin, "\u25BD", "\\bigtriangledown");
defineSymbol(math, main, bin, "\u2020", "\\dagger");
defineSymbol(math, main, bin, "\u22C4", "\\diamond");
defineSymbol(math, main, bin, "\u22C6", "\\star");
defineSymbol(math, main, bin, "\u25C3", "\\triangleleft");
defineSymbol(math, main, bin, "\u25B9", "\\triangleright");
defineSymbol(math, main, open, "{", "\\{");
defineSymbol(text, main, textord, "{", "\\{");
defineSymbol(text, main, textord, "{", "\\textbraceleft");
defineSymbol(math, main, close2, "}", "\\}");
defineSymbol(text, main, textord, "}", "\\}");
defineSymbol(text, main, textord, "}", "\\textbraceright");
defineSymbol(math, main, open, "{", "\\lbrace");
defineSymbol(math, main, close2, "}", "\\rbrace");
defineSymbol(math, main, open, "[", "\\lbrack", true);
defineSymbol(text, main, textord, "[", "\\lbrack", true);
defineSymbol(math, main, close2, "]", "\\rbrack", true);
defineSymbol(text, main, textord, "]", "\\rbrack", true);
defineSymbol(math, main, open, "(", "\\lparen", true);
defineSymbol(math, main, close2, ")", "\\rparen", true);
defineSymbol(text, main, textord, "<", "\\textless", true);
defineSymbol(text, main, textord, ">", "\\textgreater", true);
defineSymbol(math, main, open, "\u230A", "\\lfloor", true);
defineSymbol(math, main, close2, "\u230B", "\\rfloor", true);
defineSymbol(math, main, open, "\u2308", "\\lceil", true);
defineSymbol(math, main, close2, "\u2309", "\\rceil", true);
defineSymbol(math, main, textord, "\\", "\\backslash");
defineSymbol(math, main, textord, "\u2223", "|");
defineSymbol(math, main, textord, "\u2223", "\\vert");
defineSymbol(text, main, textord, "|", "\\textbar", true);
defineSymbol(math, main, textord, "\u2225", "\\|");
defineSymbol(math, main, textord, "\u2225", "\\Vert");
defineSymbol(text, main, textord, "\u2225", "\\textbardbl");
defineSymbol(text, main, textord, "~", "\\textasciitilde");
defineSymbol(text, main, textord, "\\", "\\textbackslash");
defineSymbol(text, main, textord, "^", "\\textasciicircum");
defineSymbol(math, main, rel, "\u2191", "\\uparrow", true);
defineSymbol(math, main, rel, "\u21D1", "\\Uparrow", true);
defineSymbol(math, main, rel, "\u2193", "\\downarrow", true);
defineSymbol(math, main, rel, "\u21D3", "\\Downarrow", true);
defineSymbol(math, main, rel, "\u2195", "\\updownarrow", true);
defineSymbol(math, main, rel, "\u21D5", "\\Updownarrow", true);
defineSymbol(math, main, op, "\u2210", "\\coprod");
defineSymbol(math, main, op, "\u22C1", "\\bigvee");
defineSymbol(math, main, op, "\u22C0", "\\bigwedge");
defineSymbol(math, main, op, "\u2A04", "\\biguplus");
defineSymbol(math, main, op, "\u22C2", "\\bigcap");
defineSymbol(math, main, op, "\u22C3", "\\bigcup");
defineSymbol(math, main, op, "\u222B", "\\int");
defineSymbol(math, main, op, "\u222B", "\\intop");
defineSymbol(math, main, op, "\u222C", "\\iint");
defineSymbol(math, main, op, "\u222D", "\\iiint");
defineSymbol(math, main, op, "\u220F", "\\prod");
defineSymbol(math, main, op, "\u2211", "\\sum");
defineSymbol(math, main, op, "\u2A02", "\\bigotimes");
defineSymbol(math, main, op, "\u2A01", "\\bigoplus");
defineSymbol(math, main, op, "\u2A00", "\\bigodot");
defineSymbol(math, main, op, "\u222E", "\\oint");
defineSymbol(math, main, op, "\u222F", "\\oiint");
defineSymbol(math, main, op, "\u2230", "\\oiiint");
defineSymbol(math, main, op, "\u2A06", "\\bigsqcup");
defineSymbol(math, main, op, "\u222B", "\\smallint");
defineSymbol(text, main, inner, "\u2026", "\\textellipsis");
defineSymbol(math, main, inner, "\u2026", "\\mathellipsis");
defineSymbol(text, main, inner, "\u2026", "\\ldots", true);
defineSymbol(math, main, inner, "\u2026", "\\ldots", true);
defineSymbol(math, main, inner, "\u22EF", "\\@cdots", true);
defineSymbol(math, main, inner, "\u22F1", "\\ddots", true);
defineSymbol(math, main, textord, "\u22EE", "\\varvdots");
defineSymbol(text, main, textord, "\u22EE", "\\varvdots");
defineSymbol(math, main, accent, "\u02CA", "\\acute");
defineSymbol(math, main, accent, "\u02CB", "\\grave");
defineSymbol(math, main, accent, "\xA8", "\\ddot");
defineSymbol(math, main, accent, "~", "\\tilde");
defineSymbol(math, main, accent, "\u02C9", "\\bar");
defineSymbol(math, main, accent, "\u02D8", "\\breve");
defineSymbol(math, main, accent, "\u02C7", "\\check");
defineSymbol(math, main, accent, "^", "\\hat");
defineSymbol(math, main, accent, "\u20D7", "\\vec");
defineSymbol(math, main, accent, "\u02D9", "\\dot");
defineSymbol(math, main, accent, "\u02DA", "\\mathring");
defineSymbol(math, main, mathord, "\uE131", "\\@imath");
defineSymbol(math, main, mathord, "\uE237", "\\@jmath");
defineSymbol(math, main, textord, "\u0131", "\u0131");
defineSymbol(math, main, textord, "\u0237", "\u0237");
defineSymbol(text, main, textord, "\u0131", "\\i", true);
defineSymbol(text, main, textord, "\u0237", "\\j", true);
defineSymbol(text, main, textord, "\xDF", "\\ss", true);
defineSymbol(text, main, textord, "\xE6", "\\ae", true);
defineSymbol(text, main, textord, "\u0153", "\\oe", true);
defineSymbol(text, main, textord, "\xF8", "\\o", true);
defineSymbol(text, main, textord, "\xC6", "\\AE", true);
defineSymbol(text, main, textord, "\u0152", "\\OE", true);
defineSymbol(text, main, textord, "\xD8", "\\O", true);
defineSymbol(text, main, accent, "\u02CA", "\\'");
defineSymbol(text, main, accent, "\u02CB", "\\`");
defineSymbol(text, main, accent, "\u02C6", "\\^");
defineSymbol(text, main, accent, "\u02DC", "\\~");
defineSymbol(text, main, accent, "\u02C9", "\\=");
defineSymbol(text, main, accent, "\u02D8", "\\u");
defineSymbol(text, main, accent, "\u02D9", "\\.");
defineSymbol(text, main, accent, "\xB8", "\\c");
defineSymbol(text, main, accent, "\u02DA", "\\r");
defineSymbol(text, main, accent, "\u02C7", "\\v");
defineSymbol(text, main, accent, "\xA8", '\\"');
defineSymbol(text, main, accent, "\u02DD", "\\H");
defineSymbol(text, main, accent, "\u25EF", "\\textcircled");
var ligatures = {
  "--": true,
  "---": true,
  "``": true,
  "''": true
};
defineSymbol(text, main, textord, "\u2013", "--", true);
defineSymbol(text, main, textord, "\u2013", "\\textendash");
defineSymbol(text, main, textord, "\u2014", "---", true);
defineSymbol(text, main, textord, "\u2014", "\\textemdash");
defineSymbol(text, main, textord, "\u2018", "`", true);
defineSymbol(text, main, textord, "\u2018", "\\textquoteleft");
defineSymbol(text, main, textord, "\u2019", "'", true);
defineSymbol(text, main, textord, "\u2019", "\\textquoteright");
defineSymbol(text, main, textord, "\u201C", "``", true);
defineSymbol(text, main, textord, "\u201C", "\\textquotedblleft");
defineSymbol(text, main, textord, "\u201D", "''", true);
defineSymbol(text, main, textord, "\u201D", "\\textquotedblright");
defineSymbol(math, main, textord, "\xB0", "\\degree", true);
defineSymbol(text, main, textord, "\xB0", "\\degree");
defineSymbol(text, main, textord, "\xB0", "\\textdegree", true);
defineSymbol(math, main, textord, "\xA3", "\\pounds");
defineSymbol(math, main, textord, "\xA3", "\\mathsterling", true);
defineSymbol(text, main, textord, "\xA3", "\\pounds");
defineSymbol(text, main, textord, "\xA3", "\\textsterling", true);
defineSymbol(math, ams, textord, "\u2720", "\\maltese");
defineSymbol(text, ams, textord, "\u2720", "\\maltese");
var mathTextSymbols = '0123456789/@."';
for (i = 0; i < mathTextSymbols.length; i++) {
  ch = mathTextSymbols.charAt(i);
  defineSymbol(math, main, textord, ch, ch);
}
var ch;
var i;
var textSymbols = '0123456789!@*()-=+";:?/.,';
for (_i = 0; _i < textSymbols.length; _i++) {
  _ch = textSymbols.charAt(_i);
  defineSymbol(text, main, textord, _ch, _ch);
}
var _ch;
var _i;
var letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
for (_i2 = 0; _i2 < letters.length; _i2++) {
  _ch2 = letters.charAt(_i2);
  defineSymbol(math, main, mathord, _ch2, _ch2);
  defineSymbol(text, main, textord, _ch2, _ch2);
}
var _ch2;
var _i2;
defineSymbol(math, ams, textord, "C", "\u2102");
defineSymbol(text, ams, textord, "C", "\u2102");
defineSymbol(math, ams, textord, "H", "\u210D");
defineSymbol(text, ams, textord, "H", "\u210D");
defineSymbol(math, ams, textord, "N", "\u2115");
defineSymbol(text, ams, textord, "N", "\u2115");
defineSymbol(math, ams, textord, "P", "\u2119");
defineSymbol(text, ams, textord, "P", "\u2119");
defineSymbol(math, ams, textord, "Q", "\u211A");
defineSymbol(text, ams, textord, "Q", "\u211A");
defineSymbol(math, ams, textord, "R", "\u211D");
defineSymbol(text, ams, textord, "R", "\u211D");
defineSymbol(math, ams, textord, "Z", "\u2124");
defineSymbol(text, ams, textord, "Z", "\u2124");
defineSymbol(math, main, mathord, "h", "\u210E");
defineSymbol(text, main, mathord, "h", "\u210E");
var wideChar = "";
for (_i3 = 0; _i3 < letters.length; _i3++) {
  _ch3 = letters.charAt(_i3);
  wideChar = String.fromCharCode(55349, 56320 + _i3);
  defineSymbol(math, main, mathord, _ch3, wideChar);
  defineSymbol(text, main, textord, _ch3, wideChar);
  wideChar = String.fromCharCode(55349, 56372 + _i3);
  defineSymbol(math, main, mathord, _ch3, wideChar);
  defineSymbol(text, main, textord, _ch3, wideChar);
  wideChar = String.fromCharCode(55349, 56424 + _i3);
  defineSymbol(math, main, mathord, _ch3, wideChar);
  defineSymbol(text, main, textord, _ch3, wideChar);
  wideChar = String.fromCharCode(55349, 56580 + _i3);
  defineSymbol(math, main, mathord, _ch3, wideChar);
  defineSymbol(text, main, textord, _ch3, wideChar);
  wideChar = String.fromCharCode(55349, 56684 + _i3);
  defineSymbol(math, main, mathord, _ch3, wideChar);
  defineSymbol(text, main, textord, _ch3, wideChar);
  wideChar = String.fromCharCode(55349, 56736 + _i3);
  defineSymbol(math, main, mathord, _ch3, wideChar);
  defineSymbol(text, main, textord, _ch3, wideChar);
  wideChar = String.fromCharCode(55349, 56788 + _i3);
  defineSymbol(math, main, mathord, _ch3, wideChar);
  defineSymbol(text, main, textord, _ch3, wideChar);
  wideChar = String.fromCharCode(55349, 56840 + _i3);
  defineSymbol(math, main, mathord, _ch3, wideChar);
  defineSymbol(text, main, textord, _ch3, wideChar);
  wideChar = String.fromCharCode(55349, 56944 + _i3);
  defineSymbol(math, main, mathord, _ch3, wideChar);
  defineSymbol(text, main, textord, _ch3, wideChar);
  if (_i3 < 26) {
    wideChar = String.fromCharCode(55349, 56632 + _i3);
    defineSymbol(math, main, mathord, _ch3, wideChar);
    defineSymbol(text, main, textord, _ch3, wideChar);
    wideChar = String.fromCharCode(55349, 56476 + _i3);
    defineSymbol(math, main, mathord, _ch3, wideChar);
    defineSymbol(text, main, textord, _ch3, wideChar);
  }
}
var _ch3;
var _i3;
wideChar = String.fromCharCode(55349, 56668);
defineSymbol(math, main, mathord, "k", wideChar);
defineSymbol(text, main, textord, "k", wideChar);
for (_i4 = 0; _i4 < 10; _i4++) {
  _ch4 = _i4.toString();
  wideChar = String.fromCharCode(55349, 57294 + _i4);
  defineSymbol(math, main, mathord, _ch4, wideChar);
  defineSymbol(text, main, textord, _ch4, wideChar);
  wideChar = String.fromCharCode(55349, 57314 + _i4);
  defineSymbol(math, main, mathord, _ch4, wideChar);
  defineSymbol(text, main, textord, _ch4, wideChar);
  wideChar = String.fromCharCode(55349, 57324 + _i4);
  defineSymbol(math, main, mathord, _ch4, wideChar);
  defineSymbol(text, main, textord, _ch4, wideChar);
  wideChar = String.fromCharCode(55349, 57334 + _i4);
  defineSymbol(math, main, mathord, _ch4, wideChar);
  defineSymbol(text, main, textord, _ch4, wideChar);
}
var _ch4;
var _i4;
var extraLatin = "\xD0\xDE\xFE";
for (_i5 = 0; _i5 < extraLatin.length; _i5++) {
  _ch5 = extraLatin.charAt(_i5);
  defineSymbol(math, main, mathord, _ch5, _ch5);
  defineSymbol(text, main, textord, _ch5, _ch5);
}
var _ch5;
var _i5;
var wideLatinLetterData = [
  ["mathbf", "textbf", "Main-Bold"],
  // A-Z bold upright
  ["mathbf", "textbf", "Main-Bold"],
  // a-z bold upright
  ["mathnormal", "textit", "Math-Italic"],
  // A-Z italic
  ["mathnormal", "textit", "Math-Italic"],
  // a-z italic
  ["boldsymbol", "boldsymbol", "Main-BoldItalic"],
  // A-Z bold italic
  ["boldsymbol", "boldsymbol", "Main-BoldItalic"],
  // a-z bold italic
  // Map fancy A-Z letters to script, not calligraphic.
  // This aligns with unicode-math and math fonts (except Cambria Math).
  ["mathscr", "textscr", "Script-Regular"],
  // A-Z script
  ["", "", ""],
  // a-z script.  No font
  ["", "", ""],
  // A-Z bold script. No font
  ["", "", ""],
  // a-z bold script. No font
  ["mathfrak", "textfrak", "Fraktur-Regular"],
  // A-Z Fraktur
  ["mathfrak", "textfrak", "Fraktur-Regular"],
  // a-z Fraktur
  ["mathbb", "textbb", "AMS-Regular"],
  // A-Z double-struck
  ["mathbb", "textbb", "AMS-Regular"],
  // k double-struck
  // Note that we are using a bold font, but font metrics for regular Fraktur.
  ["mathboldfrak", "textboldfrak", "Fraktur-Regular"],
  // A-Z bold Fraktur
  ["mathboldfrak", "textboldfrak", "Fraktur-Regular"],
  // a-z bold Fraktur
  ["mathsf", "textsf", "SansSerif-Regular"],
  // A-Z sans-serif
  ["mathsf", "textsf", "SansSerif-Regular"],
  // a-z sans-serif
  ["mathboldsf", "textboldsf", "SansSerif-Bold"],
  // A-Z bold sans-serif
  ["mathboldsf", "textboldsf", "SansSerif-Bold"],
  // a-z bold sans-serif
  ["mathitsf", "textitsf", "SansSerif-Italic"],
  // A-Z italic sans-serif
  ["mathitsf", "textitsf", "SansSerif-Italic"],
  // a-z italic sans-serif
  ["", "", ""],
  // A-Z bold italic sans. No font
  ["", "", ""],
  // a-z bold italic sans. No font
  ["mathtt", "texttt", "Typewriter-Regular"],
  // A-Z monospace
  ["mathtt", "texttt", "Typewriter-Regular"]
  // a-z monospace
];
var wideNumeralData = [
  ["mathbf", "textbf", "Main-Bold"],
  // 0-9 bold
  ["", "", ""],
  // 0-9 double-struck. No KaTeX font.
  ["mathsf", "textsf", "SansSerif-Regular"],
  // 0-9 sans-serif
  ["mathboldsf", "textboldsf", "SansSerif-Bold"],
  // 0-9 bold sans-serif
  ["mathtt", "texttt", "Typewriter-Regular"]
  // 0-9 monospace
];
var wideCharacterFont = function wideCharacterFont2(wideChar2, mode) {
  var H = wideChar2.charCodeAt(0);
  var L = wideChar2.charCodeAt(1);
  var codePoint = (H - 55296) * 1024 + (L - 56320) + 65536;
  var j = mode === "math" ? 0 : 1;
  if (119808 <= codePoint && codePoint < 120484) {
    var i = Math.floor((codePoint - 119808) / 26);
    return [wideLatinLetterData[i][2], wideLatinLetterData[i][j]];
  } else if (120782 <= codePoint && codePoint <= 120831) {
    var _i = Math.floor((codePoint - 120782) / 10);
    return [wideNumeralData[_i][2], wideNumeralData[_i][j]];
  } else if (codePoint === 120485 || codePoint === 120486) {
    return [wideLatinLetterData[0][2], wideLatinLetterData[0][j]];
  } else if (120486 < codePoint && codePoint < 120782) {
    return ["", ""];
  } else {
    throw new ParseError("Unsupported character: " + wideChar2);
  }
};
var lookupSymbol = function lookupSymbol2(value, fontName, mode) {
  if (symbols[mode][value] && symbols[mode][value].replace) {
    value = symbols[mode][value].replace;
  }
  return {
    value,
    metrics: getCharacterMetrics(value, fontName, mode)
  };
};
var makeSymbol = function makeSymbol2(value, fontName, mode, options, classes) {
  var lookup = lookupSymbol(value, fontName, mode);
  var metrics = lookup.metrics;
  value = lookup.value;
  var symbolNode;
  if (metrics) {
    var italic = metrics.italic;
    if (mode === "text" || options && options.font === "mathit") {
      italic = 0;
    }
    symbolNode = new SymbolNode(value, metrics.height, metrics.depth, italic, metrics.skew, metrics.width, classes);
  } else {
    typeof console !== "undefined" && console.warn("No character metrics " + ("for '" + value + "' in style '" + fontName + "' and mode '" + mode + "'"));
    symbolNode = new SymbolNode(value, 0, 0, 0, 0, 0, classes);
  }
  if (options) {
    symbolNode.maxFontSize = options.sizeMultiplier;
    if (options.style.isTight()) {
      symbolNode.classes.push("mtight");
    }
    var color = options.getColor();
    if (color) {
      symbolNode.style.color = color;
    }
  }
  return symbolNode;
};
var mathsym = function mathsym2(value, mode, options, classes) {
  if (classes === void 0) {
    classes = [];
  }
  if (options.font === "boldsymbol" && lookupSymbol(value, "Main-Bold", mode).metrics) {
    return makeSymbol(value, "Main-Bold", mode, options, classes.concat(["mathbf"]));
  } else if (value === "\\" || symbols[mode][value].font === "main") {
    return makeSymbol(value, "Main-Regular", mode, options, classes);
  } else {
    return makeSymbol(value, "AMS-Regular", mode, options, classes.concat(["amsrm"]));
  }
};
var boldsymbol = function boldsymbol2(value, mode, options, classes, type) {
  if (type !== "textord" && lookupSymbol(value, "Math-BoldItalic", mode).metrics) {
    return {
      fontName: "Math-BoldItalic",
      fontClass: "boldsymbol"
    };
  } else {
    return {
      fontName: "Main-Bold",
      fontClass: "mathbf"
    };
  }
};
var makeOrd = function makeOrd2(group, options, type) {
  var mode = group.mode;
  var text5 = group.text;
  var classes = ["mord"];
  var isFont = mode === "math" || mode === "text" && options.font;
  var fontOrFamily = isFont ? options.font : options.fontFamily;
  var wideFontName = "";
  var wideFontClass = "";
  if (text5.charCodeAt(0) === 55349) {
    [wideFontName, wideFontClass] = wideCharacterFont(text5, mode);
  }
  if (wideFontName.length > 0) {
    return makeSymbol(text5, wideFontName, mode, options, classes.concat(wideFontClass));
  } else if (fontOrFamily) {
    var fontName;
    var fontClasses;
    if (fontOrFamily === "boldsymbol") {
      var fontData = boldsymbol(text5, mode, options, classes, type);
      fontName = fontData.fontName;
      fontClasses = [fontData.fontClass];
    } else if (isFont) {
      fontName = fontMap[fontOrFamily].fontName;
      fontClasses = [fontOrFamily];
    } else {
      fontName = retrieveTextFontName(fontOrFamily, options.fontWeight, options.fontShape);
      fontClasses = [fontOrFamily, options.fontWeight, options.fontShape];
    }
    if (lookupSymbol(text5, fontName, mode).metrics) {
      return makeSymbol(text5, fontName, mode, options, classes.concat(fontClasses));
    } else if (ligatures.hasOwnProperty(text5) && fontName.slice(0, 10) === "Typewriter") {
      var parts = [];
      for (var i = 0; i < text5.length; i++) {
        parts.push(makeSymbol(text5[i], fontName, mode, options, classes.concat(fontClasses)));
      }
      return makeFragment(parts);
    }
  }
  if (type === "mathord") {
    return makeSymbol(text5, "Math-Italic", mode, options, classes.concat(["mathnormal"]));
  } else if (type === "textord") {
    var font = symbols[mode][text5] && symbols[mode][text5].font;
    if (font === "ams") {
      var _fontName = retrieveTextFontName("amsrm", options.fontWeight, options.fontShape);
      return makeSymbol(text5, _fontName, mode, options, classes.concat("amsrm", options.fontWeight, options.fontShape));
    } else if (font === "main" || !font) {
      var _fontName2 = retrieveTextFontName("textrm", options.fontWeight, options.fontShape);
      return makeSymbol(text5, _fontName2, mode, options, classes.concat(options.fontWeight, options.fontShape));
    } else {
      var _fontName3 = retrieveTextFontName(font, options.fontWeight, options.fontShape);
      return makeSymbol(text5, _fontName3, mode, options, classes.concat(_fontName3, options.fontWeight, options.fontShape));
    }
  } else {
    throw new Error("unexpected type: " + type + " in makeOrd");
  }
};
var canCombine = (prev, next) => {
  if (createClass(prev.classes) !== createClass(next.classes) || prev.skew !== next.skew || prev.maxFontSize !== next.maxFontSize) {
    return false;
  }
  if (prev.classes.length === 1) {
    var cls = prev.classes[0];
    if (cls === "mbin" || cls === "mord") {
      return false;
    }
  }
  for (var style2 in prev.style) {
    if (prev.style.hasOwnProperty(style2) && prev.style[style2] !== next.style[style2]) {
      return false;
    }
  }
  for (var _style in next.style) {
    if (next.style.hasOwnProperty(_style) && prev.style[_style] !== next.style[_style]) {
      return false;
    }
  }
  return true;
};
var tryCombineChars = (chars) => {
  for (var i = 0; i < chars.length - 1; i++) {
    var prev = chars[i];
    var next = chars[i + 1];
    if (prev instanceof SymbolNode && next instanceof SymbolNode && canCombine(prev, next)) {
      prev.text += next.text;
      prev.height = Math.max(prev.height, next.height);
      prev.depth = Math.max(prev.depth, next.depth);
      prev.italic = next.italic;
      chars.splice(i + 1, 1);
      i--;
    }
  }
  return chars;
};
var sizeElementFromChildren = function sizeElementFromChildren2(elem) {
  var height = 0;
  var depth = 0;
  var maxFontSize = 0;
  for (var i = 0; i < elem.children.length; i++) {
    var child = elem.children[i];
    if (child.height > height) {
      height = child.height;
    }
    if (child.depth > depth) {
      depth = child.depth;
    }
    if (child.maxFontSize > maxFontSize) {
      maxFontSize = child.maxFontSize;
    }
  }
  elem.height = height;
  elem.depth = depth;
  elem.maxFontSize = maxFontSize;
};
var makeSpan$2 = function makeSpan(classes, children, options, style2) {
  var span = new Span(classes, children, options, style2);
  sizeElementFromChildren(span);
  return span;
};
var makeSvgSpan = (classes, children, options, style2) => new Span(classes, children, options, style2);
var makeLineSpan = function makeLineSpan2(className, options, thickness) {
  var line = makeSpan$2([className], [], options);
  line.height = Math.max(thickness || options.fontMetrics().defaultRuleThickness, options.minRuleThickness);
  line.style.borderBottomWidth = makeEm(line.height);
  line.maxFontSize = 1;
  return line;
};
var makeAnchor = function makeAnchor2(href, classes, children, options) {
  var anchor = new Anchor(href, classes, children, options);
  sizeElementFromChildren(anchor);
  return anchor;
};
var makeFragment = function makeFragment2(children) {
  var fragment = new DocumentFragment(children);
  sizeElementFromChildren(fragment);
  return fragment;
};
var wrapFragment = function wrapFragment2(group, options) {
  if (group instanceof DocumentFragment) {
    return makeSpan$2([], [group], options);
  }
  return group;
};
var getVListChildrenAndDepth = function getVListChildrenAndDepth2(params) {
  if (params.positionType === "individualShift") {
    var oldChildren = params.children;
    var children = [oldChildren[0]];
    var _depth = -oldChildren[0].shift - oldChildren[0].elem.depth;
    var currPos = _depth;
    for (var i = 1; i < oldChildren.length; i++) {
      var diff = -oldChildren[i].shift - currPos - oldChildren[i].elem.depth;
      var size = diff - (oldChildren[i - 1].elem.height + oldChildren[i - 1].elem.depth);
      currPos = currPos + diff;
      children.push({
        type: "kern",
        size
      });
      children.push(oldChildren[i]);
    }
    return {
      children,
      depth: _depth
    };
  }
  var depth;
  if (params.positionType === "top") {
    var bottom = params.positionData;
    for (var _i = 0; _i < params.children.length; _i++) {
      var child = params.children[_i];
      bottom -= child.type === "kern" ? child.size : child.elem.height + child.elem.depth;
    }
    depth = bottom;
  } else if (params.positionType === "bottom") {
    depth = -params.positionData;
  } else {
    var firstChild = params.children[0];
    if (firstChild.type !== "elem") {
      throw new Error('First child must have type "elem".');
    }
    if (params.positionType === "shift") {
      depth = -firstChild.elem.depth - params.positionData;
    } else if (params.positionType === "firstBaseline") {
      depth = -firstChild.elem.depth;
    } else {
      throw new Error("Invalid positionType " + params.positionType + ".");
    }
  }
  return {
    children: params.children,
    depth
  };
};
var makeVList = function makeVList2(params, options) {
  var {
    children,
    depth
  } = getVListChildrenAndDepth(params);
  var pstrutSize = 0;
  for (var i = 0; i < children.length; i++) {
    var child = children[i];
    if (child.type === "elem") {
      var elem = child.elem;
      pstrutSize = Math.max(pstrutSize, elem.maxFontSize, elem.height);
    }
  }
  pstrutSize += 2;
  var pstrut = makeSpan$2(["pstrut"], []);
  pstrut.style.height = makeEm(pstrutSize);
  var realChildren = [];
  var minPos = depth;
  var maxPos = depth;
  var currPos = depth;
  for (var _i2 = 0; _i2 < children.length; _i2++) {
    var _child = children[_i2];
    if (_child.type === "kern") {
      currPos += _child.size;
    } else {
      var _elem = _child.elem;
      var classes = _child.wrapperClasses || [];
      var style2 = _child.wrapperStyle || {};
      var childWrap = makeSpan$2(classes, [pstrut, _elem], void 0, style2);
      childWrap.style.top = makeEm(-pstrutSize - currPos - _elem.depth);
      if (_child.marginLeft) {
        childWrap.style.marginLeft = _child.marginLeft;
      }
      if (_child.marginRight) {
        childWrap.style.marginRight = _child.marginRight;
      }
      realChildren.push(childWrap);
      currPos += _elem.height + _elem.depth;
    }
    minPos = Math.min(minPos, currPos);
    maxPos = Math.max(maxPos, currPos);
  }
  var vlist = makeSpan$2(["vlist"], realChildren);
  vlist.style.height = makeEm(maxPos);
  var rows;
  if (minPos < 0) {
    var emptySpan = makeSpan$2([], []);
    var depthStrut = makeSpan$2(["vlist"], [emptySpan]);
    depthStrut.style.height = makeEm(-minPos);
    var topStrut = makeSpan$2(["vlist-s"], [new SymbolNode("\u200B")]);
    rows = [makeSpan$2(["vlist-r"], [vlist, topStrut]), makeSpan$2(["vlist-r"], [depthStrut])];
  } else {
    rows = [makeSpan$2(["vlist-r"], [vlist])];
  }
  var vtable = makeSpan$2(["vlist-t"], rows);
  if (rows.length === 2) {
    vtable.classes.push("vlist-t2");
  }
  vtable.height = maxPos;
  vtable.depth = -minPos;
  return vtable;
};
var makeGlue = (measurement, options) => {
  var rule = makeSpan$2(["mspace"], [], options);
  var size = calculateSize(measurement, options);
  rule.style.marginRight = makeEm(size);
  return rule;
};
var retrieveTextFontName = function retrieveTextFontName2(fontFamily, fontWeight, fontShape) {
  var baseFontName = "";
  switch (fontFamily) {
    case "amsrm":
      baseFontName = "AMS";
      break;
    case "textrm":
      baseFontName = "Main";
      break;
    case "textsf":
      baseFontName = "SansSerif";
      break;
    case "texttt":
      baseFontName = "Typewriter";
      break;
    default:
      baseFontName = fontFamily;
  }
  var fontStylesName;
  if (fontWeight === "textbf" && fontShape === "textit") {
    fontStylesName = "BoldItalic";
  } else if (fontWeight === "textbf") {
    fontStylesName = "Bold";
  } else if (fontWeight === "textit") {
    fontStylesName = "Italic";
  } else {
    fontStylesName = "Regular";
  }
  return baseFontName + "-" + fontStylesName;
};
var fontMap = {
  // styles
  "mathbf": {
    variant: "bold",
    fontName: "Main-Bold"
  },
  "mathrm": {
    variant: "normal",
    fontName: "Main-Regular"
  },
  "textit": {
    variant: "italic",
    fontName: "Main-Italic"
  },
  "mathit": {
    variant: "italic",
    fontName: "Main-Italic"
  },
  "mathnormal": {
    variant: "italic",
    fontName: "Math-Italic"
  },
  "mathsfit": {
    variant: "sans-serif-italic",
    fontName: "SansSerif-Italic"
  },
  // "boldsymbol" is missing because they require the use of multiple fonts:
  // Math-BoldItalic and Main-Bold.  This is handled by a special case in
  // makeOrd which ends up calling boldsymbol.
  // families
  "mathbb": {
    variant: "double-struck",
    fontName: "AMS-Regular"
  },
  "mathcal": {
    variant: "script",
    fontName: "Caligraphic-Regular"
  },
  "mathfrak": {
    variant: "fraktur",
    fontName: "Fraktur-Regular"
  },
  "mathscr": {
    variant: "script",
    fontName: "Script-Regular"
  },
  "mathsf": {
    variant: "sans-serif",
    fontName: "SansSerif-Regular"
  },
  "mathtt": {
    variant: "monospace",
    fontName: "Typewriter-Regular"
  }
};
var svgData = {
  //   path, width, height
  vec: ["vec", 0.471, 0.714],
  // values from the font glyph
  oiintSize1: ["oiintSize1", 0.957, 0.499],
  // oval to overlay the integrand
  oiintSize2: ["oiintSize2", 1.472, 0.659],
  oiiintSize1: ["oiiintSize1", 1.304, 0.499],
  oiiintSize2: ["oiiintSize2", 1.98, 0.659]
};
var staticSvg = function staticSvg2(value, options) {
  var [pathName, width, height] = svgData[value];
  var path2 = new PathNode(pathName);
  var svgNode = new SvgNode([path2], {
    "width": makeEm(width),
    "height": makeEm(height),
    // Override CSS rule `.katex svg { width: 100% }`
    "style": "width:" + makeEm(width),
    "viewBox": "0 0 " + 1e3 * width + " " + 1e3 * height,
    "preserveAspectRatio": "xMinYMin"
  });
  var span = makeSvgSpan(["overlay"], [svgNode], options);
  span.height = height;
  span.style.height = makeEm(height);
  span.style.width = makeEm(width);
  return span;
};
var buildCommon = {
  fontMap,
  makeSymbol,
  mathsym,
  makeSpan: makeSpan$2,
  makeSvgSpan,
  makeLineSpan,
  makeAnchor,
  makeFragment,
  wrapFragment,
  makeVList,
  makeOrd,
  makeGlue,
  staticSvg,
  svgData,
  tryCombineChars
};
var thinspace = {
  number: 3,
  unit: "mu"
};
var mediumspace = {
  number: 4,
  unit: "mu"
};
var thickspace = {
  number: 5,
  unit: "mu"
};
var spacings = {
  mord: {
    mop: thinspace,
    mbin: mediumspace,
    mrel: thickspace,
    minner: thinspace
  },
  mop: {
    mord: thinspace,
    mop: thinspace,
    mrel: thickspace,
    minner: thinspace
  },
  mbin: {
    mord: mediumspace,
    mop: mediumspace,
    mopen: mediumspace,
    minner: mediumspace
  },
  mrel: {
    mord: thickspace,
    mop: thickspace,
    mopen: thickspace,
    minner: thickspace
  },
  mopen: {},
  mclose: {
    mop: thinspace,
    mbin: mediumspace,
    mrel: thickspace,
    minner: thinspace
  },
  mpunct: {
    mord: thinspace,
    mop: thinspace,
    mrel: thickspace,
    mopen: thinspace,
    mclose: thinspace,
    mpunct: thinspace,
    minner: thinspace
  },
  minner: {
    mord: thinspace,
    mop: thinspace,
    mbin: mediumspace,
    mrel: thickspace,
    mopen: thinspace,
    mpunct: thinspace,
    minner: thinspace
  }
};
var tightSpacings = {
  mord: {
    mop: thinspace
  },
  mop: {
    mord: thinspace,
    mop: thinspace
  },
  mbin: {},
  mrel: {},
  mopen: {},
  mclose: {
    mop: thinspace
  },
  mpunct: {},
  minner: {
    mop: thinspace
  }
};
var _functions = {};
var _htmlGroupBuilders = {};
var _mathmlGroupBuilders = {};
function defineFunction(_ref) {
  var {
    type,
    names,
    props,
    handler,
    htmlBuilder: htmlBuilder3,
    mathmlBuilder: mathmlBuilder3
  } = _ref;
  var data = {
    type,
    numArgs: props.numArgs,
    argTypes: props.argTypes,
    allowedInArgument: !!props.allowedInArgument,
    allowedInText: !!props.allowedInText,
    allowedInMath: props.allowedInMath === void 0 ? true : props.allowedInMath,
    numOptionalArgs: props.numOptionalArgs || 0,
    infix: !!props.infix,
    primitive: !!props.primitive,
    handler
  };
  for (var i = 0; i < names.length; ++i) {
    _functions[names[i]] = data;
  }
  if (type) {
    if (htmlBuilder3) {
      _htmlGroupBuilders[type] = htmlBuilder3;
    }
    if (mathmlBuilder3) {
      _mathmlGroupBuilders[type] = mathmlBuilder3;
    }
  }
}
function defineFunctionBuilders(_ref2) {
  var {
    type,
    htmlBuilder: htmlBuilder3,
    mathmlBuilder: mathmlBuilder3
  } = _ref2;
  defineFunction({
    type,
    names: [],
    props: {
      numArgs: 0
    },
    handler() {
      throw new Error("Should never be called.");
    },
    htmlBuilder: htmlBuilder3,
    mathmlBuilder: mathmlBuilder3
  });
}
var normalizeArgument = function normalizeArgument2(arg) {
  return arg.type === "ordgroup" && arg.body.length === 1 ? arg.body[0] : arg;
};
var ordargument = function ordargument2(arg) {
  return arg.type === "ordgroup" ? arg.body : [arg];
};
var makeSpan$1 = buildCommon.makeSpan;
var binLeftCanceller = ["leftmost", "mbin", "mopen", "mrel", "mop", "mpunct"];
var binRightCanceller = ["rightmost", "mrel", "mclose", "mpunct"];
var styleMap$1 = {
  "display": Style$1.DISPLAY,
  "text": Style$1.TEXT,
  "script": Style$1.SCRIPT,
  "scriptscript": Style$1.SCRIPTSCRIPT
};
var DomEnum = {
  mord: "mord",
  mop: "mop",
  mbin: "mbin",
  mrel: "mrel",
  mopen: "mopen",
  mclose: "mclose",
  mpunct: "mpunct",
  minner: "minner"
};
var buildExpression$1 = function buildExpression(expression, options, isRealGroup, surrounding) {
  if (surrounding === void 0) {
    surrounding = [null, null];
  }
  var groups = [];
  for (var i = 0; i < expression.length; i++) {
    var output7 = buildGroup$1(expression[i], options);
    if (output7 instanceof DocumentFragment) {
      var children = output7.children;
      groups.push(...children);
    } else {
      groups.push(output7);
    }
  }
  buildCommon.tryCombineChars(groups);
  if (!isRealGroup) {
    return groups;
  }
  var glueOptions = options;
  if (expression.length === 1) {
    var node = expression[0];
    if (node.type === "sizing") {
      glueOptions = options.havingSize(node.size);
    } else if (node.type === "styling") {
      glueOptions = options.havingStyle(styleMap$1[node.style]);
    }
  }
  var dummyPrev = makeSpan$1([surrounding[0] || "leftmost"], [], options);
  var dummyNext = makeSpan$1([surrounding[1] || "rightmost"], [], options);
  var isRoot = isRealGroup === "root";
  traverseNonSpaceNodes(groups, (node2, prev) => {
    var prevType = prev.classes[0];
    var type = node2.classes[0];
    if (prevType === "mbin" && utils.contains(binRightCanceller, type)) {
      prev.classes[0] = "mord";
    } else if (type === "mbin" && utils.contains(binLeftCanceller, prevType)) {
      node2.classes[0] = "mord";
    }
  }, {
    node: dummyPrev
  }, dummyNext, isRoot);
  traverseNonSpaceNodes(groups, (node2, prev) => {
    var prevType = getTypeOfDomTree(prev);
    var type = getTypeOfDomTree(node2);
    var space3 = prevType && type ? node2.hasClass("mtight") ? tightSpacings[prevType][type] : spacings[prevType][type] : null;
    if (space3) {
      return buildCommon.makeGlue(space3, glueOptions);
    }
  }, {
    node: dummyPrev
  }, dummyNext, isRoot);
  return groups;
};
var traverseNonSpaceNodes = function traverseNonSpaceNodes2(nodes, callback, prev, next, isRoot) {
  if (next) {
    nodes.push(next);
  }
  var i = 0;
  for (; i < nodes.length; i++) {
    var node = nodes[i];
    var partialGroup = checkPartialGroup(node);
    if (partialGroup) {
      traverseNonSpaceNodes2(partialGroup.children, callback, prev, null, isRoot);
      continue;
    }
    var nonspace = !node.hasClass("mspace");
    if (nonspace) {
      var result = callback(node, prev.node);
      if (result) {
        if (prev.insertAfter) {
          prev.insertAfter(result);
        } else {
          nodes.unshift(result);
          i++;
        }
      }
    }
    if (nonspace) {
      prev.node = node;
    } else if (isRoot && node.hasClass("newline")) {
      prev.node = makeSpan$1(["leftmost"]);
    }
    prev.insertAfter = /* @__PURE__ */ ((index) => (n) => {
      nodes.splice(index + 1, 0, n);
      i++;
    })(i);
  }
  if (next) {
    nodes.pop();
  }
};
var checkPartialGroup = function checkPartialGroup2(node) {
  if (node instanceof DocumentFragment || node instanceof Anchor || node instanceof Span && node.hasClass("enclosing")) {
    return node;
  }
  return null;
};
var getOutermostNode = function getOutermostNode2(node, side) {
  var partialGroup = checkPartialGroup(node);
  if (partialGroup) {
    var children = partialGroup.children;
    if (children.length) {
      if (side === "right") {
        return getOutermostNode2(children[children.length - 1], "right");
      } else if (side === "left") {
        return getOutermostNode2(children[0], "left");
      }
    }
  }
  return node;
};
var getTypeOfDomTree = function getTypeOfDomTree2(node, side) {
  if (!node) {
    return null;
  }
  if (side) {
    node = getOutermostNode(node, side);
  }
  return DomEnum[node.classes[0]] || null;
};
var makeNullDelimiter = function makeNullDelimiter2(options, classes) {
  var moreClasses = ["nulldelimiter"].concat(options.baseSizingClasses());
  return makeSpan$1(classes.concat(moreClasses));
};
var buildGroup$1 = function buildGroup(group, options, baseOptions) {
  if (!group) {
    return makeSpan$1();
  }
  if (_htmlGroupBuilders[group.type]) {
    var groupNode = _htmlGroupBuilders[group.type](group, options);
    if (baseOptions && options.size !== baseOptions.size) {
      groupNode = makeSpan$1(options.sizingClasses(baseOptions), [groupNode], options);
      var multiplier = options.sizeMultiplier / baseOptions.sizeMultiplier;
      groupNode.height *= multiplier;
      groupNode.depth *= multiplier;
    }
    return groupNode;
  } else {
    throw new ParseError("Got group of unknown type: '" + group.type + "'");
  }
};
function buildHTMLUnbreakable(children, options) {
  var body = makeSpan$1(["base"], children, options);
  var strut = makeSpan$1(["strut"]);
  strut.style.height = makeEm(body.height + body.depth);
  if (body.depth) {
    strut.style.verticalAlign = makeEm(-body.depth);
  }
  body.children.unshift(strut);
  return body;
}
function buildHTML(tree, options) {
  var tag = null;
  if (tree.length === 1 && tree[0].type === "tag") {
    tag = tree[0].tag;
    tree = tree[0].body;
  }
  var expression = buildExpression$1(tree, options, "root");
  var eqnNum;
  if (expression.length === 2 && expression[1].hasClass("tag")) {
    eqnNum = expression.pop();
  }
  var children = [];
  var parts = [];
  for (var i = 0; i < expression.length; i++) {
    parts.push(expression[i]);
    if (expression[i].hasClass("mbin") || expression[i].hasClass("mrel") || expression[i].hasClass("allowbreak")) {
      var nobreak = false;
      while (i < expression.length - 1 && expression[i + 1].hasClass("mspace") && !expression[i + 1].hasClass("newline")) {
        i++;
        parts.push(expression[i]);
        if (expression[i].hasClass("nobreak")) {
          nobreak = true;
        }
      }
      if (!nobreak) {
        children.push(buildHTMLUnbreakable(parts, options));
        parts = [];
      }
    } else if (expression[i].hasClass("newline")) {
      parts.pop();
      if (parts.length > 0) {
        children.push(buildHTMLUnbreakable(parts, options));
        parts = [];
      }
      children.push(expression[i]);
    }
  }
  if (parts.length > 0) {
    children.push(buildHTMLUnbreakable(parts, options));
  }
  var tagChild;
  if (tag) {
    tagChild = buildHTMLUnbreakable(buildExpression$1(tag, options, true));
    tagChild.classes = ["tag"];
    children.push(tagChild);
  } else if (eqnNum) {
    children.push(eqnNum);
  }
  var htmlNode = makeSpan$1(["katex-html"], children);
  htmlNode.setAttribute("aria-hidden", "true");
  if (tagChild) {
    var strut = tagChild.children[0];
    strut.style.height = makeEm(htmlNode.height + htmlNode.depth);
    if (htmlNode.depth) {
      strut.style.verticalAlign = makeEm(-htmlNode.depth);
    }
  }
  return htmlNode;
}
function newDocumentFragment(children) {
  return new DocumentFragment(children);
}
var MathNode = class {
  constructor(type, children, classes) {
    this.type = void 0;
    this.attributes = void 0;
    this.children = void 0;
    this.classes = void 0;
    this.type = type;
    this.attributes = {};
    this.children = children || [];
    this.classes = classes || [];
  }
  /**
   * Sets an attribute on a MathML node. MathML depends on attributes to convey a
   * semantic content, so this is used heavily.
   */
  setAttribute(name, value) {
    this.attributes[name] = value;
  }
  /**
   * Gets an attribute on a MathML node.
   */
  getAttribute(name) {
    return this.attributes[name];
  }
  /**
   * Converts the math node into a MathML-namespaced DOM element.
   */
  toNode() {
    var node = document.createElementNS("http://www.w3.org/1998/Math/MathML", this.type);
    for (var attr in this.attributes) {
      if (Object.prototype.hasOwnProperty.call(this.attributes, attr)) {
        node.setAttribute(attr, this.attributes[attr]);
      }
    }
    if (this.classes.length > 0) {
      node.className = createClass(this.classes);
    }
    for (var i = 0; i < this.children.length; i++) {
      if (this.children[i] instanceof TextNode2 && this.children[i + 1] instanceof TextNode2) {
        var text5 = this.children[i].toText() + this.children[++i].toText();
        while (this.children[i + 1] instanceof TextNode2) {
          text5 += this.children[++i].toText();
        }
        node.appendChild(new TextNode2(text5).toNode());
      } else {
        node.appendChild(this.children[i].toNode());
      }
    }
    return node;
  }
  /**
   * Converts the math node into an HTML markup string.
   */
  toMarkup() {
    var markup = "<" + this.type;
    for (var attr in this.attributes) {
      if (Object.prototype.hasOwnProperty.call(this.attributes, attr)) {
        markup += " " + attr + '="';
        markup += utils.escape(this.attributes[attr]);
        markup += '"';
      }
    }
    if (this.classes.length > 0) {
      markup += ' class ="' + utils.escape(createClass(this.classes)) + '"';
    }
    markup += ">";
    for (var i = 0; i < this.children.length; i++) {
      markup += this.children[i].toMarkup();
    }
    markup += "</" + this.type + ">";
    return markup;
  }
  /**
   * Converts the math node into a string, similar to innerText, but escaped.
   */
  toText() {
    return this.children.map((child) => child.toText()).join("");
  }
};
var TextNode2 = class {
  constructor(text5) {
    this.text = void 0;
    this.text = text5;
  }
  /**
   * Converts the text node into a DOM text node.
   */
  toNode() {
    return document.createTextNode(this.text);
  }
  /**
   * Converts the text node into escaped HTML markup
   * (representing the text itself).
   */
  toMarkup() {
    return utils.escape(this.toText());
  }
  /**
   * Converts the text node into a string
   * (representing the text itself).
   */
  toText() {
    return this.text;
  }
};
var SpaceNode = class {
  /**
   * Create a Space node with width given in CSS ems.
   */
  constructor(width) {
    this.width = void 0;
    this.character = void 0;
    this.width = width;
    if (width >= 0.05555 && width <= 0.05556) {
      this.character = "\u200A";
    } else if (width >= 0.1666 && width <= 0.1667) {
      this.character = "\u2009";
    } else if (width >= 0.2222 && width <= 0.2223) {
      this.character = "\u2005";
    } else if (width >= 0.2777 && width <= 0.2778) {
      this.character = "\u2005\u200A";
    } else if (width >= -0.05556 && width <= -0.05555) {
      this.character = "\u200A\u2063";
    } else if (width >= -0.1667 && width <= -0.1666) {
      this.character = "\u2009\u2063";
    } else if (width >= -0.2223 && width <= -0.2222) {
      this.character = "\u205F\u2063";
    } else if (width >= -0.2778 && width <= -0.2777) {
      this.character = "\u2005\u2063";
    } else {
      this.character = null;
    }
  }
  /**
   * Converts the math node into a MathML-namespaced DOM element.
   */
  toNode() {
    if (this.character) {
      return document.createTextNode(this.character);
    } else {
      var node = document.createElementNS("http://www.w3.org/1998/Math/MathML", "mspace");
      node.setAttribute("width", makeEm(this.width));
      return node;
    }
  }
  /**
   * Converts the math node into an HTML markup string.
   */
  toMarkup() {
    if (this.character) {
      return "<mtext>" + this.character + "</mtext>";
    } else {
      return '<mspace width="' + makeEm(this.width) + '"/>';
    }
  }
  /**
   * Converts the math node into a string, similar to innerText.
   */
  toText() {
    if (this.character) {
      return this.character;
    } else {
      return " ";
    }
  }
};
var mathMLTree = {
  MathNode,
  TextNode: TextNode2,
  SpaceNode,
  newDocumentFragment
};
var makeText = function makeText2(text5, mode, options) {
  if (symbols[mode][text5] && symbols[mode][text5].replace && text5.charCodeAt(0) !== 55349 && !(ligatures.hasOwnProperty(text5) && options && (options.fontFamily && options.fontFamily.slice(4, 6) === "tt" || options.font && options.font.slice(4, 6) === "tt"))) {
    text5 = symbols[mode][text5].replace;
  }
  return new mathMLTree.TextNode(text5);
};
var makeRow = function makeRow2(body) {
  if (body.length === 1) {
    return body[0];
  } else {
    return new mathMLTree.MathNode("mrow", body);
  }
};
var getVariant = function getVariant2(group, options) {
  if (options.fontFamily === "texttt") {
    return "monospace";
  } else if (options.fontFamily === "textsf") {
    if (options.fontShape === "textit" && options.fontWeight === "textbf") {
      return "sans-serif-bold-italic";
    } else if (options.fontShape === "textit") {
      return "sans-serif-italic";
    } else if (options.fontWeight === "textbf") {
      return "bold-sans-serif";
    } else {
      return "sans-serif";
    }
  } else if (options.fontShape === "textit" && options.fontWeight === "textbf") {
    return "bold-italic";
  } else if (options.fontShape === "textit") {
    return "italic";
  } else if (options.fontWeight === "textbf") {
    return "bold";
  }
  var font = options.font;
  if (!font || font === "mathnormal") {
    return null;
  }
  var mode = group.mode;
  if (font === "mathit") {
    return "italic";
  } else if (font === "boldsymbol") {
    return group.type === "textord" ? "bold" : "bold-italic";
  } else if (font === "mathbf") {
    return "bold";
  } else if (font === "mathbb") {
    return "double-struck";
  } else if (font === "mathsfit") {
    return "sans-serif-italic";
  } else if (font === "mathfrak") {
    return "fraktur";
  } else if (font === "mathscr" || font === "mathcal") {
    return "script";
  } else if (font === "mathsf") {
    return "sans-serif";
  } else if (font === "mathtt") {
    return "monospace";
  }
  var text5 = group.text;
  if (utils.contains(["\\imath", "\\jmath"], text5)) {
    return null;
  }
  if (symbols[mode][text5] && symbols[mode][text5].replace) {
    text5 = symbols[mode][text5].replace;
  }
  var fontName = buildCommon.fontMap[font].fontName;
  if (getCharacterMetrics(text5, fontName, mode)) {
    return buildCommon.fontMap[font].variant;
  }
  return null;
};
function isNumberPunctuation(group) {
  if (!group) {
    return false;
  }
  if (group.type === "mi" && group.children.length === 1) {
    var child = group.children[0];
    return child instanceof TextNode2 && child.text === ".";
  } else if (group.type === "mo" && group.children.length === 1 && group.getAttribute("separator") === "true" && group.getAttribute("lspace") === "0em" && group.getAttribute("rspace") === "0em") {
    var _child = group.children[0];
    return _child instanceof TextNode2 && _child.text === ",";
  } else {
    return false;
  }
}
var buildExpression2 = function buildExpression3(expression, options, isOrdgroup) {
  if (expression.length === 1) {
    var group = buildGroup2(expression[0], options);
    if (isOrdgroup && group instanceof MathNode && group.type === "mo") {
      group.setAttribute("lspace", "0em");
      group.setAttribute("rspace", "0em");
    }
    return [group];
  }
  var groups = [];
  var lastGroup;
  for (var i = 0; i < expression.length; i++) {
    var _group = buildGroup2(expression[i], options);
    if (_group instanceof MathNode && lastGroup instanceof MathNode) {
      if (_group.type === "mtext" && lastGroup.type === "mtext" && _group.getAttribute("mathvariant") === lastGroup.getAttribute("mathvariant")) {
        lastGroup.children.push(..._group.children);
        continue;
      } else if (_group.type === "mn" && lastGroup.type === "mn") {
        lastGroup.children.push(..._group.children);
        continue;
      } else if (isNumberPunctuation(_group) && lastGroup.type === "mn") {
        lastGroup.children.push(..._group.children);
        continue;
      } else if (_group.type === "mn" && isNumberPunctuation(lastGroup)) {
        _group.children = [...lastGroup.children, ..._group.children];
        groups.pop();
      } else if ((_group.type === "msup" || _group.type === "msub") && _group.children.length >= 1 && (lastGroup.type === "mn" || isNumberPunctuation(lastGroup))) {
        var base2 = _group.children[0];
        if (base2 instanceof MathNode && base2.type === "mn") {
          base2.children = [...lastGroup.children, ...base2.children];
          groups.pop();
        }
      } else if (lastGroup.type === "mi" && lastGroup.children.length === 1) {
        var lastChild = lastGroup.children[0];
        if (lastChild instanceof TextNode2 && lastChild.text === "\u0338" && (_group.type === "mo" || _group.type === "mi" || _group.type === "mn")) {
          var child = _group.children[0];
          if (child instanceof TextNode2 && child.text.length > 0) {
            child.text = child.text.slice(0, 1) + "\u0338" + child.text.slice(1);
            groups.pop();
          }
        }
      }
    }
    groups.push(_group);
    lastGroup = _group;
  }
  return groups;
};
var buildExpressionRow = function buildExpressionRow2(expression, options, isOrdgroup) {
  return makeRow(buildExpression2(expression, options, isOrdgroup));
};
var buildGroup2 = function buildGroup3(group, options) {
  if (!group) {
    return new mathMLTree.MathNode("mrow");
  }
  if (_mathmlGroupBuilders[group.type]) {
    var result = _mathmlGroupBuilders[group.type](group, options);
    return result;
  } else {
    throw new ParseError("Got group of unknown type: '" + group.type + "'");
  }
};
function buildMathML(tree, texExpression, options, isDisplayMode, forMathmlOnly) {
  var expression = buildExpression2(tree, options);
  var wrapper;
  if (expression.length === 1 && expression[0] instanceof MathNode && utils.contains(["mrow", "mtable"], expression[0].type)) {
    wrapper = expression[0];
  } else {
    wrapper = new mathMLTree.MathNode("mrow", expression);
  }
  var annotation = new mathMLTree.MathNode("annotation", [new mathMLTree.TextNode(texExpression)]);
  annotation.setAttribute("encoding", "application/x-tex");
  var semantics = new mathMLTree.MathNode("semantics", [wrapper, annotation]);
  var math2 = new mathMLTree.MathNode("math", [semantics]);
  math2.setAttribute("xmlns", "http://www.w3.org/1998/Math/MathML");
  if (isDisplayMode) {
    math2.setAttribute("display", "block");
  }
  var wrapperClass = forMathmlOnly ? "katex" : "katex-mathml";
  return buildCommon.makeSpan([wrapperClass], [math2]);
}
var optionsFromSettings = function optionsFromSettings2(settings) {
  return new Options2({
    style: settings.displayMode ? Style$1.DISPLAY : Style$1.TEXT,
    maxSize: settings.maxSize,
    minRuleThickness: settings.minRuleThickness
  });
};
var displayWrap = function displayWrap2(node, settings) {
  if (settings.displayMode) {
    var classes = ["katex-display"];
    if (settings.leqno) {
      classes.push("leqno");
    }
    if (settings.fleqn) {
      classes.push("fleqn");
    }
    node = buildCommon.makeSpan(classes, [node]);
  }
  return node;
};
var buildTree2 = function buildTree3(tree, expression, settings) {
  var options = optionsFromSettings(settings);
  var katexNode;
  if (settings.output === "mathml") {
    return buildMathML(tree, expression, options, settings.displayMode, true);
  } else if (settings.output === "html") {
    var htmlNode = buildHTML(tree, options);
    katexNode = buildCommon.makeSpan(["katex"], [htmlNode]);
  } else {
    var mathMLNode = buildMathML(tree, expression, options, settings.displayMode, false);
    var _htmlNode = buildHTML(tree, options);
    katexNode = buildCommon.makeSpan(["katex"], [mathMLNode, _htmlNode]);
  }
  return displayWrap(katexNode, settings);
};
var buildHTMLTree = function buildHTMLTree2(tree, expression, settings) {
  var options = optionsFromSettings(settings);
  var htmlNode = buildHTML(tree, options);
  var katexNode = buildCommon.makeSpan(["katex"], [htmlNode]);
  return displayWrap(katexNode, settings);
};
var stretchyCodePoint = {
  widehat: "^",
  widecheck: "\u02C7",
  widetilde: "~",
  utilde: "~",
  overleftarrow: "\u2190",
  underleftarrow: "\u2190",
  xleftarrow: "\u2190",
  overrightarrow: "\u2192",
  underrightarrow: "\u2192",
  xrightarrow: "\u2192",
  underbrace: "\u23DF",
  overbrace: "\u23DE",
  overgroup: "\u23E0",
  undergroup: "\u23E1",
  overleftrightarrow: "\u2194",
  underleftrightarrow: "\u2194",
  xleftrightarrow: "\u2194",
  Overrightarrow: "\u21D2",
  xRightarrow: "\u21D2",
  overleftharpoon: "\u21BC",
  xleftharpoonup: "\u21BC",
  overrightharpoon: "\u21C0",
  xrightharpoonup: "\u21C0",
  xLeftarrow: "\u21D0",
  xLeftrightarrow: "\u21D4",
  xhookleftarrow: "\u21A9",
  xhookrightarrow: "\u21AA",
  xmapsto: "\u21A6",
  xrightharpoondown: "\u21C1",
  xleftharpoondown: "\u21BD",
  xrightleftharpoons: "\u21CC",
  xleftrightharpoons: "\u21CB",
  xtwoheadleftarrow: "\u219E",
  xtwoheadrightarrow: "\u21A0",
  xlongequal: "=",
  xtofrom: "\u21C4",
  xrightleftarrows: "\u21C4",
  xrightequilibrium: "\u21CC",
  // Not a perfect match.
  xleftequilibrium: "\u21CB",
  // None better available.
  "\\cdrightarrow": "\u2192",
  "\\cdleftarrow": "\u2190",
  "\\cdlongequal": "="
};
var mathMLnode = function mathMLnode2(label) {
  var node = new mathMLTree.MathNode("mo", [new mathMLTree.TextNode(stretchyCodePoint[label.replace(/^\\/, "")])]);
  node.setAttribute("stretchy", "true");
  return node;
};
var katexImagesData = {
  //   path(s), minWidth, height, align
  overrightarrow: [["rightarrow"], 0.888, 522, "xMaxYMin"],
  overleftarrow: [["leftarrow"], 0.888, 522, "xMinYMin"],
  underrightarrow: [["rightarrow"], 0.888, 522, "xMaxYMin"],
  underleftarrow: [["leftarrow"], 0.888, 522, "xMinYMin"],
  xrightarrow: [["rightarrow"], 1.469, 522, "xMaxYMin"],
  "\\cdrightarrow": [["rightarrow"], 3, 522, "xMaxYMin"],
  // CD minwwidth2.5pc
  xleftarrow: [["leftarrow"], 1.469, 522, "xMinYMin"],
  "\\cdleftarrow": [["leftarrow"], 3, 522, "xMinYMin"],
  Overrightarrow: [["doublerightarrow"], 0.888, 560, "xMaxYMin"],
  xRightarrow: [["doublerightarrow"], 1.526, 560, "xMaxYMin"],
  xLeftarrow: [["doubleleftarrow"], 1.526, 560, "xMinYMin"],
  overleftharpoon: [["leftharpoon"], 0.888, 522, "xMinYMin"],
  xleftharpoonup: [["leftharpoon"], 0.888, 522, "xMinYMin"],
  xleftharpoondown: [["leftharpoondown"], 0.888, 522, "xMinYMin"],
  overrightharpoon: [["rightharpoon"], 0.888, 522, "xMaxYMin"],
  xrightharpoonup: [["rightharpoon"], 0.888, 522, "xMaxYMin"],
  xrightharpoondown: [["rightharpoondown"], 0.888, 522, "xMaxYMin"],
  xlongequal: [["longequal"], 0.888, 334, "xMinYMin"],
  "\\cdlongequal": [["longequal"], 3, 334, "xMinYMin"],
  xtwoheadleftarrow: [["twoheadleftarrow"], 0.888, 334, "xMinYMin"],
  xtwoheadrightarrow: [["twoheadrightarrow"], 0.888, 334, "xMaxYMin"],
  overleftrightarrow: [["leftarrow", "rightarrow"], 0.888, 522],
  overbrace: [["leftbrace", "midbrace", "rightbrace"], 1.6, 548],
  underbrace: [["leftbraceunder", "midbraceunder", "rightbraceunder"], 1.6, 548],
  underleftrightarrow: [["leftarrow", "rightarrow"], 0.888, 522],
  xleftrightarrow: [["leftarrow", "rightarrow"], 1.75, 522],
  xLeftrightarrow: [["doubleleftarrow", "doublerightarrow"], 1.75, 560],
  xrightleftharpoons: [["leftharpoondownplus", "rightharpoonplus"], 1.75, 716],
  xleftrightharpoons: [["leftharpoonplus", "rightharpoondownplus"], 1.75, 716],
  xhookleftarrow: [["leftarrow", "righthook"], 1.08, 522],
  xhookrightarrow: [["lefthook", "rightarrow"], 1.08, 522],
  overlinesegment: [["leftlinesegment", "rightlinesegment"], 0.888, 522],
  underlinesegment: [["leftlinesegment", "rightlinesegment"], 0.888, 522],
  overgroup: [["leftgroup", "rightgroup"], 0.888, 342],
  undergroup: [["leftgroupunder", "rightgroupunder"], 0.888, 342],
  xmapsto: [["leftmapsto", "rightarrow"], 1.5, 522],
  xtofrom: [["leftToFrom", "rightToFrom"], 1.75, 528],
  // The next three arrows are from the mhchem package.
  // In mhchem.sty, min-length is 2.0em. But these arrows might appear in the
  // document as \xrightarrow or \xrightleftharpoons. Those have
  // min-length = 1.75em, so we set min-length on these next three to match.
  xrightleftarrows: [["baraboveleftarrow", "rightarrowabovebar"], 1.75, 901],
  xrightequilibrium: [["baraboveshortleftharpoon", "rightharpoonaboveshortbar"], 1.75, 716],
  xleftequilibrium: [["shortbaraboveleftharpoon", "shortrightharpoonabovebar"], 1.75, 716]
};
var groupLength = function groupLength2(arg) {
  if (arg.type === "ordgroup") {
    return arg.body.length;
  } else {
    return 1;
  }
};
var svgSpan = function svgSpan2(group, options) {
  function buildSvgSpan_() {
    var viewBoxWidth = 4e5;
    var label = group.label.slice(1);
    if (utils.contains(["widehat", "widecheck", "widetilde", "utilde"], label)) {
      var grp = group;
      var numChars = groupLength(grp.base);
      var viewBoxHeight;
      var pathName;
      var _height;
      if (numChars > 5) {
        if (label === "widehat" || label === "widecheck") {
          viewBoxHeight = 420;
          viewBoxWidth = 2364;
          _height = 0.42;
          pathName = label + "4";
        } else {
          viewBoxHeight = 312;
          viewBoxWidth = 2340;
          _height = 0.34;
          pathName = "tilde4";
        }
      } else {
        var imgIndex = [1, 1, 2, 2, 3, 3][numChars];
        if (label === "widehat" || label === "widecheck") {
          viewBoxWidth = [0, 1062, 2364, 2364, 2364][imgIndex];
          viewBoxHeight = [0, 239, 300, 360, 420][imgIndex];
          _height = [0, 0.24, 0.3, 0.3, 0.36, 0.42][imgIndex];
          pathName = label + imgIndex;
        } else {
          viewBoxWidth = [0, 600, 1033, 2339, 2340][imgIndex];
          viewBoxHeight = [0, 260, 286, 306, 312][imgIndex];
          _height = [0, 0.26, 0.286, 0.3, 0.306, 0.34][imgIndex];
          pathName = "tilde" + imgIndex;
        }
      }
      var path2 = new PathNode(pathName);
      var svgNode = new SvgNode([path2], {
        "width": "100%",
        "height": makeEm(_height),
        "viewBox": "0 0 " + viewBoxWidth + " " + viewBoxHeight,
        "preserveAspectRatio": "none"
      });
      return {
        span: buildCommon.makeSvgSpan([], [svgNode], options),
        minWidth: 0,
        height: _height
      };
    } else {
      var spans = [];
      var data = katexImagesData[label];
      var [paths, _minWidth, _viewBoxHeight] = data;
      var _height2 = _viewBoxHeight / 1e3;
      var numSvgChildren = paths.length;
      var widthClasses;
      var aligns;
      if (numSvgChildren === 1) {
        var align1 = data[3];
        widthClasses = ["hide-tail"];
        aligns = [align1];
      } else if (numSvgChildren === 2) {
        widthClasses = ["halfarrow-left", "halfarrow-right"];
        aligns = ["xMinYMin", "xMaxYMin"];
      } else if (numSvgChildren === 3) {
        widthClasses = ["brace-left", "brace-center", "brace-right"];
        aligns = ["xMinYMin", "xMidYMin", "xMaxYMin"];
      } else {
        throw new Error("Correct katexImagesData or update code here to support\n                    " + numSvgChildren + " children.");
      }
      for (var i = 0; i < numSvgChildren; i++) {
        var _path = new PathNode(paths[i]);
        var _svgNode = new SvgNode([_path], {
          "width": "400em",
          "height": makeEm(_height2),
          "viewBox": "0 0 " + viewBoxWidth + " " + _viewBoxHeight,
          "preserveAspectRatio": aligns[i] + " slice"
        });
        var _span = buildCommon.makeSvgSpan([widthClasses[i]], [_svgNode], options);
        if (numSvgChildren === 1) {
          return {
            span: _span,
            minWidth: _minWidth,
            height: _height2
          };
        } else {
          _span.style.height = makeEm(_height2);
          spans.push(_span);
        }
      }
      return {
        span: buildCommon.makeSpan(["stretchy"], spans, options),
        minWidth: _minWidth,
        height: _height2
      };
    }
  }
  var {
    span,
    minWidth,
    height
  } = buildSvgSpan_();
  span.height = height;
  span.style.height = makeEm(height);
  if (minWidth > 0) {
    span.style.minWidth = makeEm(minWidth);
  }
  return span;
};
var encloseSpan = function encloseSpan2(inner2, label, topPad, bottomPad, options) {
  var img;
  var totalHeight = inner2.height + inner2.depth + topPad + bottomPad;
  if (/fbox|color|angl/.test(label)) {
    img = buildCommon.makeSpan(["stretchy", label], [], options);
    if (label === "fbox") {
      var color = options.color && options.getColor();
      if (color) {
        img.style.borderColor = color;
      }
    }
  } else {
    var lines = [];
    if (/^[bx]cancel$/.test(label)) {
      lines.push(new LineNode({
        "x1": "0",
        "y1": "0",
        "x2": "100%",
        "y2": "100%",
        "stroke-width": "0.046em"
      }));
    }
    if (/^x?cancel$/.test(label)) {
      lines.push(new LineNode({
        "x1": "0",
        "y1": "100%",
        "x2": "100%",
        "y2": "0",
        "stroke-width": "0.046em"
      }));
    }
    var svgNode = new SvgNode(lines, {
      "width": "100%",
      "height": makeEm(totalHeight)
    });
    img = buildCommon.makeSvgSpan([], [svgNode], options);
  }
  img.height = totalHeight;
  img.style.height = makeEm(totalHeight);
  return img;
};
var stretchy = {
  encloseSpan,
  mathMLnode,
  svgSpan
};
function assertNodeType(node, type) {
  if (!node || node.type !== type) {
    throw new Error("Expected node of type " + type + ", but got " + (node ? "node of type " + node.type : String(node)));
  }
  return node;
}
function assertSymbolNodeType(node) {
  var typedNode = checkSymbolNodeType(node);
  if (!typedNode) {
    throw new Error("Expected node of symbol group type, but got " + (node ? "node of type " + node.type : String(node)));
  }
  return typedNode;
}
function checkSymbolNodeType(node) {
  if (node && (node.type === "atom" || NON_ATOMS.hasOwnProperty(node.type))) {
    return node;
  }
  return null;
}
var htmlBuilder$a = (grp, options) => {
  var base2;
  var group;
  var supSubGroup;
  if (grp && grp.type === "supsub") {
    group = assertNodeType(grp.base, "accent");
    base2 = group.base;
    grp.base = base2;
    supSubGroup = assertSpan(buildGroup$1(grp, options));
    grp.base = group;
  } else {
    group = assertNodeType(grp, "accent");
    base2 = group.base;
  }
  var body = buildGroup$1(base2, options.havingCrampedStyle());
  var mustShift = group.isShifty && utils.isCharacterBox(base2);
  var skew = 0;
  if (mustShift) {
    var baseChar = utils.getBaseElem(base2);
    var baseGroup = buildGroup$1(baseChar, options.havingCrampedStyle());
    skew = assertSymbolDomNode(baseGroup).skew;
  }
  var accentBelow = group.label === "\\c";
  var clearance = accentBelow ? body.height + body.depth : Math.min(body.height, options.fontMetrics().xHeight);
  var accentBody;
  if (!group.isStretchy) {
    var accent2;
    var width;
    if (group.label === "\\vec") {
      accent2 = buildCommon.staticSvg("vec", options);
      width = buildCommon.svgData.vec[1];
    } else {
      accent2 = buildCommon.makeOrd({
        mode: group.mode,
        text: group.label
      }, options, "textord");
      accent2 = assertSymbolDomNode(accent2);
      accent2.italic = 0;
      width = accent2.width;
      if (accentBelow) {
        clearance += accent2.depth;
      }
    }
    accentBody = buildCommon.makeSpan(["accent-body"], [accent2]);
    var accentFull = group.label === "\\textcircled";
    if (accentFull) {
      accentBody.classes.push("accent-full");
      clearance = body.height;
    }
    var left = skew;
    if (!accentFull) {
      left -= width / 2;
    }
    accentBody.style.left = makeEm(left);
    if (group.label === "\\textcircled") {
      accentBody.style.top = ".2em";
    }
    accentBody = buildCommon.makeVList({
      positionType: "firstBaseline",
      children: [{
        type: "elem",
        elem: body
      }, {
        type: "kern",
        size: -clearance
      }, {
        type: "elem",
        elem: accentBody
      }]
    }, options);
  } else {
    accentBody = stretchy.svgSpan(group, options);
    accentBody = buildCommon.makeVList({
      positionType: "firstBaseline",
      children: [{
        type: "elem",
        elem: body
      }, {
        type: "elem",
        elem: accentBody,
        wrapperClasses: ["svg-align"],
        wrapperStyle: skew > 0 ? {
          width: "calc(100% - " + makeEm(2 * skew) + ")",
          marginLeft: makeEm(2 * skew)
        } : void 0
      }]
    }, options);
  }
  var accentWrap = buildCommon.makeSpan(["mord", "accent"], [accentBody], options);
  if (supSubGroup) {
    supSubGroup.children[0] = accentWrap;
    supSubGroup.height = Math.max(accentWrap.height, supSubGroup.height);
    supSubGroup.classes[0] = "mord";
    return supSubGroup;
  } else {
    return accentWrap;
  }
};
var mathmlBuilder$9 = (group, options) => {
  var accentNode = group.isStretchy ? stretchy.mathMLnode(group.label) : new mathMLTree.MathNode("mo", [makeText(group.label, group.mode)]);
  var node = new mathMLTree.MathNode("mover", [buildGroup2(group.base, options), accentNode]);
  node.setAttribute("accent", "true");
  return node;
};
var NON_STRETCHY_ACCENT_REGEX = new RegExp(["\\acute", "\\grave", "\\ddot", "\\tilde", "\\bar", "\\breve", "\\check", "\\hat", "\\vec", "\\dot", "\\mathring"].map((accent2) => "\\" + accent2).join("|"));
defineFunction({
  type: "accent",
  names: ["\\acute", "\\grave", "\\ddot", "\\tilde", "\\bar", "\\breve", "\\check", "\\hat", "\\vec", "\\dot", "\\mathring", "\\widecheck", "\\widehat", "\\widetilde", "\\overrightarrow", "\\overleftarrow", "\\Overrightarrow", "\\overleftrightarrow", "\\overgroup", "\\overlinesegment", "\\overleftharpoon", "\\overrightharpoon"],
  props: {
    numArgs: 1
  },
  handler: (context, args) => {
    var base2 = normalizeArgument(args[0]);
    var isStretchy = !NON_STRETCHY_ACCENT_REGEX.test(context.funcName);
    var isShifty = !isStretchy || context.funcName === "\\widehat" || context.funcName === "\\widetilde" || context.funcName === "\\widecheck";
    return {
      type: "accent",
      mode: context.parser.mode,
      label: context.funcName,
      isStretchy,
      isShifty,
      base: base2
    };
  },
  htmlBuilder: htmlBuilder$a,
  mathmlBuilder: mathmlBuilder$9
});
defineFunction({
  type: "accent",
  names: ["\\'", "\\`", "\\^", "\\~", "\\=", "\\u", "\\.", '\\"', "\\c", "\\r", "\\H", "\\v", "\\textcircled"],
  props: {
    numArgs: 1,
    allowedInText: true,
    allowedInMath: true,
    // unless in strict mode
    argTypes: ["primitive"]
  },
  handler: (context, args) => {
    var base2 = args[0];
    var mode = context.parser.mode;
    if (mode === "math") {
      context.parser.settings.reportNonstrict("mathVsTextAccents", "LaTeX's accent " + context.funcName + " works only in text mode");
      mode = "text";
    }
    return {
      type: "accent",
      mode,
      label: context.funcName,
      isStretchy: false,
      isShifty: true,
      base: base2
    };
  },
  htmlBuilder: htmlBuilder$a,
  mathmlBuilder: mathmlBuilder$9
});
defineFunction({
  type: "accentUnder",
  names: ["\\underleftarrow", "\\underrightarrow", "\\underleftrightarrow", "\\undergroup", "\\underlinesegment", "\\utilde"],
  props: {
    numArgs: 1
  },
  handler: (_ref, args) => {
    var {
      parser,
      funcName
    } = _ref;
    var base2 = args[0];
    return {
      type: "accentUnder",
      mode: parser.mode,
      label: funcName,
      base: base2
    };
  },
  htmlBuilder: (group, options) => {
    var innerGroup = buildGroup$1(group.base, options);
    var accentBody = stretchy.svgSpan(group, options);
    var kern = group.label === "\\utilde" ? 0.12 : 0;
    var vlist = buildCommon.makeVList({
      positionType: "top",
      positionData: innerGroup.height,
      children: [{
        type: "elem",
        elem: accentBody,
        wrapperClasses: ["svg-align"]
      }, {
        type: "kern",
        size: kern
      }, {
        type: "elem",
        elem: innerGroup
      }]
    }, options);
    return buildCommon.makeSpan(["mord", "accentunder"], [vlist], options);
  },
  mathmlBuilder: (group, options) => {
    var accentNode = stretchy.mathMLnode(group.label);
    var node = new mathMLTree.MathNode("munder", [buildGroup2(group.base, options), accentNode]);
    node.setAttribute("accentunder", "true");
    return node;
  }
});
var paddedNode = (group) => {
  var node = new mathMLTree.MathNode("mpadded", group ? [group] : []);
  node.setAttribute("width", "+0.6em");
  node.setAttribute("lspace", "0.3em");
  return node;
};
defineFunction({
  type: "xArrow",
  names: [
    "\\xleftarrow",
    "\\xrightarrow",
    "\\xLeftarrow",
    "\\xRightarrow",
    "\\xleftrightarrow",
    "\\xLeftrightarrow",
    "\\xhookleftarrow",
    "\\xhookrightarrow",
    "\\xmapsto",
    "\\xrightharpoondown",
    "\\xrightharpoonup",
    "\\xleftharpoondown",
    "\\xleftharpoonup",
    "\\xrightleftharpoons",
    "\\xleftrightharpoons",
    "\\xlongequal",
    "\\xtwoheadrightarrow",
    "\\xtwoheadleftarrow",
    "\\xtofrom",
    // The next 3 functions are here to support the mhchem extension.
    // Direct use of these functions is discouraged and may break someday.
    "\\xrightleftarrows",
    "\\xrightequilibrium",
    "\\xleftequilibrium",
    // The next 3 functions are here only to support the {CD} environment.
    "\\\\cdrightarrow",
    "\\\\cdleftarrow",
    "\\\\cdlongequal"
  ],
  props: {
    numArgs: 1,
    numOptionalArgs: 1
  },
  handler(_ref, args, optArgs) {
    var {
      parser,
      funcName
    } = _ref;
    return {
      type: "xArrow",
      mode: parser.mode,
      label: funcName,
      body: args[0],
      below: optArgs[0]
    };
  },
  // Flow is unable to correctly infer the type of `group`, even though it's
  // unambiguously determined from the passed-in `type` above.
  htmlBuilder(group, options) {
    var style2 = options.style;
    var newOptions = options.havingStyle(style2.sup());
    var upperGroup = buildCommon.wrapFragment(buildGroup$1(group.body, newOptions, options), options);
    var arrowPrefix = group.label.slice(0, 2) === "\\x" ? "x" : "cd";
    upperGroup.classes.push(arrowPrefix + "-arrow-pad");
    var lowerGroup;
    if (group.below) {
      newOptions = options.havingStyle(style2.sub());
      lowerGroup = buildCommon.wrapFragment(buildGroup$1(group.below, newOptions, options), options);
      lowerGroup.classes.push(arrowPrefix + "-arrow-pad");
    }
    var arrowBody = stretchy.svgSpan(group, options);
    var arrowShift = -options.fontMetrics().axisHeight + 0.5 * arrowBody.height;
    var upperShift = -options.fontMetrics().axisHeight - 0.5 * arrowBody.height - 0.111;
    if (upperGroup.depth > 0.25 || group.label === "\\xleftequilibrium") {
      upperShift -= upperGroup.depth;
    }
    var vlist;
    if (lowerGroup) {
      var lowerShift = -options.fontMetrics().axisHeight + lowerGroup.height + 0.5 * arrowBody.height + 0.111;
      vlist = buildCommon.makeVList({
        positionType: "individualShift",
        children: [{
          type: "elem",
          elem: upperGroup,
          shift: upperShift
        }, {
          type: "elem",
          elem: arrowBody,
          shift: arrowShift
        }, {
          type: "elem",
          elem: lowerGroup,
          shift: lowerShift
        }]
      }, options);
    } else {
      vlist = buildCommon.makeVList({
        positionType: "individualShift",
        children: [{
          type: "elem",
          elem: upperGroup,
          shift: upperShift
        }, {
          type: "elem",
          elem: arrowBody,
          shift: arrowShift
        }]
      }, options);
    }
    vlist.children[0].children[0].children[1].classes.push("svg-align");
    return buildCommon.makeSpan(["mrel", "x-arrow"], [vlist], options);
  },
  mathmlBuilder(group, options) {
    var arrowNode = stretchy.mathMLnode(group.label);
    arrowNode.setAttribute("minsize", group.label.charAt(0) === "x" ? "1.75em" : "3.0em");
    var node;
    if (group.body) {
      var upperNode = paddedNode(buildGroup2(group.body, options));
      if (group.below) {
        var lowerNode = paddedNode(buildGroup2(group.below, options));
        node = new mathMLTree.MathNode("munderover", [arrowNode, lowerNode, upperNode]);
      } else {
        node = new mathMLTree.MathNode("mover", [arrowNode, upperNode]);
      }
    } else if (group.below) {
      var _lowerNode = paddedNode(buildGroup2(group.below, options));
      node = new mathMLTree.MathNode("munder", [arrowNode, _lowerNode]);
    } else {
      node = paddedNode();
      node = new mathMLTree.MathNode("mover", [arrowNode, node]);
    }
    return node;
  }
});
var makeSpan2 = buildCommon.makeSpan;
function htmlBuilder$9(group, options) {
  var elements = buildExpression$1(group.body, options, true);
  return makeSpan2([group.mclass], elements, options);
}
function mathmlBuilder$8(group, options) {
  var node;
  var inner2 = buildExpression2(group.body, options);
  if (group.mclass === "minner") {
    node = new mathMLTree.MathNode("mpadded", inner2);
  } else if (group.mclass === "mord") {
    if (group.isCharacterBox) {
      node = inner2[0];
      node.type = "mi";
    } else {
      node = new mathMLTree.MathNode("mi", inner2);
    }
  } else {
    if (group.isCharacterBox) {
      node = inner2[0];
      node.type = "mo";
    } else {
      node = new mathMLTree.MathNode("mo", inner2);
    }
    if (group.mclass === "mbin") {
      node.attributes.lspace = "0.22em";
      node.attributes.rspace = "0.22em";
    } else if (group.mclass === "mpunct") {
      node.attributes.lspace = "0em";
      node.attributes.rspace = "0.17em";
    } else if (group.mclass === "mopen" || group.mclass === "mclose") {
      node.attributes.lspace = "0em";
      node.attributes.rspace = "0em";
    } else if (group.mclass === "minner") {
      node.attributes.lspace = "0.0556em";
      node.attributes.width = "+0.1111em";
    }
  }
  return node;
}
defineFunction({
  type: "mclass",
  names: ["\\mathord", "\\mathbin", "\\mathrel", "\\mathopen", "\\mathclose", "\\mathpunct", "\\mathinner"],
  props: {
    numArgs: 1,
    primitive: true
  },
  handler(_ref, args) {
    var {
      parser,
      funcName
    } = _ref;
    var body = args[0];
    return {
      type: "mclass",
      mode: parser.mode,
      mclass: "m" + funcName.slice(5),
      // TODO(kevinb): don't prefix with 'm'
      body: ordargument(body),
      isCharacterBox: utils.isCharacterBox(body)
    };
  },
  htmlBuilder: htmlBuilder$9,
  mathmlBuilder: mathmlBuilder$8
});
var binrelClass = (arg) => {
  var atom = arg.type === "ordgroup" && arg.body.length ? arg.body[0] : arg;
  if (atom.type === "atom" && (atom.family === "bin" || atom.family === "rel")) {
    return "m" + atom.family;
  } else {
    return "mord";
  }
};
defineFunction({
  type: "mclass",
  names: ["\\@binrel"],
  props: {
    numArgs: 2
  },
  handler(_ref2, args) {
    var {
      parser
    } = _ref2;
    return {
      type: "mclass",
      mode: parser.mode,
      mclass: binrelClass(args[0]),
      body: ordargument(args[1]),
      isCharacterBox: utils.isCharacterBox(args[1])
    };
  }
});
defineFunction({
  type: "mclass",
  names: ["\\stackrel", "\\overset", "\\underset"],
  props: {
    numArgs: 2
  },
  handler(_ref3, args) {
    var {
      parser,
      funcName
    } = _ref3;
    var baseArg = args[1];
    var shiftedArg = args[0];
    var mclass;
    if (funcName !== "\\stackrel") {
      mclass = binrelClass(baseArg);
    } else {
      mclass = "mrel";
    }
    var baseOp = {
      type: "op",
      mode: baseArg.mode,
      limits: true,
      alwaysHandleSupSub: true,
      parentIsSupSub: false,
      symbol: false,
      suppressBaseShift: funcName !== "\\stackrel",
      body: ordargument(baseArg)
    };
    var supsub = {
      type: "supsub",
      mode: shiftedArg.mode,
      base: baseOp,
      sup: funcName === "\\underset" ? null : shiftedArg,
      sub: funcName === "\\underset" ? shiftedArg : null
    };
    return {
      type: "mclass",
      mode: parser.mode,
      mclass,
      body: [supsub],
      isCharacterBox: utils.isCharacterBox(supsub)
    };
  },
  htmlBuilder: htmlBuilder$9,
  mathmlBuilder: mathmlBuilder$8
});
defineFunction({
  type: "pmb",
  names: ["\\pmb"],
  props: {
    numArgs: 1,
    allowedInText: true
  },
  handler(_ref, args) {
    var {
      parser
    } = _ref;
    return {
      type: "pmb",
      mode: parser.mode,
      mclass: binrelClass(args[0]),
      body: ordargument(args[0])
    };
  },
  htmlBuilder(group, options) {
    var elements = buildExpression$1(group.body, options, true);
    var node = buildCommon.makeSpan([group.mclass], elements, options);
    node.style.textShadow = "0.02em 0.01em 0.04px";
    return node;
  },
  mathmlBuilder(group, style2) {
    var inner2 = buildExpression2(group.body, style2);
    var node = new mathMLTree.MathNode("mstyle", inner2);
    node.setAttribute("style", "text-shadow: 0.02em 0.01em 0.04px");
    return node;
  }
});
var cdArrowFunctionName = {
  ">": "\\\\cdrightarrow",
  "<": "\\\\cdleftarrow",
  "=": "\\\\cdlongequal",
  "A": "\\uparrow",
  "V": "\\downarrow",
  "|": "\\Vert",
  ".": "no arrow"
};
var newCell = () => {
  return {
    type: "styling",
    body: [],
    mode: "math",
    style: "display"
  };
};
var isStartOfArrow = (node) => {
  return node.type === "textord" && node.text === "@";
};
var isLabelEnd = (node, endChar) => {
  return (node.type === "mathord" || node.type === "atom") && node.text === endChar;
};
function cdArrow(arrowChar, labels, parser) {
  var funcName = cdArrowFunctionName[arrowChar];
  switch (funcName) {
    case "\\\\cdrightarrow":
    case "\\\\cdleftarrow":
      return parser.callFunction(funcName, [labels[0]], [labels[1]]);
    case "\\uparrow":
    case "\\downarrow": {
      var leftLabel = parser.callFunction("\\\\cdleft", [labels[0]], []);
      var bareArrow = {
        type: "atom",
        text: funcName,
        mode: "math",
        family: "rel"
      };
      var sizedArrow = parser.callFunction("\\Big", [bareArrow], []);
      var rightLabel = parser.callFunction("\\\\cdright", [labels[1]], []);
      var arrowGroup = {
        type: "ordgroup",
        mode: "math",
        body: [leftLabel, sizedArrow, rightLabel]
      };
      return parser.callFunction("\\\\cdparent", [arrowGroup], []);
    }
    case "\\\\cdlongequal":
      return parser.callFunction("\\\\cdlongequal", [], []);
    case "\\Vert": {
      var arrow2 = {
        type: "textord",
        text: "\\Vert",
        mode: "math"
      };
      return parser.callFunction("\\Big", [arrow2], []);
    }
    default:
      return {
        type: "textord",
        text: " ",
        mode: "math"
      };
  }
}
function parseCD(parser) {
  var parsedRows = [];
  parser.gullet.beginGroup();
  parser.gullet.macros.set("\\cr", "\\\\\\relax");
  parser.gullet.beginGroup();
  while (true) {
    parsedRows.push(parser.parseExpression(false, "\\\\"));
    parser.gullet.endGroup();
    parser.gullet.beginGroup();
    var next = parser.fetch().text;
    if (next === "&" || next === "\\\\") {
      parser.consume();
    } else if (next === "\\end") {
      if (parsedRows[parsedRows.length - 1].length === 0) {
        parsedRows.pop();
      }
      break;
    } else {
      throw new ParseError("Expected \\\\ or \\cr or \\end", parser.nextToken);
    }
  }
  var row = [];
  var body = [row];
  for (var i = 0; i < parsedRows.length; i++) {
    var rowNodes = parsedRows[i];
    var cell = newCell();
    for (var j = 0; j < rowNodes.length; j++) {
      if (!isStartOfArrow(rowNodes[j])) {
        cell.body.push(rowNodes[j]);
      } else {
        row.push(cell);
        j += 1;
        var arrowChar = assertSymbolNodeType(rowNodes[j]).text;
        var labels = new Array(2);
        labels[0] = {
          type: "ordgroup",
          mode: "math",
          body: []
        };
        labels[1] = {
          type: "ordgroup",
          mode: "math",
          body: []
        };
        if ("=|.".indexOf(arrowChar) > -1) ;
        else if ("<>AV".indexOf(arrowChar) > -1) {
          for (var labelNum = 0; labelNum < 2; labelNum++) {
            var inLabel = true;
            for (var k = j + 1; k < rowNodes.length; k++) {
              if (isLabelEnd(rowNodes[k], arrowChar)) {
                inLabel = false;
                j = k;
                break;
              }
              if (isStartOfArrow(rowNodes[k])) {
                throw new ParseError("Missing a " + arrowChar + " character to complete a CD arrow.", rowNodes[k]);
              }
              labels[labelNum].body.push(rowNodes[k]);
            }
            if (inLabel) {
              throw new ParseError("Missing a " + arrowChar + " character to complete a CD arrow.", rowNodes[j]);
            }
          }
        } else {
          throw new ParseError('Expected one of "<>AV=|." after @', rowNodes[j]);
        }
        var arrow2 = cdArrow(arrowChar, labels, parser);
        var wrappedArrow = {
          type: "styling",
          body: [arrow2],
          mode: "math",
          style: "display"
          // CD is always displaystyle.
        };
        row.push(wrappedArrow);
        cell = newCell();
      }
    }
    if (i % 2 === 0) {
      row.push(cell);
    } else {
      row.shift();
    }
    row = [];
    body.push(row);
  }
  parser.gullet.endGroup();
  parser.gullet.endGroup();
  var cols = new Array(body[0].length).fill({
    type: "align",
    align: "c",
    pregap: 0.25,
    // CD package sets \enskip between columns.
    postgap: 0.25
    // So pre and post each get half an \enskip, i.e. 0.25em.
  });
  return {
    type: "array",
    mode: "math",
    body,
    arraystretch: 1,
    addJot: true,
    rowGaps: [null],
    cols,
    colSeparationType: "CD",
    hLinesBeforeRow: new Array(body.length + 1).fill([])
  };
}
defineFunction({
  type: "cdlabel",
  names: ["\\\\cdleft", "\\\\cdright"],
  props: {
    numArgs: 1
  },
  handler(_ref, args) {
    var {
      parser,
      funcName
    } = _ref;
    return {
      type: "cdlabel",
      mode: parser.mode,
      side: funcName.slice(4),
      label: args[0]
    };
  },
  htmlBuilder(group, options) {
    var newOptions = options.havingStyle(options.style.sup());
    var label = buildCommon.wrapFragment(buildGroup$1(group.label, newOptions, options), options);
    label.classes.push("cd-label-" + group.side);
    label.style.bottom = makeEm(0.8 - label.depth);
    label.height = 0;
    label.depth = 0;
    return label;
  },
  mathmlBuilder(group, options) {
    var label = new mathMLTree.MathNode("mrow", [buildGroup2(group.label, options)]);
    label = new mathMLTree.MathNode("mpadded", [label]);
    label.setAttribute("width", "0");
    if (group.side === "left") {
      label.setAttribute("lspace", "-1width");
    }
    label.setAttribute("voffset", "0.7em");
    label = new mathMLTree.MathNode("mstyle", [label]);
    label.setAttribute("displaystyle", "false");
    label.setAttribute("scriptlevel", "1");
    return label;
  }
});
defineFunction({
  type: "cdlabelparent",
  names: ["\\\\cdparent"],
  props: {
    numArgs: 1
  },
  handler(_ref2, args) {
    var {
      parser
    } = _ref2;
    return {
      type: "cdlabelparent",
      mode: parser.mode,
      fragment: args[0]
    };
  },
  htmlBuilder(group, options) {
    var parent = buildCommon.wrapFragment(buildGroup$1(group.fragment, options), options);
    parent.classes.push("cd-vert-arrow");
    return parent;
  },
  mathmlBuilder(group, options) {
    return new mathMLTree.MathNode("mrow", [buildGroup2(group.fragment, options)]);
  }
});
defineFunction({
  type: "textord",
  names: ["\\@char"],
  props: {
    numArgs: 1,
    allowedInText: true
  },
  handler(_ref, args) {
    var {
      parser
    } = _ref;
    var arg = assertNodeType(args[0], "ordgroup");
    var group = arg.body;
    var number2 = "";
    for (var i = 0; i < group.length; i++) {
      var node = assertNodeType(group[i], "textord");
      number2 += node.text;
    }
    var code = parseInt(number2);
    var text5;
    if (isNaN(code)) {
      throw new ParseError("\\@char has non-numeric argument " + number2);
    } else if (code < 0 || code >= 1114111) {
      throw new ParseError("\\@char with invalid code point " + number2);
    } else if (code <= 65535) {
      text5 = String.fromCharCode(code);
    } else {
      code -= 65536;
      text5 = String.fromCharCode((code >> 10) + 55296, (code & 1023) + 56320);
    }
    return {
      type: "textord",
      mode: parser.mode,
      text: text5
    };
  }
});
var htmlBuilder$8 = (group, options) => {
  var elements = buildExpression$1(group.body, options.withColor(group.color), false);
  return buildCommon.makeFragment(elements);
};
var mathmlBuilder$7 = (group, options) => {
  var inner2 = buildExpression2(group.body, options.withColor(group.color));
  var node = new mathMLTree.MathNode("mstyle", inner2);
  node.setAttribute("mathcolor", group.color);
  return node;
};
defineFunction({
  type: "color",
  names: ["\\textcolor"],
  props: {
    numArgs: 2,
    allowedInText: true,
    argTypes: ["color", "original"]
  },
  handler(_ref, args) {
    var {
      parser
    } = _ref;
    var color = assertNodeType(args[0], "color-token").color;
    var body = args[1];
    return {
      type: "color",
      mode: parser.mode,
      color,
      body: ordargument(body)
    };
  },
  htmlBuilder: htmlBuilder$8,
  mathmlBuilder: mathmlBuilder$7
});
defineFunction({
  type: "color",
  names: ["\\color"],
  props: {
    numArgs: 1,
    allowedInText: true,
    argTypes: ["color"]
  },
  handler(_ref2, args) {
    var {
      parser,
      breakOnTokenText
    } = _ref2;
    var color = assertNodeType(args[0], "color-token").color;
    parser.gullet.macros.set("\\current@color", color);
    var body = parser.parseExpression(true, breakOnTokenText);
    return {
      type: "color",
      mode: parser.mode,
      color,
      body
    };
  },
  htmlBuilder: htmlBuilder$8,
  mathmlBuilder: mathmlBuilder$7
});
defineFunction({
  type: "cr",
  names: ["\\\\"],
  props: {
    numArgs: 0,
    numOptionalArgs: 0,
    allowedInText: true
  },
  handler(_ref, args, optArgs) {
    var {
      parser
    } = _ref;
    var size = parser.gullet.future().text === "[" ? parser.parseSizeGroup(true) : null;
    var newLine = !parser.settings.displayMode || !parser.settings.useStrictBehavior("newLineInDisplayMode", "In LaTeX, \\\\ or \\newline does nothing in display mode");
    return {
      type: "cr",
      mode: parser.mode,
      newLine,
      size: size && assertNodeType(size, "size").value
    };
  },
  // The following builders are called only at the top level,
  // not within tabular/array environments.
  htmlBuilder(group, options) {
    var span = buildCommon.makeSpan(["mspace"], [], options);
    if (group.newLine) {
      span.classes.push("newline");
      if (group.size) {
        span.style.marginTop = makeEm(calculateSize(group.size, options));
      }
    }
    return span;
  },
  mathmlBuilder(group, options) {
    var node = new mathMLTree.MathNode("mspace");
    if (group.newLine) {
      node.setAttribute("linebreak", "newline");
      if (group.size) {
        node.setAttribute("height", makeEm(calculateSize(group.size, options)));
      }
    }
    return node;
  }
});
var globalMap = {
  "\\global": "\\global",
  "\\long": "\\\\globallong",
  "\\\\globallong": "\\\\globallong",
  "\\def": "\\gdef",
  "\\gdef": "\\gdef",
  "\\edef": "\\xdef",
  "\\xdef": "\\xdef",
  "\\let": "\\\\globallet",
  "\\futurelet": "\\\\globalfuture"
};
var checkControlSequence = (tok) => {
  var name = tok.text;
  if (/^(?:[\\{}$&#^_]|EOF)$/.test(name)) {
    throw new ParseError("Expected a control sequence", tok);
  }
  return name;
};
var getRHS = (parser) => {
  var tok = parser.gullet.popToken();
  if (tok.text === "=") {
    tok = parser.gullet.popToken();
    if (tok.text === " ") {
      tok = parser.gullet.popToken();
    }
  }
  return tok;
};
var letCommand = (parser, name, tok, global) => {
  var macro = parser.gullet.macros.get(tok.text);
  if (macro == null) {
    tok.noexpand = true;
    macro = {
      tokens: [tok],
      numArgs: 0,
      // reproduce the same behavior in expansion
      unexpandable: !parser.gullet.isExpandable(tok.text)
    };
  }
  parser.gullet.macros.set(name, macro, global);
};
defineFunction({
  type: "internal",
  names: [
    "\\global",
    "\\long",
    "\\\\globallong"
    // can’t be entered directly
  ],
  props: {
    numArgs: 0,
    allowedInText: true
  },
  handler(_ref) {
    var {
      parser,
      funcName
    } = _ref;
    parser.consumeSpaces();
    var token = parser.fetch();
    if (globalMap[token.text]) {
      if (funcName === "\\global" || funcName === "\\\\globallong") {
        token.text = globalMap[token.text];
      }
      return assertNodeType(parser.parseFunction(), "internal");
    }
    throw new ParseError("Invalid token after macro prefix", token);
  }
});
defineFunction({
  type: "internal",
  names: ["\\def", "\\gdef", "\\edef", "\\xdef"],
  props: {
    numArgs: 0,
    allowedInText: true,
    primitive: true
  },
  handler(_ref2) {
    var {
      parser,
      funcName
    } = _ref2;
    var tok = parser.gullet.popToken();
    var name = tok.text;
    if (/^(?:[\\{}$&#^_]|EOF)$/.test(name)) {
      throw new ParseError("Expected a control sequence", tok);
    }
    var numArgs = 0;
    var insert2;
    var delimiters2 = [[]];
    while (parser.gullet.future().text !== "{") {
      tok = parser.gullet.popToken();
      if (tok.text === "#") {
        if (parser.gullet.future().text === "{") {
          insert2 = parser.gullet.future();
          delimiters2[numArgs].push("{");
          break;
        }
        tok = parser.gullet.popToken();
        if (!/^[1-9]$/.test(tok.text)) {
          throw new ParseError('Invalid argument number "' + tok.text + '"');
        }
        if (parseInt(tok.text) !== numArgs + 1) {
          throw new ParseError('Argument number "' + tok.text + '" out of order');
        }
        numArgs++;
        delimiters2.push([]);
      } else if (tok.text === "EOF") {
        throw new ParseError("Expected a macro definition");
      } else {
        delimiters2[numArgs].push(tok.text);
      }
    }
    var {
      tokens
    } = parser.gullet.consumeArg();
    if (insert2) {
      tokens.unshift(insert2);
    }
    if (funcName === "\\edef" || funcName === "\\xdef") {
      tokens = parser.gullet.expandTokens(tokens);
      tokens.reverse();
    }
    parser.gullet.macros.set(name, {
      tokens,
      numArgs,
      delimiters: delimiters2
    }, funcName === globalMap[funcName]);
    return {
      type: "internal",
      mode: parser.mode
    };
  }
});
defineFunction({
  type: "internal",
  names: [
    "\\let",
    "\\\\globallet"
    // can’t be entered directly
  ],
  props: {
    numArgs: 0,
    allowedInText: true,
    primitive: true
  },
  handler(_ref3) {
    var {
      parser,
      funcName
    } = _ref3;
    var name = checkControlSequence(parser.gullet.popToken());
    parser.gullet.consumeSpaces();
    var tok = getRHS(parser);
    letCommand(parser, name, tok, funcName === "\\\\globallet");
    return {
      type: "internal",
      mode: parser.mode
    };
  }
});
defineFunction({
  type: "internal",
  names: [
    "\\futurelet",
    "\\\\globalfuture"
    // can’t be entered directly
  ],
  props: {
    numArgs: 0,
    allowedInText: true,
    primitive: true
  },
  handler(_ref4) {
    var {
      parser,
      funcName
    } = _ref4;
    var name = checkControlSequence(parser.gullet.popToken());
    var middle = parser.gullet.popToken();
    var tok = parser.gullet.popToken();
    letCommand(parser, name, tok, funcName === "\\\\globalfuture");
    parser.gullet.pushToken(tok);
    parser.gullet.pushToken(middle);
    return {
      type: "internal",
      mode: parser.mode
    };
  }
});
var getMetrics = function getMetrics2(symbol, font, mode) {
  var replace2 = symbols.math[symbol] && symbols.math[symbol].replace;
  var metrics = getCharacterMetrics(replace2 || symbol, font, mode);
  if (!metrics) {
    throw new Error("Unsupported symbol " + symbol + " and font size " + font + ".");
  }
  return metrics;
};
var styleWrap = function styleWrap2(delim, toStyle, options, classes) {
  var newOptions = options.havingBaseStyle(toStyle);
  var span = buildCommon.makeSpan(classes.concat(newOptions.sizingClasses(options)), [delim], options);
  var delimSizeMultiplier = newOptions.sizeMultiplier / options.sizeMultiplier;
  span.height *= delimSizeMultiplier;
  span.depth *= delimSizeMultiplier;
  span.maxFontSize = newOptions.sizeMultiplier;
  return span;
};
var centerSpan = function centerSpan2(span, options, style2) {
  var newOptions = options.havingBaseStyle(style2);
  var shift2 = (1 - options.sizeMultiplier / newOptions.sizeMultiplier) * options.fontMetrics().axisHeight;
  span.classes.push("delimcenter");
  span.style.top = makeEm(shift2);
  span.height -= shift2;
  span.depth += shift2;
};
var makeSmallDelim = function makeSmallDelim2(delim, style2, center3, options, mode, classes) {
  var text5 = buildCommon.makeSymbol(delim, "Main-Regular", mode, options);
  var span = styleWrap(text5, style2, options, classes);
  if (center3) {
    centerSpan(span, options, style2);
  }
  return span;
};
var mathrmSize = function mathrmSize2(value, size, mode, options) {
  return buildCommon.makeSymbol(value, "Size" + size + "-Regular", mode, options);
};
var makeLargeDelim = function makeLargeDelim2(delim, size, center3, options, mode, classes) {
  var inner2 = mathrmSize(delim, size, mode, options);
  var span = styleWrap(buildCommon.makeSpan(["delimsizing", "size" + size], [inner2], options), Style$1.TEXT, options, classes);
  if (center3) {
    centerSpan(span, options, Style$1.TEXT);
  }
  return span;
};
var makeGlyphSpan = function makeGlyphSpan2(symbol, font, mode) {
  var sizeClass;
  if (font === "Size1-Regular") {
    sizeClass = "delim-size1";
  } else {
    sizeClass = "delim-size4";
  }
  var corner = buildCommon.makeSpan(["delimsizinginner", sizeClass], [buildCommon.makeSpan([], [buildCommon.makeSymbol(symbol, font, mode)])]);
  return {
    type: "elem",
    elem: corner
  };
};
var makeInner = function makeInner2(ch, height, options) {
  var width = fontMetricsData["Size4-Regular"][ch.charCodeAt(0)] ? fontMetricsData["Size4-Regular"][ch.charCodeAt(0)][4] : fontMetricsData["Size1-Regular"][ch.charCodeAt(0)][4];
  var path2 = new PathNode("inner", innerPath(ch, Math.round(1e3 * height)));
  var svgNode = new SvgNode([path2], {
    "width": makeEm(width),
    "height": makeEm(height),
    // Override CSS rule `.katex svg { width: 100% }`
    "style": "width:" + makeEm(width),
    "viewBox": "0 0 " + 1e3 * width + " " + Math.round(1e3 * height),
    "preserveAspectRatio": "xMinYMin"
  });
  var span = buildCommon.makeSvgSpan([], [svgNode], options);
  span.height = height;
  span.style.height = makeEm(height);
  span.style.width = makeEm(width);
  return {
    type: "elem",
    elem: span
  };
};
var lapInEms = 8e-3;
var lap = {
  type: "kern",
  size: -1 * lapInEms
};
var verts = ["|", "\\lvert", "\\rvert", "\\vert"];
var doubleVerts = ["\\|", "\\lVert", "\\rVert", "\\Vert"];
var makeStackedDelim = function makeStackedDelim2(delim, heightTotal, center3, options, mode, classes) {
  var top;
  var middle;
  var repeat;
  var bottom;
  var svgLabel = "";
  var viewBoxWidth = 0;
  top = repeat = bottom = delim;
  middle = null;
  var font = "Size1-Regular";
  if (delim === "\\uparrow") {
    repeat = bottom = "\u23D0";
  } else if (delim === "\\Uparrow") {
    repeat = bottom = "\u2016";
  } else if (delim === "\\downarrow") {
    top = repeat = "\u23D0";
  } else if (delim === "\\Downarrow") {
    top = repeat = "\u2016";
  } else if (delim === "\\updownarrow") {
    top = "\\uparrow";
    repeat = "\u23D0";
    bottom = "\\downarrow";
  } else if (delim === "\\Updownarrow") {
    top = "\\Uparrow";
    repeat = "\u2016";
    bottom = "\\Downarrow";
  } else if (utils.contains(verts, delim)) {
    repeat = "\u2223";
    svgLabel = "vert";
    viewBoxWidth = 333;
  } else if (utils.contains(doubleVerts, delim)) {
    repeat = "\u2225";
    svgLabel = "doublevert";
    viewBoxWidth = 556;
  } else if (delim === "[" || delim === "\\lbrack") {
    top = "\u23A1";
    repeat = "\u23A2";
    bottom = "\u23A3";
    font = "Size4-Regular";
    svgLabel = "lbrack";
    viewBoxWidth = 667;
  } else if (delim === "]" || delim === "\\rbrack") {
    top = "\u23A4";
    repeat = "\u23A5";
    bottom = "\u23A6";
    font = "Size4-Regular";
    svgLabel = "rbrack";
    viewBoxWidth = 667;
  } else if (delim === "\\lfloor" || delim === "\u230A") {
    repeat = top = "\u23A2";
    bottom = "\u23A3";
    font = "Size4-Regular";
    svgLabel = "lfloor";
    viewBoxWidth = 667;
  } else if (delim === "\\lceil" || delim === "\u2308") {
    top = "\u23A1";
    repeat = bottom = "\u23A2";
    font = "Size4-Regular";
    svgLabel = "lceil";
    viewBoxWidth = 667;
  } else if (delim === "\\rfloor" || delim === "\u230B") {
    repeat = top = "\u23A5";
    bottom = "\u23A6";
    font = "Size4-Regular";
    svgLabel = "rfloor";
    viewBoxWidth = 667;
  } else if (delim === "\\rceil" || delim === "\u2309") {
    top = "\u23A4";
    repeat = bottom = "\u23A5";
    font = "Size4-Regular";
    svgLabel = "rceil";
    viewBoxWidth = 667;
  } else if (delim === "(" || delim === "\\lparen") {
    top = "\u239B";
    repeat = "\u239C";
    bottom = "\u239D";
    font = "Size4-Regular";
    svgLabel = "lparen";
    viewBoxWidth = 875;
  } else if (delim === ")" || delim === "\\rparen") {
    top = "\u239E";
    repeat = "\u239F";
    bottom = "\u23A0";
    font = "Size4-Regular";
    svgLabel = "rparen";
    viewBoxWidth = 875;
  } else if (delim === "\\{" || delim === "\\lbrace") {
    top = "\u23A7";
    middle = "\u23A8";
    bottom = "\u23A9";
    repeat = "\u23AA";
    font = "Size4-Regular";
  } else if (delim === "\\}" || delim === "\\rbrace") {
    top = "\u23AB";
    middle = "\u23AC";
    bottom = "\u23AD";
    repeat = "\u23AA";
    font = "Size4-Regular";
  } else if (delim === "\\lgroup" || delim === "\u27EE") {
    top = "\u23A7";
    bottom = "\u23A9";
    repeat = "\u23AA";
    font = "Size4-Regular";
  } else if (delim === "\\rgroup" || delim === "\u27EF") {
    top = "\u23AB";
    bottom = "\u23AD";
    repeat = "\u23AA";
    font = "Size4-Regular";
  } else if (delim === "\\lmoustache" || delim === "\u23B0") {
    top = "\u23A7";
    bottom = "\u23AD";
    repeat = "\u23AA";
    font = "Size4-Regular";
  } else if (delim === "\\rmoustache" || delim === "\u23B1") {
    top = "\u23AB";
    bottom = "\u23A9";
    repeat = "\u23AA";
    font = "Size4-Regular";
  }
  var topMetrics = getMetrics(top, font, mode);
  var topHeightTotal = topMetrics.height + topMetrics.depth;
  var repeatMetrics = getMetrics(repeat, font, mode);
  var repeatHeightTotal = repeatMetrics.height + repeatMetrics.depth;
  var bottomMetrics = getMetrics(bottom, font, mode);
  var bottomHeightTotal = bottomMetrics.height + bottomMetrics.depth;
  var middleHeightTotal = 0;
  var middleFactor = 1;
  if (middle !== null) {
    var middleMetrics = getMetrics(middle, font, mode);
    middleHeightTotal = middleMetrics.height + middleMetrics.depth;
    middleFactor = 2;
  }
  var minHeight = topHeightTotal + bottomHeightTotal + middleHeightTotal;
  var repeatCount = Math.max(0, Math.ceil((heightTotal - minHeight) / (middleFactor * repeatHeightTotal)));
  var realHeightTotal = minHeight + repeatCount * middleFactor * repeatHeightTotal;
  var axisHeight = options.fontMetrics().axisHeight;
  if (center3) {
    axisHeight *= options.sizeMultiplier;
  }
  var depth = realHeightTotal / 2 - axisHeight;
  var stack = [];
  if (svgLabel.length > 0) {
    var midHeight = realHeightTotal - topHeightTotal - bottomHeightTotal;
    var viewBoxHeight = Math.round(realHeightTotal * 1e3);
    var pathStr = tallDelim(svgLabel, Math.round(midHeight * 1e3));
    var path2 = new PathNode(svgLabel, pathStr);
    var width = (viewBoxWidth / 1e3).toFixed(3) + "em";
    var height = (viewBoxHeight / 1e3).toFixed(3) + "em";
    var svg = new SvgNode([path2], {
      "width": width,
      "height": height,
      "viewBox": "0 0 " + viewBoxWidth + " " + viewBoxHeight
    });
    var wrapper = buildCommon.makeSvgSpan([], [svg], options);
    wrapper.height = viewBoxHeight / 1e3;
    wrapper.style.width = width;
    wrapper.style.height = height;
    stack.push({
      type: "elem",
      elem: wrapper
    });
  } else {
    stack.push(makeGlyphSpan(bottom, font, mode));
    stack.push(lap);
    if (middle === null) {
      var innerHeight2 = realHeightTotal - topHeightTotal - bottomHeightTotal + 2 * lapInEms;
      stack.push(makeInner(repeat, innerHeight2, options));
    } else {
      var _innerHeight = (realHeightTotal - topHeightTotal - bottomHeightTotal - middleHeightTotal) / 2 + 2 * lapInEms;
      stack.push(makeInner(repeat, _innerHeight, options));
      stack.push(lap);
      stack.push(makeGlyphSpan(middle, font, mode));
      stack.push(lap);
      stack.push(makeInner(repeat, _innerHeight, options));
    }
    stack.push(lap);
    stack.push(makeGlyphSpan(top, font, mode));
  }
  var newOptions = options.havingBaseStyle(Style$1.TEXT);
  var inner2 = buildCommon.makeVList({
    positionType: "bottom",
    positionData: depth,
    children: stack
  }, newOptions);
  return styleWrap(buildCommon.makeSpan(["delimsizing", "mult"], [inner2], newOptions), Style$1.TEXT, options, classes);
};
var vbPad = 80;
var emPad = 0.08;
var sqrtSvg = function sqrtSvg2(sqrtName, height, viewBoxHeight, extraVinculum, options) {
  var path2 = sqrtPath(sqrtName, extraVinculum, viewBoxHeight);
  var pathNode = new PathNode(sqrtName, path2);
  var svg = new SvgNode([pathNode], {
    // Note: 1000:1 ratio of viewBox to document em width.
    "width": "400em",
    "height": makeEm(height),
    "viewBox": "0 0 400000 " + viewBoxHeight,
    "preserveAspectRatio": "xMinYMin slice"
  });
  return buildCommon.makeSvgSpan(["hide-tail"], [svg], options);
};
var makeSqrtImage = function makeSqrtImage2(height, options) {
  var newOptions = options.havingBaseSizing();
  var delim = traverseSequence("\\surd", height * newOptions.sizeMultiplier, stackLargeDelimiterSequence, newOptions);
  var sizeMultiplier = newOptions.sizeMultiplier;
  var extraVinculum = Math.max(0, options.minRuleThickness - options.fontMetrics().sqrtRuleThickness);
  var span;
  var spanHeight = 0;
  var texHeight = 0;
  var viewBoxHeight = 0;
  var advanceWidth;
  if (delim.type === "small") {
    viewBoxHeight = 1e3 + 1e3 * extraVinculum + vbPad;
    if (height < 1) {
      sizeMultiplier = 1;
    } else if (height < 1.4) {
      sizeMultiplier = 0.7;
    }
    spanHeight = (1 + extraVinculum + emPad) / sizeMultiplier;
    texHeight = (1 + extraVinculum) / sizeMultiplier;
    span = sqrtSvg("sqrtMain", spanHeight, viewBoxHeight, extraVinculum, options);
    span.style.minWidth = "0.853em";
    advanceWidth = 0.833 / sizeMultiplier;
  } else if (delim.type === "large") {
    viewBoxHeight = (1e3 + vbPad) * sizeToMaxHeight[delim.size];
    texHeight = (sizeToMaxHeight[delim.size] + extraVinculum) / sizeMultiplier;
    spanHeight = (sizeToMaxHeight[delim.size] + extraVinculum + emPad) / sizeMultiplier;
    span = sqrtSvg("sqrtSize" + delim.size, spanHeight, viewBoxHeight, extraVinculum, options);
    span.style.minWidth = "1.02em";
    advanceWidth = 1 / sizeMultiplier;
  } else {
    spanHeight = height + extraVinculum + emPad;
    texHeight = height + extraVinculum;
    viewBoxHeight = Math.floor(1e3 * height + extraVinculum) + vbPad;
    span = sqrtSvg("sqrtTall", spanHeight, viewBoxHeight, extraVinculum, options);
    span.style.minWidth = "0.742em";
    advanceWidth = 1.056;
  }
  span.height = texHeight;
  span.style.height = makeEm(spanHeight);
  return {
    span,
    advanceWidth,
    // Calculate the actual line width.
    // This actually should depend on the chosen font -- e.g. \boldmath
    // should use the thicker surd symbols from e.g. KaTeX_Main-Bold, and
    // have thicker rules.
    ruleWidth: (options.fontMetrics().sqrtRuleThickness + extraVinculum) * sizeMultiplier
  };
};
var stackLargeDelimiters = ["(", "\\lparen", ")", "\\rparen", "[", "\\lbrack", "]", "\\rbrack", "\\{", "\\lbrace", "\\}", "\\rbrace", "\\lfloor", "\\rfloor", "\u230A", "\u230B", "\\lceil", "\\rceil", "\u2308", "\u2309", "\\surd"];
var stackAlwaysDelimiters = ["\\uparrow", "\\downarrow", "\\updownarrow", "\\Uparrow", "\\Downarrow", "\\Updownarrow", "|", "\\|", "\\vert", "\\Vert", "\\lvert", "\\rvert", "\\lVert", "\\rVert", "\\lgroup", "\\rgroup", "\u27EE", "\u27EF", "\\lmoustache", "\\rmoustache", "\u23B0", "\u23B1"];
var stackNeverDelimiters = ["<", ">", "\\langle", "\\rangle", "/", "\\backslash", "\\lt", "\\gt"];
var sizeToMaxHeight = [0, 1.2, 1.8, 2.4, 3];
var makeSizedDelim = function makeSizedDelim2(delim, size, options, mode, classes) {
  if (delim === "<" || delim === "\\lt" || delim === "\u27E8") {
    delim = "\\langle";
  } else if (delim === ">" || delim === "\\gt" || delim === "\u27E9") {
    delim = "\\rangle";
  }
  if (utils.contains(stackLargeDelimiters, delim) || utils.contains(stackNeverDelimiters, delim)) {
    return makeLargeDelim(delim, size, false, options, mode, classes);
  } else if (utils.contains(stackAlwaysDelimiters, delim)) {
    return makeStackedDelim(delim, sizeToMaxHeight[size], false, options, mode, classes);
  } else {
    throw new ParseError("Illegal delimiter: '" + delim + "'");
  }
};
var stackNeverDelimiterSequence = [{
  type: "small",
  style: Style$1.SCRIPTSCRIPT
}, {
  type: "small",
  style: Style$1.SCRIPT
}, {
  type: "small",
  style: Style$1.TEXT
}, {
  type: "large",
  size: 1
}, {
  type: "large",
  size: 2
}, {
  type: "large",
  size: 3
}, {
  type: "large",
  size: 4
}];
var stackAlwaysDelimiterSequence = [{
  type: "small",
  style: Style$1.SCRIPTSCRIPT
}, {
  type: "small",
  style: Style$1.SCRIPT
}, {
  type: "small",
  style: Style$1.TEXT
}, {
  type: "stack"
}];
var stackLargeDelimiterSequence = [{
  type: "small",
  style: Style$1.SCRIPTSCRIPT
}, {
  type: "small",
  style: Style$1.SCRIPT
}, {
  type: "small",
  style: Style$1.TEXT
}, {
  type: "large",
  size: 1
}, {
  type: "large",
  size: 2
}, {
  type: "large",
  size: 3
}, {
  type: "large",
  size: 4
}, {
  type: "stack"
}];
var delimTypeToFont = function delimTypeToFont2(type) {
  if (type.type === "small") {
    return "Main-Regular";
  } else if (type.type === "large") {
    return "Size" + type.size + "-Regular";
  } else if (type.type === "stack") {
    return "Size4-Regular";
  } else {
    throw new Error("Add support for delim type '" + type.type + "' here.");
  }
};
var traverseSequence = function traverseSequence2(delim, height, sequence, options) {
  var start = Math.min(2, 3 - options.style.size);
  for (var i = start; i < sequence.length; i++) {
    if (sequence[i].type === "stack") {
      break;
    }
    var metrics = getMetrics(delim, delimTypeToFont(sequence[i]), "math");
    var heightDepth = metrics.height + metrics.depth;
    if (sequence[i].type === "small") {
      var newOptions = options.havingBaseStyle(sequence[i].style);
      heightDepth *= newOptions.sizeMultiplier;
    }
    if (heightDepth > height) {
      return sequence[i];
    }
  }
  return sequence[sequence.length - 1];
};
var makeCustomSizedDelim = function makeCustomSizedDelim2(delim, height, center3, options, mode, classes) {
  if (delim === "<" || delim === "\\lt" || delim === "\u27E8") {
    delim = "\\langle";
  } else if (delim === ">" || delim === "\\gt" || delim === "\u27E9") {
    delim = "\\rangle";
  }
  var sequence;
  if (utils.contains(stackNeverDelimiters, delim)) {
    sequence = stackNeverDelimiterSequence;
  } else if (utils.contains(stackLargeDelimiters, delim)) {
    sequence = stackLargeDelimiterSequence;
  } else {
    sequence = stackAlwaysDelimiterSequence;
  }
  var delimType = traverseSequence(delim, height, sequence, options);
  if (delimType.type === "small") {
    return makeSmallDelim(delim, delimType.style, center3, options, mode, classes);
  } else if (delimType.type === "large") {
    return makeLargeDelim(delim, delimType.size, center3, options, mode, classes);
  } else {
    return makeStackedDelim(delim, height, center3, options, mode, classes);
  }
};
var makeLeftRightDelim = function makeLeftRightDelim2(delim, height, depth, options, mode, classes) {
  var axisHeight = options.fontMetrics().axisHeight * options.sizeMultiplier;
  var delimiterFactor = 901;
  var delimiterExtend = 5 / options.fontMetrics().ptPerEm;
  var maxDistFromAxis = Math.max(height - axisHeight, depth + axisHeight);
  var totalHeight = Math.max(
    // In real TeX, calculations are done using integral values which are
    // 65536 per pt, or 655360 per em. So, the division here truncates in
    // TeX but doesn't here, producing different results. If we wanted to
    // exactly match TeX's calculation, we could do
    //   Math.floor(655360 * maxDistFromAxis / 500) *
    //    delimiterFactor / 655360
    // (To see the difference, compare
    //    x^{x^{\left(\rule{0.1em}{0.68em}\right)}}
    // in TeX and KaTeX)
    maxDistFromAxis / 500 * delimiterFactor,
    2 * maxDistFromAxis - delimiterExtend
  );
  return makeCustomSizedDelim(delim, totalHeight, true, options, mode, classes);
};
var delimiter = {
  sqrtImage: makeSqrtImage,
  sizedDelim: makeSizedDelim,
  sizeToMaxHeight,
  customSizedDelim: makeCustomSizedDelim,
  leftRightDelim: makeLeftRightDelim
};
var delimiterSizes = {
  "\\bigl": {
    mclass: "mopen",
    size: 1
  },
  "\\Bigl": {
    mclass: "mopen",
    size: 2
  },
  "\\biggl": {
    mclass: "mopen",
    size: 3
  },
  "\\Biggl": {
    mclass: "mopen",
    size: 4
  },
  "\\bigr": {
    mclass: "mclose",
    size: 1
  },
  "\\Bigr": {
    mclass: "mclose",
    size: 2
  },
  "\\biggr": {
    mclass: "mclose",
    size: 3
  },
  "\\Biggr": {
    mclass: "mclose",
    size: 4
  },
  "\\bigm": {
    mclass: "mrel",
    size: 1
  },
  "\\Bigm": {
    mclass: "mrel",
    size: 2
  },
  "\\biggm": {
    mclass: "mrel",
    size: 3
  },
  "\\Biggm": {
    mclass: "mrel",
    size: 4
  },
  "\\big": {
    mclass: "mord",
    size: 1
  },
  "\\Big": {
    mclass: "mord",
    size: 2
  },
  "\\bigg": {
    mclass: "mord",
    size: 3
  },
  "\\Bigg": {
    mclass: "mord",
    size: 4
  }
};
var delimiters = ["(", "\\lparen", ")", "\\rparen", "[", "\\lbrack", "]", "\\rbrack", "\\{", "\\lbrace", "\\}", "\\rbrace", "\\lfloor", "\\rfloor", "\u230A", "\u230B", "\\lceil", "\\rceil", "\u2308", "\u2309", "<", ">", "\\langle", "\u27E8", "\\rangle", "\u27E9", "\\lt", "\\gt", "\\lvert", "\\rvert", "\\lVert", "\\rVert", "\\lgroup", "\\rgroup", "\u27EE", "\u27EF", "\\lmoustache", "\\rmoustache", "\u23B0", "\u23B1", "/", "\\backslash", "|", "\\vert", "\\|", "\\Vert", "\\uparrow", "\\Uparrow", "\\downarrow", "\\Downarrow", "\\updownarrow", "\\Updownarrow", "."];
function checkDelimiter(delim, context) {
  var symDelim = checkSymbolNodeType(delim);
  if (symDelim && utils.contains(delimiters, symDelim.text)) {
    return symDelim;
  } else if (symDelim) {
    throw new ParseError("Invalid delimiter '" + symDelim.text + "' after '" + context.funcName + "'", delim);
  } else {
    throw new ParseError("Invalid delimiter type '" + delim.type + "'", delim);
  }
}
defineFunction({
  type: "delimsizing",
  names: ["\\bigl", "\\Bigl", "\\biggl", "\\Biggl", "\\bigr", "\\Bigr", "\\biggr", "\\Biggr", "\\bigm", "\\Bigm", "\\biggm", "\\Biggm", "\\big", "\\Big", "\\bigg", "\\Bigg"],
  props: {
    numArgs: 1,
    argTypes: ["primitive"]
  },
  handler: (context, args) => {
    var delim = checkDelimiter(args[0], context);
    return {
      type: "delimsizing",
      mode: context.parser.mode,
      size: delimiterSizes[context.funcName].size,
      mclass: delimiterSizes[context.funcName].mclass,
      delim: delim.text
    };
  },
  htmlBuilder: (group, options) => {
    if (group.delim === ".") {
      return buildCommon.makeSpan([group.mclass]);
    }
    return delimiter.sizedDelim(group.delim, group.size, options, group.mode, [group.mclass]);
  },
  mathmlBuilder: (group) => {
    var children = [];
    if (group.delim !== ".") {
      children.push(makeText(group.delim, group.mode));
    }
    var node = new mathMLTree.MathNode("mo", children);
    if (group.mclass === "mopen" || group.mclass === "mclose") {
      node.setAttribute("fence", "true");
    } else {
      node.setAttribute("fence", "false");
    }
    node.setAttribute("stretchy", "true");
    var size = makeEm(delimiter.sizeToMaxHeight[group.size]);
    node.setAttribute("minsize", size);
    node.setAttribute("maxsize", size);
    return node;
  }
});
function assertParsed(group) {
  if (!group.body) {
    throw new Error("Bug: The leftright ParseNode wasn't fully parsed.");
  }
}
defineFunction({
  type: "leftright-right",
  names: ["\\right"],
  props: {
    numArgs: 1,
    primitive: true
  },
  handler: (context, args) => {
    var color = context.parser.gullet.macros.get("\\current@color");
    if (color && typeof color !== "string") {
      throw new ParseError("\\current@color set to non-string in \\right");
    }
    return {
      type: "leftright-right",
      mode: context.parser.mode,
      delim: checkDelimiter(args[0], context).text,
      color
      // undefined if not set via \color
    };
  }
});
defineFunction({
  type: "leftright",
  names: ["\\left"],
  props: {
    numArgs: 1,
    primitive: true
  },
  handler: (context, args) => {
    var delim = checkDelimiter(args[0], context);
    var parser = context.parser;
    ++parser.leftrightDepth;
    var body = parser.parseExpression(false);
    --parser.leftrightDepth;
    parser.expect("\\right", false);
    var right = assertNodeType(parser.parseFunction(), "leftright-right");
    return {
      type: "leftright",
      mode: parser.mode,
      body,
      left: delim.text,
      right: right.delim,
      rightColor: right.color
    };
  },
  htmlBuilder: (group, options) => {
    assertParsed(group);
    var inner2 = buildExpression$1(group.body, options, true, ["mopen", "mclose"]);
    var innerHeight2 = 0;
    var innerDepth = 0;
    var hadMiddle = false;
    for (var i = 0; i < inner2.length; i++) {
      if (inner2[i].isMiddle) {
        hadMiddle = true;
      } else {
        innerHeight2 = Math.max(inner2[i].height, innerHeight2);
        innerDepth = Math.max(inner2[i].depth, innerDepth);
      }
    }
    innerHeight2 *= options.sizeMultiplier;
    innerDepth *= options.sizeMultiplier;
    var leftDelim;
    if (group.left === ".") {
      leftDelim = makeNullDelimiter(options, ["mopen"]);
    } else {
      leftDelim = delimiter.leftRightDelim(group.left, innerHeight2, innerDepth, options, group.mode, ["mopen"]);
    }
    inner2.unshift(leftDelim);
    if (hadMiddle) {
      for (var _i = 1; _i < inner2.length; _i++) {
        var middleDelim = inner2[_i];
        var isMiddle = middleDelim.isMiddle;
        if (isMiddle) {
          inner2[_i] = delimiter.leftRightDelim(isMiddle.delim, innerHeight2, innerDepth, isMiddle.options, group.mode, []);
        }
      }
    }
    var rightDelim;
    if (group.right === ".") {
      rightDelim = makeNullDelimiter(options, ["mclose"]);
    } else {
      var colorOptions = group.rightColor ? options.withColor(group.rightColor) : options;
      rightDelim = delimiter.leftRightDelim(group.right, innerHeight2, innerDepth, colorOptions, group.mode, ["mclose"]);
    }
    inner2.push(rightDelim);
    return buildCommon.makeSpan(["minner"], inner2, options);
  },
  mathmlBuilder: (group, options) => {
    assertParsed(group);
    var inner2 = buildExpression2(group.body, options);
    if (group.left !== ".") {
      var leftNode = new mathMLTree.MathNode("mo", [makeText(group.left, group.mode)]);
      leftNode.setAttribute("fence", "true");
      inner2.unshift(leftNode);
    }
    if (group.right !== ".") {
      var rightNode = new mathMLTree.MathNode("mo", [makeText(group.right, group.mode)]);
      rightNode.setAttribute("fence", "true");
      if (group.rightColor) {
        rightNode.setAttribute("mathcolor", group.rightColor);
      }
      inner2.push(rightNode);
    }
    return makeRow(inner2);
  }
});
defineFunction({
  type: "middle",
  names: ["\\middle"],
  props: {
    numArgs: 1,
    primitive: true
  },
  handler: (context, args) => {
    var delim = checkDelimiter(args[0], context);
    if (!context.parser.leftrightDepth) {
      throw new ParseError("\\middle without preceding \\left", delim);
    }
    return {
      type: "middle",
      mode: context.parser.mode,
      delim: delim.text
    };
  },
  htmlBuilder: (group, options) => {
    var middleDelim;
    if (group.delim === ".") {
      middleDelim = makeNullDelimiter(options, []);
    } else {
      middleDelim = delimiter.sizedDelim(group.delim, 1, options, group.mode, []);
      var isMiddle = {
        delim: group.delim,
        options
      };
      middleDelim.isMiddle = isMiddle;
    }
    return middleDelim;
  },
  mathmlBuilder: (group, options) => {
    var textNode = group.delim === "\\vert" || group.delim === "|" ? makeText("|", "text") : makeText(group.delim, group.mode);
    var middleNode = new mathMLTree.MathNode("mo", [textNode]);
    middleNode.setAttribute("fence", "true");
    middleNode.setAttribute("lspace", "0.05em");
    middleNode.setAttribute("rspace", "0.05em");
    return middleNode;
  }
});
var htmlBuilder$7 = (group, options) => {
  var inner2 = buildCommon.wrapFragment(buildGroup$1(group.body, options), options);
  var label = group.label.slice(1);
  var scale = options.sizeMultiplier;
  var img;
  var imgShift = 0;
  var isSingleChar = utils.isCharacterBox(group.body);
  if (label === "sout") {
    img = buildCommon.makeSpan(["stretchy", "sout"]);
    img.height = options.fontMetrics().defaultRuleThickness / scale;
    imgShift = -0.5 * options.fontMetrics().xHeight;
  } else if (label === "phase") {
    var lineWeight = calculateSize({
      number: 0.6,
      unit: "pt"
    }, options);
    var clearance = calculateSize({
      number: 0.35,
      unit: "ex"
    }, options);
    var newOptions = options.havingBaseSizing();
    scale = scale / newOptions.sizeMultiplier;
    var angleHeight = inner2.height + inner2.depth + lineWeight + clearance;
    inner2.style.paddingLeft = makeEm(angleHeight / 2 + lineWeight);
    var viewBoxHeight = Math.floor(1e3 * angleHeight * scale);
    var path2 = phasePath(viewBoxHeight);
    var svgNode = new SvgNode([new PathNode("phase", path2)], {
      "width": "400em",
      "height": makeEm(viewBoxHeight / 1e3),
      "viewBox": "0 0 400000 " + viewBoxHeight,
      "preserveAspectRatio": "xMinYMin slice"
    });
    img = buildCommon.makeSvgSpan(["hide-tail"], [svgNode], options);
    img.style.height = makeEm(angleHeight);
    imgShift = inner2.depth + lineWeight + clearance;
  } else {
    if (/cancel/.test(label)) {
      if (!isSingleChar) {
        inner2.classes.push("cancel-pad");
      }
    } else if (label === "angl") {
      inner2.classes.push("anglpad");
    } else {
      inner2.classes.push("boxpad");
    }
    var topPad = 0;
    var bottomPad = 0;
    var ruleThickness = 0;
    if (/box/.test(label)) {
      ruleThickness = Math.max(
        options.fontMetrics().fboxrule,
        // default
        options.minRuleThickness
        // User override.
      );
      topPad = options.fontMetrics().fboxsep + (label === "colorbox" ? 0 : ruleThickness);
      bottomPad = topPad;
    } else if (label === "angl") {
      ruleThickness = Math.max(options.fontMetrics().defaultRuleThickness, options.minRuleThickness);
      topPad = 4 * ruleThickness;
      bottomPad = Math.max(0, 0.25 - inner2.depth);
    } else {
      topPad = isSingleChar ? 0.2 : 0;
      bottomPad = topPad;
    }
    img = stretchy.encloseSpan(inner2, label, topPad, bottomPad, options);
    if (/fbox|boxed|fcolorbox/.test(label)) {
      img.style.borderStyle = "solid";
      img.style.borderWidth = makeEm(ruleThickness);
    } else if (label === "angl" && ruleThickness !== 0.049) {
      img.style.borderTopWidth = makeEm(ruleThickness);
      img.style.borderRightWidth = makeEm(ruleThickness);
    }
    imgShift = inner2.depth + bottomPad;
    if (group.backgroundColor) {
      img.style.backgroundColor = group.backgroundColor;
      if (group.borderColor) {
        img.style.borderColor = group.borderColor;
      }
    }
  }
  var vlist;
  if (group.backgroundColor) {
    vlist = buildCommon.makeVList({
      positionType: "individualShift",
      children: [
        // Put the color background behind inner;
        {
          type: "elem",
          elem: img,
          shift: imgShift
        },
        {
          type: "elem",
          elem: inner2,
          shift: 0
        }
      ]
    }, options);
  } else {
    var classes = /cancel|phase/.test(label) ? ["svg-align"] : [];
    vlist = buildCommon.makeVList({
      positionType: "individualShift",
      children: [
        // Write the \cancel stroke on top of inner.
        {
          type: "elem",
          elem: inner2,
          shift: 0
        },
        {
          type: "elem",
          elem: img,
          shift: imgShift,
          wrapperClasses: classes
        }
      ]
    }, options);
  }
  if (/cancel/.test(label)) {
    vlist.height = inner2.height;
    vlist.depth = inner2.depth;
  }
  if (/cancel/.test(label) && !isSingleChar) {
    return buildCommon.makeSpan(["mord", "cancel-lap"], [vlist], options);
  } else {
    return buildCommon.makeSpan(["mord"], [vlist], options);
  }
};
var mathmlBuilder$6 = (group, options) => {
  var fboxsep = 0;
  var node = new mathMLTree.MathNode(group.label.indexOf("colorbox") > -1 ? "mpadded" : "menclose", [buildGroup2(group.body, options)]);
  switch (group.label) {
    case "\\cancel":
      node.setAttribute("notation", "updiagonalstrike");
      break;
    case "\\bcancel":
      node.setAttribute("notation", "downdiagonalstrike");
      break;
    case "\\phase":
      node.setAttribute("notation", "phasorangle");
      break;
    case "\\sout":
      node.setAttribute("notation", "horizontalstrike");
      break;
    case "\\fbox":
      node.setAttribute("notation", "box");
      break;
    case "\\angl":
      node.setAttribute("notation", "actuarial");
      break;
    case "\\fcolorbox":
    case "\\colorbox":
      fboxsep = options.fontMetrics().fboxsep * options.fontMetrics().ptPerEm;
      node.setAttribute("width", "+" + 2 * fboxsep + "pt");
      node.setAttribute("height", "+" + 2 * fboxsep + "pt");
      node.setAttribute("lspace", fboxsep + "pt");
      node.setAttribute("voffset", fboxsep + "pt");
      if (group.label === "\\fcolorbox") {
        var thk = Math.max(
          options.fontMetrics().fboxrule,
          // default
          options.minRuleThickness
          // user override
        );
        node.setAttribute("style", "border: " + thk + "em solid " + String(group.borderColor));
      }
      break;
    case "\\xcancel":
      node.setAttribute("notation", "updiagonalstrike downdiagonalstrike");
      break;
  }
  if (group.backgroundColor) {
    node.setAttribute("mathbackground", group.backgroundColor);
  }
  return node;
};
defineFunction({
  type: "enclose",
  names: ["\\colorbox"],
  props: {
    numArgs: 2,
    allowedInText: true,
    argTypes: ["color", "text"]
  },
  handler(_ref, args, optArgs) {
    var {
      parser,
      funcName
    } = _ref;
    var color = assertNodeType(args[0], "color-token").color;
    var body = args[1];
    return {
      type: "enclose",
      mode: parser.mode,
      label: funcName,
      backgroundColor: color,
      body
    };
  },
  htmlBuilder: htmlBuilder$7,
  mathmlBuilder: mathmlBuilder$6
});
defineFunction({
  type: "enclose",
  names: ["\\fcolorbox"],
  props: {
    numArgs: 3,
    allowedInText: true,
    argTypes: ["color", "color", "text"]
  },
  handler(_ref2, args, optArgs) {
    var {
      parser,
      funcName
    } = _ref2;
    var borderColor = assertNodeType(args[0], "color-token").color;
    var backgroundColor = assertNodeType(args[1], "color-token").color;
    var body = args[2];
    return {
      type: "enclose",
      mode: parser.mode,
      label: funcName,
      backgroundColor,
      borderColor,
      body
    };
  },
  htmlBuilder: htmlBuilder$7,
  mathmlBuilder: mathmlBuilder$6
});
defineFunction({
  type: "enclose",
  names: ["\\fbox"],
  props: {
    numArgs: 1,
    argTypes: ["hbox"],
    allowedInText: true
  },
  handler(_ref3, args) {
    var {
      parser
    } = _ref3;
    return {
      type: "enclose",
      mode: parser.mode,
      label: "\\fbox",
      body: args[0]
    };
  }
});
defineFunction({
  type: "enclose",
  names: ["\\cancel", "\\bcancel", "\\xcancel", "\\sout", "\\phase"],
  props: {
    numArgs: 1
  },
  handler(_ref4, args) {
    var {
      parser,
      funcName
    } = _ref4;
    var body = args[0];
    return {
      type: "enclose",
      mode: parser.mode,
      label: funcName,
      body
    };
  },
  htmlBuilder: htmlBuilder$7,
  mathmlBuilder: mathmlBuilder$6
});
defineFunction({
  type: "enclose",
  names: ["\\angl"],
  props: {
    numArgs: 1,
    argTypes: ["hbox"],
    allowedInText: false
  },
  handler(_ref5, args) {
    var {
      parser
    } = _ref5;
    return {
      type: "enclose",
      mode: parser.mode,
      label: "\\angl",
      body: args[0]
    };
  }
});
var _environments = {};
function defineEnvironment(_ref) {
  var {
    type,
    names,
    props,
    handler,
    htmlBuilder: htmlBuilder3,
    mathmlBuilder: mathmlBuilder3
  } = _ref;
  var data = {
    type,
    numArgs: props.numArgs || 0,
    allowedInText: false,
    numOptionalArgs: 0,
    handler
  };
  for (var i = 0; i < names.length; ++i) {
    _environments[names[i]] = data;
  }
  if (htmlBuilder3) {
    _htmlGroupBuilders[type] = htmlBuilder3;
  }
  if (mathmlBuilder3) {
    _mathmlGroupBuilders[type] = mathmlBuilder3;
  }
}
var _macros = {};
function defineMacro(name, body) {
  _macros[name] = body;
}
function getHLines(parser) {
  var hlineInfo = [];
  parser.consumeSpaces();
  var nxt = parser.fetch().text;
  if (nxt === "\\relax") {
    parser.consume();
    parser.consumeSpaces();
    nxt = parser.fetch().text;
  }
  while (nxt === "\\hline" || nxt === "\\hdashline") {
    parser.consume();
    hlineInfo.push(nxt === "\\hdashline");
    parser.consumeSpaces();
    nxt = parser.fetch().text;
  }
  return hlineInfo;
}
var validateAmsEnvironmentContext = (context) => {
  var settings = context.parser.settings;
  if (!settings.displayMode) {
    throw new ParseError("{" + context.envName + "} can be used only in display mode.");
  }
};
function getAutoTag(name) {
  if (name.indexOf("ed") === -1) {
    return name.indexOf("*") === -1;
  }
}
function parseArray(parser, _ref, style2) {
  var {
    hskipBeforeAndAfter,
    addJot,
    cols,
    arraystretch,
    colSeparationType,
    autoTag,
    singleRow,
    emptySingleRow,
    maxNumCols,
    leqno
  } = _ref;
  parser.gullet.beginGroup();
  if (!singleRow) {
    parser.gullet.macros.set("\\cr", "\\\\\\relax");
  }
  if (!arraystretch) {
    var stretch = parser.gullet.expandMacroAsText("\\arraystretch");
    if (stretch == null) {
      arraystretch = 1;
    } else {
      arraystretch = parseFloat(stretch);
      if (!arraystretch || arraystretch < 0) {
        throw new ParseError("Invalid \\arraystretch: " + stretch);
      }
    }
  }
  parser.gullet.beginGroup();
  var row = [];
  var body = [row];
  var rowGaps = [];
  var hLinesBeforeRow = [];
  var tags = autoTag != null ? [] : void 0;
  function beginRow() {
    if (autoTag) {
      parser.gullet.macros.set("\\@eqnsw", "1", true);
    }
  }
  function endRow() {
    if (tags) {
      if (parser.gullet.macros.get("\\df@tag")) {
        tags.push(parser.subparse([new Token("\\df@tag")]));
        parser.gullet.macros.set("\\df@tag", void 0, true);
      } else {
        tags.push(Boolean(autoTag) && parser.gullet.macros.get("\\@eqnsw") === "1");
      }
    }
  }
  beginRow();
  hLinesBeforeRow.push(getHLines(parser));
  while (true) {
    var cell = parser.parseExpression(false, singleRow ? "\\end" : "\\\\");
    parser.gullet.endGroup();
    parser.gullet.beginGroup();
    cell = {
      type: "ordgroup",
      mode: parser.mode,
      body: cell
    };
    if (style2) {
      cell = {
        type: "styling",
        mode: parser.mode,
        style: style2,
        body: [cell]
      };
    }
    row.push(cell);
    var next = parser.fetch().text;
    if (next === "&") {
      if (maxNumCols && row.length === maxNumCols) {
        if (singleRow || colSeparationType) {
          throw new ParseError("Too many tab characters: &", parser.nextToken);
        } else {
          parser.settings.reportNonstrict("textEnv", "Too few columns specified in the {array} column argument.");
        }
      }
      parser.consume();
    } else if (next === "\\end") {
      endRow();
      if (row.length === 1 && cell.type === "styling" && cell.body[0].body.length === 0 && (body.length > 1 || !emptySingleRow)) {
        body.pop();
      }
      if (hLinesBeforeRow.length < body.length + 1) {
        hLinesBeforeRow.push([]);
      }
      break;
    } else if (next === "\\\\") {
      parser.consume();
      var size = void 0;
      if (parser.gullet.future().text !== " ") {
        size = parser.parseSizeGroup(true);
      }
      rowGaps.push(size ? size.value : null);
      endRow();
      hLinesBeforeRow.push(getHLines(parser));
      row = [];
      body.push(row);
      beginRow();
    } else {
      throw new ParseError("Expected & or \\\\ or \\cr or \\end", parser.nextToken);
    }
  }
  parser.gullet.endGroup();
  parser.gullet.endGroup();
  return {
    type: "array",
    mode: parser.mode,
    addJot,
    arraystretch,
    body,
    cols,
    rowGaps,
    hskipBeforeAndAfter,
    hLinesBeforeRow,
    colSeparationType,
    tags,
    leqno
  };
}
function dCellStyle(envName) {
  if (envName.slice(0, 1) === "d") {
    return "display";
  } else {
    return "text";
  }
}
var htmlBuilder$6 = function htmlBuilder(group, options) {
  var r2;
  var c;
  var nr = group.body.length;
  var hLinesBeforeRow = group.hLinesBeforeRow;
  var nc = 0;
  var body = new Array(nr);
  var hlines = [];
  var ruleThickness = Math.max(
    // From LaTeX \showthe\arrayrulewidth. Equals 0.04 em.
    options.fontMetrics().arrayRuleWidth,
    options.minRuleThickness
    // User override.
  );
  var pt = 1 / options.fontMetrics().ptPerEm;
  var arraycolsep = 5 * pt;
  if (group.colSeparationType && group.colSeparationType === "small") {
    var localMultiplier = options.havingStyle(Style$1.SCRIPT).sizeMultiplier;
    arraycolsep = 0.2778 * (localMultiplier / options.sizeMultiplier);
  }
  var baselineskip = group.colSeparationType === "CD" ? calculateSize({
    number: 3,
    unit: "ex"
  }, options) : 12 * pt;
  var jot = 3 * pt;
  var arrayskip = group.arraystretch * baselineskip;
  var arstrutHeight = 0.7 * arrayskip;
  var arstrutDepth = 0.3 * arrayskip;
  var totalHeight = 0;
  function setHLinePos(hlinesInGap) {
    for (var i = 0; i < hlinesInGap.length; ++i) {
      if (i > 0) {
        totalHeight += 0.25;
      }
      hlines.push({
        pos: totalHeight,
        isDashed: hlinesInGap[i]
      });
    }
  }
  setHLinePos(hLinesBeforeRow[0]);
  for (r2 = 0; r2 < group.body.length; ++r2) {
    var inrow = group.body[r2];
    var height = arstrutHeight;
    var depth = arstrutDepth;
    if (nc < inrow.length) {
      nc = inrow.length;
    }
    var outrow = new Array(inrow.length);
    for (c = 0; c < inrow.length; ++c) {
      var elt = buildGroup$1(inrow[c], options);
      if (depth < elt.depth) {
        depth = elt.depth;
      }
      if (height < elt.height) {
        height = elt.height;
      }
      outrow[c] = elt;
    }
    var rowGap = group.rowGaps[r2];
    var gap = 0;
    if (rowGap) {
      gap = calculateSize(rowGap, options);
      if (gap > 0) {
        gap += arstrutDepth;
        if (depth < gap) {
          depth = gap;
        }
        gap = 0;
      }
    }
    if (group.addJot) {
      depth += jot;
    }
    outrow.height = height;
    outrow.depth = depth;
    totalHeight += height;
    outrow.pos = totalHeight;
    totalHeight += depth + gap;
    body[r2] = outrow;
    setHLinePos(hLinesBeforeRow[r2 + 1]);
  }
  var offset = totalHeight / 2 + options.fontMetrics().axisHeight;
  var colDescriptions = group.cols || [];
  var cols = [];
  var colSep;
  var colDescrNum;
  var tagSpans = [];
  if (group.tags && group.tags.some((tag2) => tag2)) {
    for (r2 = 0; r2 < nr; ++r2) {
      var rw = body[r2];
      var shift2 = rw.pos - offset;
      var tag = group.tags[r2];
      var tagSpan = void 0;
      if (tag === true) {
        tagSpan = buildCommon.makeSpan(["eqn-num"], [], options);
      } else if (tag === false) {
        tagSpan = buildCommon.makeSpan([], [], options);
      } else {
        tagSpan = buildCommon.makeSpan([], buildExpression$1(tag, options, true), options);
      }
      tagSpan.depth = rw.depth;
      tagSpan.height = rw.height;
      tagSpans.push({
        type: "elem",
        elem: tagSpan,
        shift: shift2
      });
    }
  }
  for (
    c = 0, colDescrNum = 0;
    // Continue while either there are more columns or more column
    // descriptions, so trailing separators don't get lost.
    c < nc || colDescrNum < colDescriptions.length;
    ++c, ++colDescrNum
  ) {
    var colDescr = colDescriptions[colDescrNum] || {};
    var firstSeparator = true;
    while (colDescr.type === "separator") {
      if (!firstSeparator) {
        colSep = buildCommon.makeSpan(["arraycolsep"], []);
        colSep.style.width = makeEm(options.fontMetrics().doubleRuleSep);
        cols.push(colSep);
      }
      if (colDescr.separator === "|" || colDescr.separator === ":") {
        var lineType = colDescr.separator === "|" ? "solid" : "dashed";
        var separator = buildCommon.makeSpan(["vertical-separator"], [], options);
        separator.style.height = makeEm(totalHeight);
        separator.style.borderRightWidth = makeEm(ruleThickness);
        separator.style.borderRightStyle = lineType;
        separator.style.margin = "0 " + makeEm(-ruleThickness / 2);
        var _shift = totalHeight - offset;
        if (_shift) {
          separator.style.verticalAlign = makeEm(-_shift);
        }
        cols.push(separator);
      } else {
        throw new ParseError("Invalid separator type: " + colDescr.separator);
      }
      colDescrNum++;
      colDescr = colDescriptions[colDescrNum] || {};
      firstSeparator = false;
    }
    if (c >= nc) {
      continue;
    }
    var sepwidth = void 0;
    if (c > 0 || group.hskipBeforeAndAfter) {
      sepwidth = utils.deflt(colDescr.pregap, arraycolsep);
      if (sepwidth !== 0) {
        colSep = buildCommon.makeSpan(["arraycolsep"], []);
        colSep.style.width = makeEm(sepwidth);
        cols.push(colSep);
      }
    }
    var col = [];
    for (r2 = 0; r2 < nr; ++r2) {
      var row = body[r2];
      var elem = row[c];
      if (!elem) {
        continue;
      }
      var _shift2 = row.pos - offset;
      elem.depth = row.depth;
      elem.height = row.height;
      col.push({
        type: "elem",
        elem,
        shift: _shift2
      });
    }
    col = buildCommon.makeVList({
      positionType: "individualShift",
      children: col
    }, options);
    col = buildCommon.makeSpan(["col-align-" + (colDescr.align || "c")], [col]);
    cols.push(col);
    if (c < nc - 1 || group.hskipBeforeAndAfter) {
      sepwidth = utils.deflt(colDescr.postgap, arraycolsep);
      if (sepwidth !== 0) {
        colSep = buildCommon.makeSpan(["arraycolsep"], []);
        colSep.style.width = makeEm(sepwidth);
        cols.push(colSep);
      }
    }
  }
  body = buildCommon.makeSpan(["mtable"], cols);
  if (hlines.length > 0) {
    var line = buildCommon.makeLineSpan("hline", options, ruleThickness);
    var dashes = buildCommon.makeLineSpan("hdashline", options, ruleThickness);
    var vListElems = [{
      type: "elem",
      elem: body,
      shift: 0
    }];
    while (hlines.length > 0) {
      var hline = hlines.pop();
      var lineShift = hline.pos - offset;
      if (hline.isDashed) {
        vListElems.push({
          type: "elem",
          elem: dashes,
          shift: lineShift
        });
      } else {
        vListElems.push({
          type: "elem",
          elem: line,
          shift: lineShift
        });
      }
    }
    body = buildCommon.makeVList({
      positionType: "individualShift",
      children: vListElems
    }, options);
  }
  if (tagSpans.length === 0) {
    return buildCommon.makeSpan(["mord"], [body], options);
  } else {
    var eqnNumCol = buildCommon.makeVList({
      positionType: "individualShift",
      children: tagSpans
    }, options);
    eqnNumCol = buildCommon.makeSpan(["tag"], [eqnNumCol], options);
    return buildCommon.makeFragment([body, eqnNumCol]);
  }
};
var alignMap = {
  c: "center ",
  l: "left ",
  r: "right "
};
var mathmlBuilder$5 = function mathmlBuilder(group, options) {
  var tbl = [];
  var glue = new mathMLTree.MathNode("mtd", [], ["mtr-glue"]);
  var tag = new mathMLTree.MathNode("mtd", [], ["mml-eqn-num"]);
  for (var i = 0; i < group.body.length; i++) {
    var rw = group.body[i];
    var row = [];
    for (var j = 0; j < rw.length; j++) {
      row.push(new mathMLTree.MathNode("mtd", [buildGroup2(rw[j], options)]));
    }
    if (group.tags && group.tags[i]) {
      row.unshift(glue);
      row.push(glue);
      if (group.leqno) {
        row.unshift(tag);
      } else {
        row.push(tag);
      }
    }
    tbl.push(new mathMLTree.MathNode("mtr", row));
  }
  var table = new mathMLTree.MathNode("mtable", tbl);
  var gap = group.arraystretch === 0.5 ? 0.1 : 0.16 + group.arraystretch - 1 + (group.addJot ? 0.09 : 0);
  table.setAttribute("rowspacing", makeEm(gap));
  var menclose = "";
  var align = "";
  if (group.cols && group.cols.length > 0) {
    var cols = group.cols;
    var columnLines = "";
    var prevTypeWasAlign = false;
    var iStart = 0;
    var iEnd = cols.length;
    if (cols[0].type === "separator") {
      menclose += "top ";
      iStart = 1;
    }
    if (cols[cols.length - 1].type === "separator") {
      menclose += "bottom ";
      iEnd -= 1;
    }
    for (var _i = iStart; _i < iEnd; _i++) {
      if (cols[_i].type === "align") {
        align += alignMap[cols[_i].align];
        if (prevTypeWasAlign) {
          columnLines += "none ";
        }
        prevTypeWasAlign = true;
      } else if (cols[_i].type === "separator") {
        if (prevTypeWasAlign) {
          columnLines += cols[_i].separator === "|" ? "solid " : "dashed ";
          prevTypeWasAlign = false;
        }
      }
    }
    table.setAttribute("columnalign", align.trim());
    if (/[sd]/.test(columnLines)) {
      table.setAttribute("columnlines", columnLines.trim());
    }
  }
  if (group.colSeparationType === "align") {
    var _cols = group.cols || [];
    var spacing2 = "";
    for (var _i2 = 1; _i2 < _cols.length; _i2++) {
      spacing2 += _i2 % 2 ? "0em " : "1em ";
    }
    table.setAttribute("columnspacing", spacing2.trim());
  } else if (group.colSeparationType === "alignat" || group.colSeparationType === "gather") {
    table.setAttribute("columnspacing", "0em");
  } else if (group.colSeparationType === "small") {
    table.setAttribute("columnspacing", "0.2778em");
  } else if (group.colSeparationType === "CD") {
    table.setAttribute("columnspacing", "0.5em");
  } else {
    table.setAttribute("columnspacing", "1em");
  }
  var rowLines = "";
  var hlines = group.hLinesBeforeRow;
  menclose += hlines[0].length > 0 ? "left " : "";
  menclose += hlines[hlines.length - 1].length > 0 ? "right " : "";
  for (var _i3 = 1; _i3 < hlines.length - 1; _i3++) {
    rowLines += hlines[_i3].length === 0 ? "none " : hlines[_i3][0] ? "dashed " : "solid ";
  }
  if (/[sd]/.test(rowLines)) {
    table.setAttribute("rowlines", rowLines.trim());
  }
  if (menclose !== "") {
    table = new mathMLTree.MathNode("menclose", [table]);
    table.setAttribute("notation", menclose.trim());
  }
  if (group.arraystretch && group.arraystretch < 1) {
    table = new mathMLTree.MathNode("mstyle", [table]);
    table.setAttribute("scriptlevel", "1");
  }
  return table;
};
var alignedHandler = function alignedHandler2(context, args) {
  if (context.envName.indexOf("ed") === -1) {
    validateAmsEnvironmentContext(context);
  }
  var cols = [];
  var separationType = context.envName.indexOf("at") > -1 ? "alignat" : "align";
  var isSplit = context.envName === "split";
  var res = parseArray(context.parser, {
    cols,
    addJot: true,
    autoTag: isSplit ? void 0 : getAutoTag(context.envName),
    emptySingleRow: true,
    colSeparationType: separationType,
    maxNumCols: isSplit ? 2 : void 0,
    leqno: context.parser.settings.leqno
  }, "display");
  var numMaths;
  var numCols = 0;
  var emptyGroup = {
    type: "ordgroup",
    mode: context.mode,
    body: []
  };
  if (args[0] && args[0].type === "ordgroup") {
    var arg0 = "";
    for (var i = 0; i < args[0].body.length; i++) {
      var textord2 = assertNodeType(args[0].body[i], "textord");
      arg0 += textord2.text;
    }
    numMaths = Number(arg0);
    numCols = numMaths * 2;
  }
  var isAligned = !numCols;
  res.body.forEach(function(row) {
    for (var _i4 = 1; _i4 < row.length; _i4 += 2) {
      var styling = assertNodeType(row[_i4], "styling");
      var ordgroup = assertNodeType(styling.body[0], "ordgroup");
      ordgroup.body.unshift(emptyGroup);
    }
    if (!isAligned) {
      var curMaths = row.length / 2;
      if (numMaths < curMaths) {
        throw new ParseError("Too many math in a row: " + ("expected " + numMaths + ", but got " + curMaths), row[0]);
      }
    } else if (numCols < row.length) {
      numCols = row.length;
    }
  });
  for (var _i5 = 0; _i5 < numCols; ++_i5) {
    var align = "r";
    var pregap = 0;
    if (_i5 % 2 === 1) {
      align = "l";
    } else if (_i5 > 0 && isAligned) {
      pregap = 1;
    }
    cols[_i5] = {
      type: "align",
      align,
      pregap,
      postgap: 0
    };
  }
  res.colSeparationType = isAligned ? "align" : "alignat";
  return res;
};
defineEnvironment({
  type: "array",
  names: ["array", "darray"],
  props: {
    numArgs: 1
  },
  handler(context, args) {
    var symNode = checkSymbolNodeType(args[0]);
    var colalign = symNode ? [args[0]] : assertNodeType(args[0], "ordgroup").body;
    var cols = colalign.map(function(nde) {
      var node = assertSymbolNodeType(nde);
      var ca = node.text;
      if ("lcr".indexOf(ca) !== -1) {
        return {
          type: "align",
          align: ca
        };
      } else if (ca === "|") {
        return {
          type: "separator",
          separator: "|"
        };
      } else if (ca === ":") {
        return {
          type: "separator",
          separator: ":"
        };
      }
      throw new ParseError("Unknown column alignment: " + ca, nde);
    });
    var res = {
      cols,
      hskipBeforeAndAfter: true,
      // \@preamble in lttab.dtx
      maxNumCols: cols.length
    };
    return parseArray(context.parser, res, dCellStyle(context.envName));
  },
  htmlBuilder: htmlBuilder$6,
  mathmlBuilder: mathmlBuilder$5
});
defineEnvironment({
  type: "array",
  names: ["matrix", "pmatrix", "bmatrix", "Bmatrix", "vmatrix", "Vmatrix", "matrix*", "pmatrix*", "bmatrix*", "Bmatrix*", "vmatrix*", "Vmatrix*"],
  props: {
    numArgs: 0
  },
  handler(context) {
    var delimiters2 = {
      "matrix": null,
      "pmatrix": ["(", ")"],
      "bmatrix": ["[", "]"],
      "Bmatrix": ["\\{", "\\}"],
      "vmatrix": ["|", "|"],
      "Vmatrix": ["\\Vert", "\\Vert"]
    }[context.envName.replace("*", "")];
    var colAlign = "c";
    var payload = {
      hskipBeforeAndAfter: false,
      cols: [{
        type: "align",
        align: colAlign
      }]
    };
    if (context.envName.charAt(context.envName.length - 1) === "*") {
      var parser = context.parser;
      parser.consumeSpaces();
      if (parser.fetch().text === "[") {
        parser.consume();
        parser.consumeSpaces();
        colAlign = parser.fetch().text;
        if ("lcr".indexOf(colAlign) === -1) {
          throw new ParseError("Expected l or c or r", parser.nextToken);
        }
        parser.consume();
        parser.consumeSpaces();
        parser.expect("]");
        parser.consume();
        payload.cols = [{
          type: "align",
          align: colAlign
        }];
      }
    }
    var res = parseArray(context.parser, payload, dCellStyle(context.envName));
    var numCols = Math.max(0, ...res.body.map((row) => row.length));
    res.cols = new Array(numCols).fill({
      type: "align",
      align: colAlign
    });
    return delimiters2 ? {
      type: "leftright",
      mode: context.mode,
      body: [res],
      left: delimiters2[0],
      right: delimiters2[1],
      rightColor: void 0
      // \right uninfluenced by \color in array
    } : res;
  },
  htmlBuilder: htmlBuilder$6,
  mathmlBuilder: mathmlBuilder$5
});
defineEnvironment({
  type: "array",
  names: ["smallmatrix"],
  props: {
    numArgs: 0
  },
  handler(context) {
    var payload = {
      arraystretch: 0.5
    };
    var res = parseArray(context.parser, payload, "script");
    res.colSeparationType = "small";
    return res;
  },
  htmlBuilder: htmlBuilder$6,
  mathmlBuilder: mathmlBuilder$5
});
defineEnvironment({
  type: "array",
  names: ["subarray"],
  props: {
    numArgs: 1
  },
  handler(context, args) {
    var symNode = checkSymbolNodeType(args[0]);
    var colalign = symNode ? [args[0]] : assertNodeType(args[0], "ordgroup").body;
    var cols = colalign.map(function(nde) {
      var node = assertSymbolNodeType(nde);
      var ca = node.text;
      if ("lc".indexOf(ca) !== -1) {
        return {
          type: "align",
          align: ca
        };
      }
      throw new ParseError("Unknown column alignment: " + ca, nde);
    });
    if (cols.length > 1) {
      throw new ParseError("{subarray} can contain only one column");
    }
    var res = {
      cols,
      hskipBeforeAndAfter: false,
      arraystretch: 0.5
    };
    res = parseArray(context.parser, res, "script");
    if (res.body.length > 0 && res.body[0].length > 1) {
      throw new ParseError("{subarray} can contain only one column");
    }
    return res;
  },
  htmlBuilder: htmlBuilder$6,
  mathmlBuilder: mathmlBuilder$5
});
defineEnvironment({
  type: "array",
  names: ["cases", "dcases", "rcases", "drcases"],
  props: {
    numArgs: 0
  },
  handler(context) {
    var payload = {
      arraystretch: 1.2,
      cols: [{
        type: "align",
        align: "l",
        pregap: 0,
        // TODO(kevinb) get the current style.
        // For now we use the metrics for TEXT style which is what we were
        // doing before.  Before attempting to get the current style we
        // should look at TeX's behavior especially for \over and matrices.
        postgap: 1
        /* 1em quad */
      }, {
        type: "align",
        align: "l",
        pregap: 0,
        postgap: 0
      }]
    };
    var res = parseArray(context.parser, payload, dCellStyle(context.envName));
    return {
      type: "leftright",
      mode: context.mode,
      body: [res],
      left: context.envName.indexOf("r") > -1 ? "." : "\\{",
      right: context.envName.indexOf("r") > -1 ? "\\}" : ".",
      rightColor: void 0
    };
  },
  htmlBuilder: htmlBuilder$6,
  mathmlBuilder: mathmlBuilder$5
});
defineEnvironment({
  type: "array",
  names: ["align", "align*", "aligned", "split"],
  props: {
    numArgs: 0
  },
  handler: alignedHandler,
  htmlBuilder: htmlBuilder$6,
  mathmlBuilder: mathmlBuilder$5
});
defineEnvironment({
  type: "array",
  names: ["gathered", "gather", "gather*"],
  props: {
    numArgs: 0
  },
  handler(context) {
    if (utils.contains(["gather", "gather*"], context.envName)) {
      validateAmsEnvironmentContext(context);
    }
    var res = {
      cols: [{
        type: "align",
        align: "c"
      }],
      addJot: true,
      colSeparationType: "gather",
      autoTag: getAutoTag(context.envName),
      emptySingleRow: true,
      leqno: context.parser.settings.leqno
    };
    return parseArray(context.parser, res, "display");
  },
  htmlBuilder: htmlBuilder$6,
  mathmlBuilder: mathmlBuilder$5
});
defineEnvironment({
  type: "array",
  names: ["alignat", "alignat*", "alignedat"],
  props: {
    numArgs: 1
  },
  handler: alignedHandler,
  htmlBuilder: htmlBuilder$6,
  mathmlBuilder: mathmlBuilder$5
});
defineEnvironment({
  type: "array",
  names: ["equation", "equation*"],
  props: {
    numArgs: 0
  },
  handler(context) {
    validateAmsEnvironmentContext(context);
    var res = {
      autoTag: getAutoTag(context.envName),
      emptySingleRow: true,
      singleRow: true,
      maxNumCols: 1,
      leqno: context.parser.settings.leqno
    };
    return parseArray(context.parser, res, "display");
  },
  htmlBuilder: htmlBuilder$6,
  mathmlBuilder: mathmlBuilder$5
});
defineEnvironment({
  type: "array",
  names: ["CD"],
  props: {
    numArgs: 0
  },
  handler(context) {
    validateAmsEnvironmentContext(context);
    return parseCD(context.parser);
  },
  htmlBuilder: htmlBuilder$6,
  mathmlBuilder: mathmlBuilder$5
});
defineMacro("\\nonumber", "\\gdef\\@eqnsw{0}");
defineMacro("\\notag", "\\nonumber");
defineFunction({
  type: "text",
  // Doesn't matter what this is.
  names: ["\\hline", "\\hdashline"],
  props: {
    numArgs: 0,
    allowedInText: true,
    allowedInMath: true
  },
  handler(context, args) {
    throw new ParseError(context.funcName + " valid only within array environment");
  }
});
var environments = _environments;
defineFunction({
  type: "environment",
  names: ["\\begin", "\\end"],
  props: {
    numArgs: 1,
    argTypes: ["text"]
  },
  handler(_ref, args) {
    var {
      parser,
      funcName
    } = _ref;
    var nameGroup = args[0];
    if (nameGroup.type !== "ordgroup") {
      throw new ParseError("Invalid environment name", nameGroup);
    }
    var envName = "";
    for (var i = 0; i < nameGroup.body.length; ++i) {
      envName += assertNodeType(nameGroup.body[i], "textord").text;
    }
    if (funcName === "\\begin") {
      if (!environments.hasOwnProperty(envName)) {
        throw new ParseError("No such environment: " + envName, nameGroup);
      }
      var env = environments[envName];
      var {
        args: _args,
        optArgs
      } = parser.parseArguments("\\begin{" + envName + "}", env);
      var context = {
        mode: parser.mode,
        envName,
        parser
      };
      var result = env.handler(context, _args, optArgs);
      parser.expect("\\end", false);
      var endNameToken = parser.nextToken;
      var end = assertNodeType(parser.parseFunction(), "environment");
      if (end.name !== envName) {
        throw new ParseError("Mismatch: \\begin{" + envName + "} matched by \\end{" + end.name + "}", endNameToken);
      }
      return result;
    }
    return {
      type: "environment",
      mode: parser.mode,
      name: envName,
      nameGroup
    };
  }
});
var htmlBuilder$5 = (group, options) => {
  var font = group.font;
  var newOptions = options.withFont(font);
  return buildGroup$1(group.body, newOptions);
};
var mathmlBuilder$4 = (group, options) => {
  var font = group.font;
  var newOptions = options.withFont(font);
  return buildGroup2(group.body, newOptions);
};
var fontAliases = {
  "\\Bbb": "\\mathbb",
  "\\bold": "\\mathbf",
  "\\frak": "\\mathfrak",
  "\\bm": "\\boldsymbol"
};
defineFunction({
  type: "font",
  names: [
    // styles, except \boldsymbol defined below
    "\\mathrm",
    "\\mathit",
    "\\mathbf",
    "\\mathnormal",
    "\\mathsfit",
    // families
    "\\mathbb",
    "\\mathcal",
    "\\mathfrak",
    "\\mathscr",
    "\\mathsf",
    "\\mathtt",
    // aliases, except \bm defined below
    "\\Bbb",
    "\\bold",
    "\\frak"
  ],
  props: {
    numArgs: 1,
    allowedInArgument: true
  },
  handler: (_ref, args) => {
    var {
      parser,
      funcName
    } = _ref;
    var body = normalizeArgument(args[0]);
    var func = funcName;
    if (func in fontAliases) {
      func = fontAliases[func];
    }
    return {
      type: "font",
      mode: parser.mode,
      font: func.slice(1),
      body
    };
  },
  htmlBuilder: htmlBuilder$5,
  mathmlBuilder: mathmlBuilder$4
});
defineFunction({
  type: "mclass",
  names: ["\\boldsymbol", "\\bm"],
  props: {
    numArgs: 1
  },
  handler: (_ref2, args) => {
    var {
      parser
    } = _ref2;
    var body = args[0];
    var isCharacterBox3 = utils.isCharacterBox(body);
    return {
      type: "mclass",
      mode: parser.mode,
      mclass: binrelClass(body),
      body: [{
        type: "font",
        mode: parser.mode,
        font: "boldsymbol",
        body
      }],
      isCharacterBox: isCharacterBox3
    };
  }
});
defineFunction({
  type: "font",
  names: ["\\rm", "\\sf", "\\tt", "\\bf", "\\it", "\\cal"],
  props: {
    numArgs: 0,
    allowedInText: true
  },
  handler: (_ref3, args) => {
    var {
      parser,
      funcName,
      breakOnTokenText
    } = _ref3;
    var {
      mode
    } = parser;
    var body = parser.parseExpression(true, breakOnTokenText);
    var style2 = "math" + funcName.slice(1);
    return {
      type: "font",
      mode,
      font: style2,
      body: {
        type: "ordgroup",
        mode: parser.mode,
        body
      }
    };
  },
  htmlBuilder: htmlBuilder$5,
  mathmlBuilder: mathmlBuilder$4
});
var adjustStyle = (size, originalStyle) => {
  var style2 = originalStyle;
  if (size === "display") {
    style2 = style2.id >= Style$1.SCRIPT.id ? style2.text() : Style$1.DISPLAY;
  } else if (size === "text" && style2.size === Style$1.DISPLAY.size) {
    style2 = Style$1.TEXT;
  } else if (size === "script") {
    style2 = Style$1.SCRIPT;
  } else if (size === "scriptscript") {
    style2 = Style$1.SCRIPTSCRIPT;
  }
  return style2;
};
var htmlBuilder$4 = (group, options) => {
  var style2 = adjustStyle(group.size, options.style);
  var nstyle = style2.fracNum();
  var dstyle = style2.fracDen();
  var newOptions;
  newOptions = options.havingStyle(nstyle);
  var numerm = buildGroup$1(group.numer, newOptions, options);
  if (group.continued) {
    var hStrut = 8.5 / options.fontMetrics().ptPerEm;
    var dStrut = 3.5 / options.fontMetrics().ptPerEm;
    numerm.height = numerm.height < hStrut ? hStrut : numerm.height;
    numerm.depth = numerm.depth < dStrut ? dStrut : numerm.depth;
  }
  newOptions = options.havingStyle(dstyle);
  var denomm = buildGroup$1(group.denom, newOptions, options);
  var rule;
  var ruleWidth;
  var ruleSpacing;
  if (group.hasBarLine) {
    if (group.barSize) {
      ruleWidth = calculateSize(group.barSize, options);
      rule = buildCommon.makeLineSpan("frac-line", options, ruleWidth);
    } else {
      rule = buildCommon.makeLineSpan("frac-line", options);
    }
    ruleWidth = rule.height;
    ruleSpacing = rule.height;
  } else {
    rule = null;
    ruleWidth = 0;
    ruleSpacing = options.fontMetrics().defaultRuleThickness;
  }
  var numShift;
  var clearance;
  var denomShift;
  if (style2.size === Style$1.DISPLAY.size || group.size === "display") {
    numShift = options.fontMetrics().num1;
    if (ruleWidth > 0) {
      clearance = 3 * ruleSpacing;
    } else {
      clearance = 7 * ruleSpacing;
    }
    denomShift = options.fontMetrics().denom1;
  } else {
    if (ruleWidth > 0) {
      numShift = options.fontMetrics().num2;
      clearance = ruleSpacing;
    } else {
      numShift = options.fontMetrics().num3;
      clearance = 3 * ruleSpacing;
    }
    denomShift = options.fontMetrics().denom2;
  }
  var frac2;
  if (!rule) {
    var candidateClearance = numShift - numerm.depth - (denomm.height - denomShift);
    if (candidateClearance < clearance) {
      numShift += 0.5 * (clearance - candidateClearance);
      denomShift += 0.5 * (clearance - candidateClearance);
    }
    frac2 = buildCommon.makeVList({
      positionType: "individualShift",
      children: [{
        type: "elem",
        elem: denomm,
        shift: denomShift
      }, {
        type: "elem",
        elem: numerm,
        shift: -numShift
      }]
    }, options);
  } else {
    var axisHeight = options.fontMetrics().axisHeight;
    if (numShift - numerm.depth - (axisHeight + 0.5 * ruleWidth) < clearance) {
      numShift += clearance - (numShift - numerm.depth - (axisHeight + 0.5 * ruleWidth));
    }
    if (axisHeight - 0.5 * ruleWidth - (denomm.height - denomShift) < clearance) {
      denomShift += clearance - (axisHeight - 0.5 * ruleWidth - (denomm.height - denomShift));
    }
    var midShift = -(axisHeight - 0.5 * ruleWidth);
    frac2 = buildCommon.makeVList({
      positionType: "individualShift",
      children: [{
        type: "elem",
        elem: denomm,
        shift: denomShift
      }, {
        type: "elem",
        elem: rule,
        shift: midShift
      }, {
        type: "elem",
        elem: numerm,
        shift: -numShift
      }]
    }, options);
  }
  newOptions = options.havingStyle(style2);
  frac2.height *= newOptions.sizeMultiplier / options.sizeMultiplier;
  frac2.depth *= newOptions.sizeMultiplier / options.sizeMultiplier;
  var delimSize;
  if (style2.size === Style$1.DISPLAY.size) {
    delimSize = options.fontMetrics().delim1;
  } else if (style2.size === Style$1.SCRIPTSCRIPT.size) {
    delimSize = options.havingStyle(Style$1.SCRIPT).fontMetrics().delim2;
  } else {
    delimSize = options.fontMetrics().delim2;
  }
  var leftDelim;
  var rightDelim;
  if (group.leftDelim == null) {
    leftDelim = makeNullDelimiter(options, ["mopen"]);
  } else {
    leftDelim = delimiter.customSizedDelim(group.leftDelim, delimSize, true, options.havingStyle(style2), group.mode, ["mopen"]);
  }
  if (group.continued) {
    rightDelim = buildCommon.makeSpan([]);
  } else if (group.rightDelim == null) {
    rightDelim = makeNullDelimiter(options, ["mclose"]);
  } else {
    rightDelim = delimiter.customSizedDelim(group.rightDelim, delimSize, true, options.havingStyle(style2), group.mode, ["mclose"]);
  }
  return buildCommon.makeSpan(["mord"].concat(newOptions.sizingClasses(options)), [leftDelim, buildCommon.makeSpan(["mfrac"], [frac2]), rightDelim], options);
};
var mathmlBuilder$3 = (group, options) => {
  var node = new mathMLTree.MathNode("mfrac", [buildGroup2(group.numer, options), buildGroup2(group.denom, options)]);
  if (!group.hasBarLine) {
    node.setAttribute("linethickness", "0px");
  } else if (group.barSize) {
    var ruleWidth = calculateSize(group.barSize, options);
    node.setAttribute("linethickness", makeEm(ruleWidth));
  }
  var style2 = adjustStyle(group.size, options.style);
  if (style2.size !== options.style.size) {
    node = new mathMLTree.MathNode("mstyle", [node]);
    var isDisplay = style2.size === Style$1.DISPLAY.size ? "true" : "false";
    node.setAttribute("displaystyle", isDisplay);
    node.setAttribute("scriptlevel", "0");
  }
  if (group.leftDelim != null || group.rightDelim != null) {
    var withDelims = [];
    if (group.leftDelim != null) {
      var leftOp = new mathMLTree.MathNode("mo", [new mathMLTree.TextNode(group.leftDelim.replace("\\", ""))]);
      leftOp.setAttribute("fence", "true");
      withDelims.push(leftOp);
    }
    withDelims.push(node);
    if (group.rightDelim != null) {
      var rightOp = new mathMLTree.MathNode("mo", [new mathMLTree.TextNode(group.rightDelim.replace("\\", ""))]);
      rightOp.setAttribute("fence", "true");
      withDelims.push(rightOp);
    }
    return makeRow(withDelims);
  }
  return node;
};
defineFunction({
  type: "genfrac",
  names: [
    "\\dfrac",
    "\\frac",
    "\\tfrac",
    "\\dbinom",
    "\\binom",
    "\\tbinom",
    "\\\\atopfrac",
    // can’t be entered directly
    "\\\\bracefrac",
    "\\\\brackfrac"
    // ditto
  ],
  props: {
    numArgs: 2,
    allowedInArgument: true
  },
  handler: (_ref, args) => {
    var {
      parser,
      funcName
    } = _ref;
    var numer = args[0];
    var denom = args[1];
    var hasBarLine;
    var leftDelim = null;
    var rightDelim = null;
    var size = "auto";
    switch (funcName) {
      case "\\dfrac":
      case "\\frac":
      case "\\tfrac":
        hasBarLine = true;
        break;
      case "\\\\atopfrac":
        hasBarLine = false;
        break;
      case "\\dbinom":
      case "\\binom":
      case "\\tbinom":
        hasBarLine = false;
        leftDelim = "(";
        rightDelim = ")";
        break;
      case "\\\\bracefrac":
        hasBarLine = false;
        leftDelim = "\\{";
        rightDelim = "\\}";
        break;
      case "\\\\brackfrac":
        hasBarLine = false;
        leftDelim = "[";
        rightDelim = "]";
        break;
      default:
        throw new Error("Unrecognized genfrac command");
    }
    switch (funcName) {
      case "\\dfrac":
      case "\\dbinom":
        size = "display";
        break;
      case "\\tfrac":
      case "\\tbinom":
        size = "text";
        break;
    }
    return {
      type: "genfrac",
      mode: parser.mode,
      continued: false,
      numer,
      denom,
      hasBarLine,
      leftDelim,
      rightDelim,
      size,
      barSize: null
    };
  },
  htmlBuilder: htmlBuilder$4,
  mathmlBuilder: mathmlBuilder$3
});
defineFunction({
  type: "genfrac",
  names: ["\\cfrac"],
  props: {
    numArgs: 2
  },
  handler: (_ref2, args) => {
    var {
      parser,
      funcName
    } = _ref2;
    var numer = args[0];
    var denom = args[1];
    return {
      type: "genfrac",
      mode: parser.mode,
      continued: true,
      numer,
      denom,
      hasBarLine: true,
      leftDelim: null,
      rightDelim: null,
      size: "display",
      barSize: null
    };
  }
});
defineFunction({
  type: "infix",
  names: ["\\over", "\\choose", "\\atop", "\\brace", "\\brack"],
  props: {
    numArgs: 0,
    infix: true
  },
  handler(_ref3) {
    var {
      parser,
      funcName,
      token
    } = _ref3;
    var replaceWith;
    switch (funcName) {
      case "\\over":
        replaceWith = "\\frac";
        break;
      case "\\choose":
        replaceWith = "\\binom";
        break;
      case "\\atop":
        replaceWith = "\\\\atopfrac";
        break;
      case "\\brace":
        replaceWith = "\\\\bracefrac";
        break;
      case "\\brack":
        replaceWith = "\\\\brackfrac";
        break;
      default:
        throw new Error("Unrecognized infix genfrac command");
    }
    return {
      type: "infix",
      mode: parser.mode,
      replaceWith,
      token
    };
  }
});
var stylArray = ["display", "text", "script", "scriptscript"];
var delimFromValue = function delimFromValue2(delimString) {
  var delim = null;
  if (delimString.length > 0) {
    delim = delimString;
    delim = delim === "." ? null : delim;
  }
  return delim;
};
defineFunction({
  type: "genfrac",
  names: ["\\genfrac"],
  props: {
    numArgs: 6,
    allowedInArgument: true,
    argTypes: ["math", "math", "size", "text", "math", "math"]
  },
  handler(_ref4, args) {
    var {
      parser
    } = _ref4;
    var numer = args[4];
    var denom = args[5];
    var leftNode = normalizeArgument(args[0]);
    var leftDelim = leftNode.type === "atom" && leftNode.family === "open" ? delimFromValue(leftNode.text) : null;
    var rightNode = normalizeArgument(args[1]);
    var rightDelim = rightNode.type === "atom" && rightNode.family === "close" ? delimFromValue(rightNode.text) : null;
    var barNode = assertNodeType(args[2], "size");
    var hasBarLine;
    var barSize = null;
    if (barNode.isBlank) {
      hasBarLine = true;
    } else {
      barSize = barNode.value;
      hasBarLine = barSize.number > 0;
    }
    var size = "auto";
    var styl = args[3];
    if (styl.type === "ordgroup") {
      if (styl.body.length > 0) {
        var textOrd = assertNodeType(styl.body[0], "textord");
        size = stylArray[Number(textOrd.text)];
      }
    } else {
      styl = assertNodeType(styl, "textord");
      size = stylArray[Number(styl.text)];
    }
    return {
      type: "genfrac",
      mode: parser.mode,
      numer,
      denom,
      continued: false,
      hasBarLine,
      barSize,
      leftDelim,
      rightDelim,
      size
    };
  },
  htmlBuilder: htmlBuilder$4,
  mathmlBuilder: mathmlBuilder$3
});
defineFunction({
  type: "infix",
  names: ["\\above"],
  props: {
    numArgs: 1,
    argTypes: ["size"],
    infix: true
  },
  handler(_ref5, args) {
    var {
      parser,
      funcName,
      token
    } = _ref5;
    return {
      type: "infix",
      mode: parser.mode,
      replaceWith: "\\\\abovefrac",
      size: assertNodeType(args[0], "size").value,
      token
    };
  }
});
defineFunction({
  type: "genfrac",
  names: ["\\\\abovefrac"],
  props: {
    numArgs: 3,
    argTypes: ["math", "size", "math"]
  },
  handler: (_ref6, args) => {
    var {
      parser,
      funcName
    } = _ref6;
    var numer = args[0];
    var barSize = assert(assertNodeType(args[1], "infix").size);
    var denom = args[2];
    var hasBarLine = barSize.number > 0;
    return {
      type: "genfrac",
      mode: parser.mode,
      numer,
      denom,
      continued: false,
      hasBarLine,
      barSize,
      leftDelim: null,
      rightDelim: null,
      size: "auto"
    };
  },
  htmlBuilder: htmlBuilder$4,
  mathmlBuilder: mathmlBuilder$3
});
var htmlBuilder$3 = (grp, options) => {
  var style2 = options.style;
  var supSubGroup;
  var group;
  if (grp.type === "supsub") {
    supSubGroup = grp.sup ? buildGroup$1(grp.sup, options.havingStyle(style2.sup()), options) : buildGroup$1(grp.sub, options.havingStyle(style2.sub()), options);
    group = assertNodeType(grp.base, "horizBrace");
  } else {
    group = assertNodeType(grp, "horizBrace");
  }
  var body = buildGroup$1(group.base, options.havingBaseStyle(Style$1.DISPLAY));
  var braceBody = stretchy.svgSpan(group, options);
  var vlist;
  if (group.isOver) {
    vlist = buildCommon.makeVList({
      positionType: "firstBaseline",
      children: [{
        type: "elem",
        elem: body
      }, {
        type: "kern",
        size: 0.1
      }, {
        type: "elem",
        elem: braceBody
      }]
    }, options);
    vlist.children[0].children[0].children[1].classes.push("svg-align");
  } else {
    vlist = buildCommon.makeVList({
      positionType: "bottom",
      positionData: body.depth + 0.1 + braceBody.height,
      children: [{
        type: "elem",
        elem: braceBody
      }, {
        type: "kern",
        size: 0.1
      }, {
        type: "elem",
        elem: body
      }]
    }, options);
    vlist.children[0].children[0].children[0].classes.push("svg-align");
  }
  if (supSubGroup) {
    var vSpan = buildCommon.makeSpan(["mord", group.isOver ? "mover" : "munder"], [vlist], options);
    if (group.isOver) {
      vlist = buildCommon.makeVList({
        positionType: "firstBaseline",
        children: [{
          type: "elem",
          elem: vSpan
        }, {
          type: "kern",
          size: 0.2
        }, {
          type: "elem",
          elem: supSubGroup
        }]
      }, options);
    } else {
      vlist = buildCommon.makeVList({
        positionType: "bottom",
        positionData: vSpan.depth + 0.2 + supSubGroup.height + supSubGroup.depth,
        children: [{
          type: "elem",
          elem: supSubGroup
        }, {
          type: "kern",
          size: 0.2
        }, {
          type: "elem",
          elem: vSpan
        }]
      }, options);
    }
  }
  return buildCommon.makeSpan(["mord", group.isOver ? "mover" : "munder"], [vlist], options);
};
var mathmlBuilder$2 = (group, options) => {
  var accentNode = stretchy.mathMLnode(group.label);
  return new mathMLTree.MathNode(group.isOver ? "mover" : "munder", [buildGroup2(group.base, options), accentNode]);
};
defineFunction({
  type: "horizBrace",
  names: ["\\overbrace", "\\underbrace"],
  props: {
    numArgs: 1
  },
  handler(_ref, args) {
    var {
      parser,
      funcName
    } = _ref;
    return {
      type: "horizBrace",
      mode: parser.mode,
      label: funcName,
      isOver: /^\\over/.test(funcName),
      base: args[0]
    };
  },
  htmlBuilder: htmlBuilder$3,
  mathmlBuilder: mathmlBuilder$2
});
defineFunction({
  type: "href",
  names: ["\\href"],
  props: {
    numArgs: 2,
    argTypes: ["url", "original"],
    allowedInText: true
  },
  handler: (_ref, args) => {
    var {
      parser
    } = _ref;
    var body = args[1];
    var href = assertNodeType(args[0], "url").url;
    if (!parser.settings.isTrusted({
      command: "\\href",
      url: href
    })) {
      return parser.formatUnsupportedCmd("\\href");
    }
    return {
      type: "href",
      mode: parser.mode,
      href,
      body: ordargument(body)
    };
  },
  htmlBuilder: (group, options) => {
    var elements = buildExpression$1(group.body, options, false);
    return buildCommon.makeAnchor(group.href, [], elements, options);
  },
  mathmlBuilder: (group, options) => {
    var math2 = buildExpressionRow(group.body, options);
    if (!(math2 instanceof MathNode)) {
      math2 = new MathNode("mrow", [math2]);
    }
    math2.setAttribute("href", group.href);
    return math2;
  }
});
defineFunction({
  type: "href",
  names: ["\\url"],
  props: {
    numArgs: 1,
    argTypes: ["url"],
    allowedInText: true
  },
  handler: (_ref2, args) => {
    var {
      parser
    } = _ref2;
    var href = assertNodeType(args[0], "url").url;
    if (!parser.settings.isTrusted({
      command: "\\url",
      url: href
    })) {
      return parser.formatUnsupportedCmd("\\url");
    }
    var chars = [];
    for (var i = 0; i < href.length; i++) {
      var c = href[i];
      if (c === "~") {
        c = "\\textasciitilde";
      }
      chars.push({
        type: "textord",
        mode: "text",
        text: c
      });
    }
    var body = {
      type: "text",
      mode: parser.mode,
      font: "\\texttt",
      body: chars
    };
    return {
      type: "href",
      mode: parser.mode,
      href,
      body: ordargument(body)
    };
  }
});
defineFunction({
  type: "hbox",
  names: ["\\hbox"],
  props: {
    numArgs: 1,
    argTypes: ["text"],
    allowedInText: true,
    primitive: true
  },
  handler(_ref, args) {
    var {
      parser
    } = _ref;
    return {
      type: "hbox",
      mode: parser.mode,
      body: ordargument(args[0])
    };
  },
  htmlBuilder(group, options) {
    var elements = buildExpression$1(group.body, options, false);
    return buildCommon.makeFragment(elements);
  },
  mathmlBuilder(group, options) {
    return new mathMLTree.MathNode("mrow", buildExpression2(group.body, options));
  }
});
defineFunction({
  type: "html",
  names: ["\\htmlClass", "\\htmlId", "\\htmlStyle", "\\htmlData"],
  props: {
    numArgs: 2,
    argTypes: ["raw", "original"],
    allowedInText: true
  },
  handler: (_ref, args) => {
    var {
      parser,
      funcName,
      token
    } = _ref;
    var value = assertNodeType(args[0], "raw").string;
    var body = args[1];
    if (parser.settings.strict) {
      parser.settings.reportNonstrict("htmlExtension", "HTML extension is disabled on strict mode");
    }
    var trustContext;
    var attributes = {};
    switch (funcName) {
      case "\\htmlClass":
        attributes.class = value;
        trustContext = {
          command: "\\htmlClass",
          class: value
        };
        break;
      case "\\htmlId":
        attributes.id = value;
        trustContext = {
          command: "\\htmlId",
          id: value
        };
        break;
      case "\\htmlStyle":
        attributes.style = value;
        trustContext = {
          command: "\\htmlStyle",
          style: value
        };
        break;
      case "\\htmlData": {
        var data = value.split(",");
        for (var i = 0; i < data.length; i++) {
          var keyVal = data[i].split("=");
          if (keyVal.length !== 2) {
            throw new ParseError("Error parsing key-value for \\htmlData");
          }
          attributes["data-" + keyVal[0].trim()] = keyVal[1].trim();
        }
        trustContext = {
          command: "\\htmlData",
          attributes
        };
        break;
      }
      default:
        throw new Error("Unrecognized html command");
    }
    if (!parser.settings.isTrusted(trustContext)) {
      return parser.formatUnsupportedCmd(funcName);
    }
    return {
      type: "html",
      mode: parser.mode,
      attributes,
      body: ordargument(body)
    };
  },
  htmlBuilder: (group, options) => {
    var elements = buildExpression$1(group.body, options, false);
    var classes = ["enclosing"];
    if (group.attributes.class) {
      classes.push(...group.attributes.class.trim().split(/\s+/));
    }
    var span = buildCommon.makeSpan(classes, elements, options);
    for (var attr in group.attributes) {
      if (attr !== "class" && group.attributes.hasOwnProperty(attr)) {
        span.setAttribute(attr, group.attributes[attr]);
      }
    }
    return span;
  },
  mathmlBuilder: (group, options) => {
    return buildExpressionRow(group.body, options);
  }
});
defineFunction({
  type: "htmlmathml",
  names: ["\\html@mathml"],
  props: {
    numArgs: 2,
    allowedInText: true
  },
  handler: (_ref, args) => {
    var {
      parser
    } = _ref;
    return {
      type: "htmlmathml",
      mode: parser.mode,
      html: ordargument(args[0]),
      mathml: ordargument(args[1])
    };
  },
  htmlBuilder: (group, options) => {
    var elements = buildExpression$1(group.html, options, false);
    return buildCommon.makeFragment(elements);
  },
  mathmlBuilder: (group, options) => {
    return buildExpressionRow(group.mathml, options);
  }
});
var sizeData = function sizeData2(str) {
  if (/^[-+]? *(\d+(\.\d*)?|\.\d+)$/.test(str)) {
    return {
      number: +str,
      unit: "bp"
    };
  } else {
    var match = /([-+]?) *(\d+(?:\.\d*)?|\.\d+) *([a-z]{2})/.exec(str);
    if (!match) {
      throw new ParseError("Invalid size: '" + str + "' in \\includegraphics");
    }
    var data = {
      number: +(match[1] + match[2]),
      // sign + magnitude, cast to number
      unit: match[3]
    };
    if (!validUnit(data)) {
      throw new ParseError("Invalid unit: '" + data.unit + "' in \\includegraphics.");
    }
    return data;
  }
};
defineFunction({
  type: "includegraphics",
  names: ["\\includegraphics"],
  props: {
    numArgs: 1,
    numOptionalArgs: 1,
    argTypes: ["raw", "url"],
    allowedInText: false
  },
  handler: (_ref, args, optArgs) => {
    var {
      parser
    } = _ref;
    var width = {
      number: 0,
      unit: "em"
    };
    var height = {
      number: 0.9,
      unit: "em"
    };
    var totalheight = {
      number: 0,
      unit: "em"
    };
    var alt = "";
    if (optArgs[0]) {
      var attributeStr = assertNodeType(optArgs[0], "raw").string;
      var attributes = attributeStr.split(",");
      for (var i = 0; i < attributes.length; i++) {
        var keyVal = attributes[i].split("=");
        if (keyVal.length === 2) {
          var str = keyVal[1].trim();
          switch (keyVal[0].trim()) {
            case "alt":
              alt = str;
              break;
            case "width":
              width = sizeData(str);
              break;
            case "height":
              height = sizeData(str);
              break;
            case "totalheight":
              totalheight = sizeData(str);
              break;
            default:
              throw new ParseError("Invalid key: '" + keyVal[0] + "' in \\includegraphics.");
          }
        }
      }
    }
    var src = assertNodeType(args[0], "url").url;
    if (alt === "") {
      alt = src;
      alt = alt.replace(/^.*[\\/]/, "");
      alt = alt.substring(0, alt.lastIndexOf("."));
    }
    if (!parser.settings.isTrusted({
      command: "\\includegraphics",
      url: src
    })) {
      return parser.formatUnsupportedCmd("\\includegraphics");
    }
    return {
      type: "includegraphics",
      mode: parser.mode,
      alt,
      width,
      height,
      totalheight,
      src
    };
  },
  htmlBuilder: (group, options) => {
    var height = calculateSize(group.height, options);
    var depth = 0;
    if (group.totalheight.number > 0) {
      depth = calculateSize(group.totalheight, options) - height;
    }
    var width = 0;
    if (group.width.number > 0) {
      width = calculateSize(group.width, options);
    }
    var style2 = {
      height: makeEm(height + depth)
    };
    if (width > 0) {
      style2.width = makeEm(width);
    }
    if (depth > 0) {
      style2.verticalAlign = makeEm(-depth);
    }
    var node = new Img(group.src, group.alt, style2);
    node.height = height;
    node.depth = depth;
    return node;
  },
  mathmlBuilder: (group, options) => {
    var node = new mathMLTree.MathNode("mglyph", []);
    node.setAttribute("alt", group.alt);
    var height = calculateSize(group.height, options);
    var depth = 0;
    if (group.totalheight.number > 0) {
      depth = calculateSize(group.totalheight, options) - height;
      node.setAttribute("valign", makeEm(-depth));
    }
    node.setAttribute("height", makeEm(height + depth));
    if (group.width.number > 0) {
      var width = calculateSize(group.width, options);
      node.setAttribute("width", makeEm(width));
    }
    node.setAttribute("src", group.src);
    return node;
  }
});
defineFunction({
  type: "kern",
  names: ["\\kern", "\\mkern", "\\hskip", "\\mskip"],
  props: {
    numArgs: 1,
    argTypes: ["size"],
    primitive: true,
    allowedInText: true
  },
  handler(_ref, args) {
    var {
      parser,
      funcName
    } = _ref;
    var size = assertNodeType(args[0], "size");
    if (parser.settings.strict) {
      var mathFunction = funcName[1] === "m";
      var muUnit = size.value.unit === "mu";
      if (mathFunction) {
        if (!muUnit) {
          parser.settings.reportNonstrict("mathVsTextUnits", "LaTeX's " + funcName + " supports only mu units, " + ("not " + size.value.unit + " units"));
        }
        if (parser.mode !== "math") {
          parser.settings.reportNonstrict("mathVsTextUnits", "LaTeX's " + funcName + " works only in math mode");
        }
      } else {
        if (muUnit) {
          parser.settings.reportNonstrict("mathVsTextUnits", "LaTeX's " + funcName + " doesn't support mu units");
        }
      }
    }
    return {
      type: "kern",
      mode: parser.mode,
      dimension: size.value
    };
  },
  htmlBuilder(group, options) {
    return buildCommon.makeGlue(group.dimension, options);
  },
  mathmlBuilder(group, options) {
    var dimension = calculateSize(group.dimension, options);
    return new mathMLTree.SpaceNode(dimension);
  }
});
defineFunction({
  type: "lap",
  names: ["\\mathllap", "\\mathrlap", "\\mathclap"],
  props: {
    numArgs: 1,
    allowedInText: true
  },
  handler: (_ref, args) => {
    var {
      parser,
      funcName
    } = _ref;
    var body = args[0];
    return {
      type: "lap",
      mode: parser.mode,
      alignment: funcName.slice(5),
      body
    };
  },
  htmlBuilder: (group, options) => {
    var inner2;
    if (group.alignment === "clap") {
      inner2 = buildCommon.makeSpan([], [buildGroup$1(group.body, options)]);
      inner2 = buildCommon.makeSpan(["inner"], [inner2], options);
    } else {
      inner2 = buildCommon.makeSpan(["inner"], [buildGroup$1(group.body, options)]);
    }
    var fix = buildCommon.makeSpan(["fix"], []);
    var node = buildCommon.makeSpan([group.alignment], [inner2, fix], options);
    var strut = buildCommon.makeSpan(["strut"]);
    strut.style.height = makeEm(node.height + node.depth);
    if (node.depth) {
      strut.style.verticalAlign = makeEm(-node.depth);
    }
    node.children.unshift(strut);
    node = buildCommon.makeSpan(["thinbox"], [node], options);
    return buildCommon.makeSpan(["mord", "vbox"], [node], options);
  },
  mathmlBuilder: (group, options) => {
    var node = new mathMLTree.MathNode("mpadded", [buildGroup2(group.body, options)]);
    if (group.alignment !== "rlap") {
      var offset = group.alignment === "llap" ? "-1" : "-0.5";
      node.setAttribute("lspace", offset + "width");
    }
    node.setAttribute("width", "0px");
    return node;
  }
});
defineFunction({
  type: "styling",
  names: ["\\(", "$"],
  props: {
    numArgs: 0,
    allowedInText: true,
    allowedInMath: false
  },
  handler(_ref, args) {
    var {
      funcName,
      parser
    } = _ref;
    var outerMode = parser.mode;
    parser.switchMode("math");
    var close3 = funcName === "\\(" ? "\\)" : "$";
    var body = parser.parseExpression(false, close3);
    parser.expect(close3);
    parser.switchMode(outerMode);
    return {
      type: "styling",
      mode: parser.mode,
      style: "text",
      body
    };
  }
});
defineFunction({
  type: "text",
  // Doesn't matter what this is.
  names: ["\\)", "\\]"],
  props: {
    numArgs: 0,
    allowedInText: true,
    allowedInMath: false
  },
  handler(context, args) {
    throw new ParseError("Mismatched " + context.funcName);
  }
});
var chooseMathStyle = (group, options) => {
  switch (options.style.size) {
    case Style$1.DISPLAY.size:
      return group.display;
    case Style$1.TEXT.size:
      return group.text;
    case Style$1.SCRIPT.size:
      return group.script;
    case Style$1.SCRIPTSCRIPT.size:
      return group.scriptscript;
    default:
      return group.text;
  }
};
defineFunction({
  type: "mathchoice",
  names: ["\\mathchoice"],
  props: {
    numArgs: 4,
    primitive: true
  },
  handler: (_ref, args) => {
    var {
      parser
    } = _ref;
    return {
      type: "mathchoice",
      mode: parser.mode,
      display: ordargument(args[0]),
      text: ordargument(args[1]),
      script: ordargument(args[2]),
      scriptscript: ordargument(args[3])
    };
  },
  htmlBuilder: (group, options) => {
    var body = chooseMathStyle(group, options);
    var elements = buildExpression$1(body, options, false);
    return buildCommon.makeFragment(elements);
  },
  mathmlBuilder: (group, options) => {
    var body = chooseMathStyle(group, options);
    return buildExpressionRow(body, options);
  }
});
var assembleSupSub = (base2, supGroup, subGroup, options, style2, slant, baseShift) => {
  base2 = buildCommon.makeSpan([], [base2]);
  var subIsSingleCharacter = subGroup && utils.isCharacterBox(subGroup);
  var sub2;
  var sup2;
  if (supGroup) {
    var elem = buildGroup$1(supGroup, options.havingStyle(style2.sup()), options);
    sup2 = {
      elem,
      kern: Math.max(options.fontMetrics().bigOpSpacing1, options.fontMetrics().bigOpSpacing3 - elem.depth)
    };
  }
  if (subGroup) {
    var _elem = buildGroup$1(subGroup, options.havingStyle(style2.sub()), options);
    sub2 = {
      elem: _elem,
      kern: Math.max(options.fontMetrics().bigOpSpacing2, options.fontMetrics().bigOpSpacing4 - _elem.height)
    };
  }
  var finalGroup;
  if (sup2 && sub2) {
    var bottom = options.fontMetrics().bigOpSpacing5 + sub2.elem.height + sub2.elem.depth + sub2.kern + base2.depth + baseShift;
    finalGroup = buildCommon.makeVList({
      positionType: "bottom",
      positionData: bottom,
      children: [{
        type: "kern",
        size: options.fontMetrics().bigOpSpacing5
      }, {
        type: "elem",
        elem: sub2.elem,
        marginLeft: makeEm(-slant)
      }, {
        type: "kern",
        size: sub2.kern
      }, {
        type: "elem",
        elem: base2
      }, {
        type: "kern",
        size: sup2.kern
      }, {
        type: "elem",
        elem: sup2.elem,
        marginLeft: makeEm(slant)
      }, {
        type: "kern",
        size: options.fontMetrics().bigOpSpacing5
      }]
    }, options);
  } else if (sub2) {
    var top = base2.height - baseShift;
    finalGroup = buildCommon.makeVList({
      positionType: "top",
      positionData: top,
      children: [{
        type: "kern",
        size: options.fontMetrics().bigOpSpacing5
      }, {
        type: "elem",
        elem: sub2.elem,
        marginLeft: makeEm(-slant)
      }, {
        type: "kern",
        size: sub2.kern
      }, {
        type: "elem",
        elem: base2
      }]
    }, options);
  } else if (sup2) {
    var _bottom = base2.depth + baseShift;
    finalGroup = buildCommon.makeVList({
      positionType: "bottom",
      positionData: _bottom,
      children: [{
        type: "elem",
        elem: base2
      }, {
        type: "kern",
        size: sup2.kern
      }, {
        type: "elem",
        elem: sup2.elem,
        marginLeft: makeEm(slant)
      }, {
        type: "kern",
        size: options.fontMetrics().bigOpSpacing5
      }]
    }, options);
  } else {
    return base2;
  }
  var parts = [finalGroup];
  if (sub2 && slant !== 0 && !subIsSingleCharacter) {
    var spacer = buildCommon.makeSpan(["mspace"], [], options);
    spacer.style.marginRight = makeEm(slant);
    parts.unshift(spacer);
  }
  return buildCommon.makeSpan(["mop", "op-limits"], parts, options);
};
var noSuccessor = ["\\smallint"];
var htmlBuilder$2 = (grp, options) => {
  var supGroup;
  var subGroup;
  var hasLimits = false;
  var group;
  if (grp.type === "supsub") {
    supGroup = grp.sup;
    subGroup = grp.sub;
    group = assertNodeType(grp.base, "op");
    hasLimits = true;
  } else {
    group = assertNodeType(grp, "op");
  }
  var style2 = options.style;
  var large = false;
  if (style2.size === Style$1.DISPLAY.size && group.symbol && !utils.contains(noSuccessor, group.name)) {
    large = true;
  }
  var base2;
  if (group.symbol) {
    var fontName = large ? "Size2-Regular" : "Size1-Regular";
    var stash = "";
    if (group.name === "\\oiint" || group.name === "\\oiiint") {
      stash = group.name.slice(1);
      group.name = stash === "oiint" ? "\\iint" : "\\iiint";
    }
    base2 = buildCommon.makeSymbol(group.name, fontName, "math", options, ["mop", "op-symbol", large ? "large-op" : "small-op"]);
    if (stash.length > 0) {
      var italic = base2.italic;
      var oval = buildCommon.staticSvg(stash + "Size" + (large ? "2" : "1"), options);
      base2 = buildCommon.makeVList({
        positionType: "individualShift",
        children: [{
          type: "elem",
          elem: base2,
          shift: 0
        }, {
          type: "elem",
          elem: oval,
          shift: large ? 0.08 : 0
        }]
      }, options);
      group.name = "\\" + stash;
      base2.classes.unshift("mop");
      base2.italic = italic;
    }
  } else if (group.body) {
    var inner2 = buildExpression$1(group.body, options, true);
    if (inner2.length === 1 && inner2[0] instanceof SymbolNode) {
      base2 = inner2[0];
      base2.classes[0] = "mop";
    } else {
      base2 = buildCommon.makeSpan(["mop"], inner2, options);
    }
  } else {
    var output7 = [];
    for (var i = 1; i < group.name.length; i++) {
      output7.push(buildCommon.mathsym(group.name[i], group.mode, options));
    }
    base2 = buildCommon.makeSpan(["mop"], output7, options);
  }
  var baseShift = 0;
  var slant = 0;
  if ((base2 instanceof SymbolNode || group.name === "\\oiint" || group.name === "\\oiiint") && !group.suppressBaseShift) {
    baseShift = (base2.height - base2.depth) / 2 - options.fontMetrics().axisHeight;
    slant = base2.italic;
  }
  if (hasLimits) {
    return assembleSupSub(base2, supGroup, subGroup, options, style2, slant, baseShift);
  } else {
    if (baseShift) {
      base2.style.position = "relative";
      base2.style.top = makeEm(baseShift);
    }
    return base2;
  }
};
var mathmlBuilder$1 = (group, options) => {
  var node;
  if (group.symbol) {
    node = new MathNode("mo", [makeText(group.name, group.mode)]);
    if (utils.contains(noSuccessor, group.name)) {
      node.setAttribute("largeop", "false");
    }
  } else if (group.body) {
    node = new MathNode("mo", buildExpression2(group.body, options));
  } else {
    node = new MathNode("mi", [new TextNode2(group.name.slice(1))]);
    var operator3 = new MathNode("mo", [makeText("\u2061", "text")]);
    if (group.parentIsSupSub) {
      node = new MathNode("mrow", [node, operator3]);
    } else {
      node = newDocumentFragment([node, operator3]);
    }
  }
  return node;
};
var singleCharBigOps = {
  "\u220F": "\\prod",
  "\u2210": "\\coprod",
  "\u2211": "\\sum",
  "\u22C0": "\\bigwedge",
  "\u22C1": "\\bigvee",
  "\u22C2": "\\bigcap",
  "\u22C3": "\\bigcup",
  "\u2A00": "\\bigodot",
  "\u2A01": "\\bigoplus",
  "\u2A02": "\\bigotimes",
  "\u2A04": "\\biguplus",
  "\u2A06": "\\bigsqcup"
};
defineFunction({
  type: "op",
  names: ["\\coprod", "\\bigvee", "\\bigwedge", "\\biguplus", "\\bigcap", "\\bigcup", "\\intop", "\\prod", "\\sum", "\\bigotimes", "\\bigoplus", "\\bigodot", "\\bigsqcup", "\\smallint", "\u220F", "\u2210", "\u2211", "\u22C0", "\u22C1", "\u22C2", "\u22C3", "\u2A00", "\u2A01", "\u2A02", "\u2A04", "\u2A06"],
  props: {
    numArgs: 0
  },
  handler: (_ref, args) => {
    var {
      parser,
      funcName
    } = _ref;
    var fName = funcName;
    if (fName.length === 1) {
      fName = singleCharBigOps[fName];
    }
    return {
      type: "op",
      mode: parser.mode,
      limits: true,
      parentIsSupSub: false,
      symbol: true,
      name: fName
    };
  },
  htmlBuilder: htmlBuilder$2,
  mathmlBuilder: mathmlBuilder$1
});
defineFunction({
  type: "op",
  names: ["\\mathop"],
  props: {
    numArgs: 1,
    primitive: true
  },
  handler: (_ref2, args) => {
    var {
      parser
    } = _ref2;
    var body = args[0];
    return {
      type: "op",
      mode: parser.mode,
      limits: false,
      parentIsSupSub: false,
      symbol: false,
      body: ordargument(body)
    };
  },
  htmlBuilder: htmlBuilder$2,
  mathmlBuilder: mathmlBuilder$1
});
var singleCharIntegrals = {
  "\u222B": "\\int",
  "\u222C": "\\iint",
  "\u222D": "\\iiint",
  "\u222E": "\\oint",
  "\u222F": "\\oiint",
  "\u2230": "\\oiiint"
};
defineFunction({
  type: "op",
  names: ["\\arcsin", "\\arccos", "\\arctan", "\\arctg", "\\arcctg", "\\arg", "\\ch", "\\cos", "\\cosec", "\\cosh", "\\cot", "\\cotg", "\\coth", "\\csc", "\\ctg", "\\cth", "\\deg", "\\dim", "\\exp", "\\hom", "\\ker", "\\lg", "\\ln", "\\log", "\\sec", "\\sin", "\\sinh", "\\sh", "\\tan", "\\tanh", "\\tg", "\\th"],
  props: {
    numArgs: 0
  },
  handler(_ref3) {
    var {
      parser,
      funcName
    } = _ref3;
    return {
      type: "op",
      mode: parser.mode,
      limits: false,
      parentIsSupSub: false,
      symbol: false,
      name: funcName
    };
  },
  htmlBuilder: htmlBuilder$2,
  mathmlBuilder: mathmlBuilder$1
});
defineFunction({
  type: "op",
  names: ["\\det", "\\gcd", "\\inf", "\\lim", "\\max", "\\min", "\\Pr", "\\sup"],
  props: {
    numArgs: 0
  },
  handler(_ref4) {
    var {
      parser,
      funcName
    } = _ref4;
    return {
      type: "op",
      mode: parser.mode,
      limits: true,
      parentIsSupSub: false,
      symbol: false,
      name: funcName
    };
  },
  htmlBuilder: htmlBuilder$2,
  mathmlBuilder: mathmlBuilder$1
});
defineFunction({
  type: "op",
  names: ["\\int", "\\iint", "\\iiint", "\\oint", "\\oiint", "\\oiiint", "\u222B", "\u222C", "\u222D", "\u222E", "\u222F", "\u2230"],
  props: {
    numArgs: 0
  },
  handler(_ref5) {
    var {
      parser,
      funcName
    } = _ref5;
    var fName = funcName;
    if (fName.length === 1) {
      fName = singleCharIntegrals[fName];
    }
    return {
      type: "op",
      mode: parser.mode,
      limits: false,
      parentIsSupSub: false,
      symbol: true,
      name: fName
    };
  },
  htmlBuilder: htmlBuilder$2,
  mathmlBuilder: mathmlBuilder$1
});
var htmlBuilder$1 = (grp, options) => {
  var supGroup;
  var subGroup;
  var hasLimits = false;
  var group;
  if (grp.type === "supsub") {
    supGroup = grp.sup;
    subGroup = grp.sub;
    group = assertNodeType(grp.base, "operatorname");
    hasLimits = true;
  } else {
    group = assertNodeType(grp, "operatorname");
  }
  var base2;
  if (group.body.length > 0) {
    var body = group.body.map((child2) => {
      var childText = child2.text;
      if (typeof childText === "string") {
        return {
          type: "textord",
          mode: child2.mode,
          text: childText
        };
      } else {
        return child2;
      }
    });
    var expression = buildExpression$1(body, options.withFont("mathrm"), true);
    for (var i = 0; i < expression.length; i++) {
      var child = expression[i];
      if (child instanceof SymbolNode) {
        child.text = child.text.replace(/\u2212/, "-").replace(/\u2217/, "*");
      }
    }
    base2 = buildCommon.makeSpan(["mop"], expression, options);
  } else {
    base2 = buildCommon.makeSpan(["mop"], [], options);
  }
  if (hasLimits) {
    return assembleSupSub(base2, supGroup, subGroup, options, options.style, 0, 0);
  } else {
    return base2;
  }
};
var mathmlBuilder2 = (group, options) => {
  var expression = buildExpression2(group.body, options.withFont("mathrm"));
  var isAllString = true;
  for (var i = 0; i < expression.length; i++) {
    var node = expression[i];
    if (node instanceof mathMLTree.SpaceNode) ;
    else if (node instanceof mathMLTree.MathNode) {
      switch (node.type) {
        case "mi":
        case "mn":
        case "ms":
        case "mspace":
        case "mtext":
          break;
        // Do nothing yet.
        case "mo": {
          var child = node.children[0];
          if (node.children.length === 1 && child instanceof mathMLTree.TextNode) {
            child.text = child.text.replace(/\u2212/, "-").replace(/\u2217/, "*");
          } else {
            isAllString = false;
          }
          break;
        }
        default:
          isAllString = false;
      }
    } else {
      isAllString = false;
    }
  }
  if (isAllString) {
    var word = expression.map((node2) => node2.toText()).join("");
    expression = [new mathMLTree.TextNode(word)];
  }
  var identifier = new mathMLTree.MathNode("mi", expression);
  identifier.setAttribute("mathvariant", "normal");
  var operator3 = new mathMLTree.MathNode("mo", [makeText("\u2061", "text")]);
  if (group.parentIsSupSub) {
    return new mathMLTree.MathNode("mrow", [identifier, operator3]);
  } else {
    return mathMLTree.newDocumentFragment([identifier, operator3]);
  }
};
defineFunction({
  type: "operatorname",
  names: ["\\operatorname@", "\\operatornamewithlimits"],
  props: {
    numArgs: 1
  },
  handler: (_ref, args) => {
    var {
      parser,
      funcName
    } = _ref;
    var body = args[0];
    return {
      type: "operatorname",
      mode: parser.mode,
      body: ordargument(body),
      alwaysHandleSupSub: funcName === "\\operatornamewithlimits",
      limits: false,
      parentIsSupSub: false
    };
  },
  htmlBuilder: htmlBuilder$1,
  mathmlBuilder: mathmlBuilder2
});
defineMacro("\\operatorname", "\\@ifstar\\operatornamewithlimits\\operatorname@");
defineFunctionBuilders({
  type: "ordgroup",
  htmlBuilder(group, options) {
    if (group.semisimple) {
      return buildCommon.makeFragment(buildExpression$1(group.body, options, false));
    }
    return buildCommon.makeSpan(["mord"], buildExpression$1(group.body, options, true), options);
  },
  mathmlBuilder(group, options) {
    return buildExpressionRow(group.body, options, true);
  }
});
defineFunction({
  type: "overline",
  names: ["\\overline"],
  props: {
    numArgs: 1
  },
  handler(_ref, args) {
    var {
      parser
    } = _ref;
    var body = args[0];
    return {
      type: "overline",
      mode: parser.mode,
      body
    };
  },
  htmlBuilder(group, options) {
    var innerGroup = buildGroup$1(group.body, options.havingCrampedStyle());
    var line = buildCommon.makeLineSpan("overline-line", options);
    var defaultRuleThickness = options.fontMetrics().defaultRuleThickness;
    var vlist = buildCommon.makeVList({
      positionType: "firstBaseline",
      children: [{
        type: "elem",
        elem: innerGroup
      }, {
        type: "kern",
        size: 3 * defaultRuleThickness
      }, {
        type: "elem",
        elem: line
      }, {
        type: "kern",
        size: defaultRuleThickness
      }]
    }, options);
    return buildCommon.makeSpan(["mord", "overline"], [vlist], options);
  },
  mathmlBuilder(group, options) {
    var operator3 = new mathMLTree.MathNode("mo", [new mathMLTree.TextNode("\u203E")]);
    operator3.setAttribute("stretchy", "true");
    var node = new mathMLTree.MathNode("mover", [buildGroup2(group.body, options), operator3]);
    node.setAttribute("accent", "true");
    return node;
  }
});
defineFunction({
  type: "phantom",
  names: ["\\phantom"],
  props: {
    numArgs: 1,
    allowedInText: true
  },
  handler: (_ref, args) => {
    var {
      parser
    } = _ref;
    var body = args[0];
    return {
      type: "phantom",
      mode: parser.mode,
      body: ordargument(body)
    };
  },
  htmlBuilder: (group, options) => {
    var elements = buildExpression$1(group.body, options.withPhantom(), false);
    return buildCommon.makeFragment(elements);
  },
  mathmlBuilder: (group, options) => {
    var inner2 = buildExpression2(group.body, options);
    return new mathMLTree.MathNode("mphantom", inner2);
  }
});
defineFunction({
  type: "hphantom",
  names: ["\\hphantom"],
  props: {
    numArgs: 1,
    allowedInText: true
  },
  handler: (_ref2, args) => {
    var {
      parser
    } = _ref2;
    var body = args[0];
    return {
      type: "hphantom",
      mode: parser.mode,
      body
    };
  },
  htmlBuilder: (group, options) => {
    var node = buildCommon.makeSpan([], [buildGroup$1(group.body, options.withPhantom())]);
    node.height = 0;
    node.depth = 0;
    if (node.children) {
      for (var i = 0; i < node.children.length; i++) {
        node.children[i].height = 0;
        node.children[i].depth = 0;
      }
    }
    node = buildCommon.makeVList({
      positionType: "firstBaseline",
      children: [{
        type: "elem",
        elem: node
      }]
    }, options);
    return buildCommon.makeSpan(["mord"], [node], options);
  },
  mathmlBuilder: (group, options) => {
    var inner2 = buildExpression2(ordargument(group.body), options);
    var phantom = new mathMLTree.MathNode("mphantom", inner2);
    var node = new mathMLTree.MathNode("mpadded", [phantom]);
    node.setAttribute("height", "0px");
    node.setAttribute("depth", "0px");
    return node;
  }
});
defineFunction({
  type: "vphantom",
  names: ["\\vphantom"],
  props: {
    numArgs: 1,
    allowedInText: true
  },
  handler: (_ref3, args) => {
    var {
      parser
    } = _ref3;
    var body = args[0];
    return {
      type: "vphantom",
      mode: parser.mode,
      body
    };
  },
  htmlBuilder: (group, options) => {
    var inner2 = buildCommon.makeSpan(["inner"], [buildGroup$1(group.body, options.withPhantom())]);
    var fix = buildCommon.makeSpan(["fix"], []);
    return buildCommon.makeSpan(["mord", "rlap"], [inner2, fix], options);
  },
  mathmlBuilder: (group, options) => {
    var inner2 = buildExpression2(ordargument(group.body), options);
    var phantom = new mathMLTree.MathNode("mphantom", inner2);
    var node = new mathMLTree.MathNode("mpadded", [phantom]);
    node.setAttribute("width", "0px");
    return node;
  }
});
defineFunction({
  type: "raisebox",
  names: ["\\raisebox"],
  props: {
    numArgs: 2,
    argTypes: ["size", "hbox"],
    allowedInText: true
  },
  handler(_ref, args) {
    var {
      parser
    } = _ref;
    var amount3 = assertNodeType(args[0], "size").value;
    var body = args[1];
    return {
      type: "raisebox",
      mode: parser.mode,
      dy: amount3,
      body
    };
  },
  htmlBuilder(group, options) {
    var body = buildGroup$1(group.body, options);
    var dy = calculateSize(group.dy, options);
    return buildCommon.makeVList({
      positionType: "shift",
      positionData: -dy,
      children: [{
        type: "elem",
        elem: body
      }]
    }, options);
  },
  mathmlBuilder(group, options) {
    var node = new mathMLTree.MathNode("mpadded", [buildGroup2(group.body, options)]);
    var dy = group.dy.number + group.dy.unit;
    node.setAttribute("voffset", dy);
    return node;
  }
});
defineFunction({
  type: "internal",
  names: ["\\relax"],
  props: {
    numArgs: 0,
    allowedInText: true,
    allowedInArgument: true
  },
  handler(_ref) {
    var {
      parser
    } = _ref;
    return {
      type: "internal",
      mode: parser.mode
    };
  }
});
defineFunction({
  type: "rule",
  names: ["\\rule"],
  props: {
    numArgs: 2,
    numOptionalArgs: 1,
    allowedInText: true,
    allowedInMath: true,
    argTypes: ["size", "size", "size"]
  },
  handler(_ref, args, optArgs) {
    var {
      parser
    } = _ref;
    var shift2 = optArgs[0];
    var width = assertNodeType(args[0], "size");
    var height = assertNodeType(args[1], "size");
    return {
      type: "rule",
      mode: parser.mode,
      shift: shift2 && assertNodeType(shift2, "size").value,
      width: width.value,
      height: height.value
    };
  },
  htmlBuilder(group, options) {
    var rule = buildCommon.makeSpan(["mord", "rule"], [], options);
    var width = calculateSize(group.width, options);
    var height = calculateSize(group.height, options);
    var shift2 = group.shift ? calculateSize(group.shift, options) : 0;
    rule.style.borderRightWidth = makeEm(width);
    rule.style.borderTopWidth = makeEm(height);
    rule.style.bottom = makeEm(shift2);
    rule.width = width;
    rule.height = height + shift2;
    rule.depth = -shift2;
    rule.maxFontSize = height * 1.125 * options.sizeMultiplier;
    return rule;
  },
  mathmlBuilder(group, options) {
    var width = calculateSize(group.width, options);
    var height = calculateSize(group.height, options);
    var shift2 = group.shift ? calculateSize(group.shift, options) : 0;
    var color = options.color && options.getColor() || "black";
    var rule = new mathMLTree.MathNode("mspace");
    rule.setAttribute("mathbackground", color);
    rule.setAttribute("width", makeEm(width));
    rule.setAttribute("height", makeEm(height));
    var wrapper = new mathMLTree.MathNode("mpadded", [rule]);
    if (shift2 >= 0) {
      wrapper.setAttribute("height", makeEm(shift2));
    } else {
      wrapper.setAttribute("height", makeEm(shift2));
      wrapper.setAttribute("depth", makeEm(-shift2));
    }
    wrapper.setAttribute("voffset", makeEm(shift2));
    return wrapper;
  }
});
function sizingGroup(value, options, baseOptions) {
  var inner2 = buildExpression$1(value, options, false);
  var multiplier = options.sizeMultiplier / baseOptions.sizeMultiplier;
  for (var i = 0; i < inner2.length; i++) {
    var pos = inner2[i].classes.indexOf("sizing");
    if (pos < 0) {
      Array.prototype.push.apply(inner2[i].classes, options.sizingClasses(baseOptions));
    } else if (inner2[i].classes[pos + 1] === "reset-size" + options.size) {
      inner2[i].classes[pos + 1] = "reset-size" + baseOptions.size;
    }
    inner2[i].height *= multiplier;
    inner2[i].depth *= multiplier;
  }
  return buildCommon.makeFragment(inner2);
}
var sizeFuncs = ["\\tiny", "\\sixptsize", "\\scriptsize", "\\footnotesize", "\\small", "\\normalsize", "\\large", "\\Large", "\\LARGE", "\\huge", "\\Huge"];
var htmlBuilder2 = (group, options) => {
  var newOptions = options.havingSize(group.size);
  return sizingGroup(group.body, newOptions, options);
};
defineFunction({
  type: "sizing",
  names: sizeFuncs,
  props: {
    numArgs: 0,
    allowedInText: true
  },
  handler: (_ref, args) => {
    var {
      breakOnTokenText,
      funcName,
      parser
    } = _ref;
    var body = parser.parseExpression(false, breakOnTokenText);
    return {
      type: "sizing",
      mode: parser.mode,
      // Figure out what size to use based on the list of functions above
      size: sizeFuncs.indexOf(funcName) + 1,
      body
    };
  },
  htmlBuilder: htmlBuilder2,
  mathmlBuilder: (group, options) => {
    var newOptions = options.havingSize(group.size);
    var inner2 = buildExpression2(group.body, newOptions);
    var node = new mathMLTree.MathNode("mstyle", inner2);
    node.setAttribute("mathsize", makeEm(newOptions.sizeMultiplier));
    return node;
  }
});
defineFunction({
  type: "smash",
  names: ["\\smash"],
  props: {
    numArgs: 1,
    numOptionalArgs: 1,
    allowedInText: true
  },
  handler: (_ref, args, optArgs) => {
    var {
      parser
    } = _ref;
    var smashHeight = false;
    var smashDepth = false;
    var tbArg = optArgs[0] && assertNodeType(optArgs[0], "ordgroup");
    if (tbArg) {
      var letter = "";
      for (var i = 0; i < tbArg.body.length; ++i) {
        var node = tbArg.body[i];
        letter = node.text;
        if (letter === "t") {
          smashHeight = true;
        } else if (letter === "b") {
          smashDepth = true;
        } else {
          smashHeight = false;
          smashDepth = false;
          break;
        }
      }
    } else {
      smashHeight = true;
      smashDepth = true;
    }
    var body = args[0];
    return {
      type: "smash",
      mode: parser.mode,
      body,
      smashHeight,
      smashDepth
    };
  },
  htmlBuilder: (group, options) => {
    var node = buildCommon.makeSpan([], [buildGroup$1(group.body, options)]);
    if (!group.smashHeight && !group.smashDepth) {
      return node;
    }
    if (group.smashHeight) {
      node.height = 0;
      if (node.children) {
        for (var i = 0; i < node.children.length; i++) {
          node.children[i].height = 0;
        }
      }
    }
    if (group.smashDepth) {
      node.depth = 0;
      if (node.children) {
        for (var _i = 0; _i < node.children.length; _i++) {
          node.children[_i].depth = 0;
        }
      }
    }
    var smashedNode = buildCommon.makeVList({
      positionType: "firstBaseline",
      children: [{
        type: "elem",
        elem: node
      }]
    }, options);
    return buildCommon.makeSpan(["mord"], [smashedNode], options);
  },
  mathmlBuilder: (group, options) => {
    var node = new mathMLTree.MathNode("mpadded", [buildGroup2(group.body, options)]);
    if (group.smashHeight) {
      node.setAttribute("height", "0px");
    }
    if (group.smashDepth) {
      node.setAttribute("depth", "0px");
    }
    return node;
  }
});
defineFunction({
  type: "sqrt",
  names: ["\\sqrt"],
  props: {
    numArgs: 1,
    numOptionalArgs: 1
  },
  handler(_ref, args, optArgs) {
    var {
      parser
    } = _ref;
    var index = optArgs[0];
    var body = args[0];
    return {
      type: "sqrt",
      mode: parser.mode,
      body,
      index
    };
  },
  htmlBuilder(group, options) {
    var inner2 = buildGroup$1(group.body, options.havingCrampedStyle());
    if (inner2.height === 0) {
      inner2.height = options.fontMetrics().xHeight;
    }
    inner2 = buildCommon.wrapFragment(inner2, options);
    var metrics = options.fontMetrics();
    var theta = metrics.defaultRuleThickness;
    var phi = theta;
    if (options.style.id < Style$1.TEXT.id) {
      phi = options.fontMetrics().xHeight;
    }
    var lineClearance = theta + phi / 4;
    var minDelimiterHeight = inner2.height + inner2.depth + lineClearance + theta;
    var {
      span: img,
      ruleWidth,
      advanceWidth
    } = delimiter.sqrtImage(minDelimiterHeight, options);
    var delimDepth = img.height - ruleWidth;
    if (delimDepth > inner2.height + inner2.depth + lineClearance) {
      lineClearance = (lineClearance + delimDepth - inner2.height - inner2.depth) / 2;
    }
    var imgShift = img.height - inner2.height - lineClearance - ruleWidth;
    inner2.style.paddingLeft = makeEm(advanceWidth);
    var body = buildCommon.makeVList({
      positionType: "firstBaseline",
      children: [{
        type: "elem",
        elem: inner2,
        wrapperClasses: ["svg-align"]
      }, {
        type: "kern",
        size: -(inner2.height + imgShift)
      }, {
        type: "elem",
        elem: img
      }, {
        type: "kern",
        size: ruleWidth
      }]
    }, options);
    if (!group.index) {
      return buildCommon.makeSpan(["mord", "sqrt"], [body], options);
    } else {
      var newOptions = options.havingStyle(Style$1.SCRIPTSCRIPT);
      var rootm = buildGroup$1(group.index, newOptions, options);
      var toShift = 0.6 * (body.height - body.depth);
      var rootVList = buildCommon.makeVList({
        positionType: "shift",
        positionData: -toShift,
        children: [{
          type: "elem",
          elem: rootm
        }]
      }, options);
      var rootVListWrap = buildCommon.makeSpan(["root"], [rootVList]);
      return buildCommon.makeSpan(["mord", "sqrt"], [rootVListWrap, body], options);
    }
  },
  mathmlBuilder(group, options) {
    var {
      body,
      index
    } = group;
    return index ? new mathMLTree.MathNode("mroot", [buildGroup2(body, options), buildGroup2(index, options)]) : new mathMLTree.MathNode("msqrt", [buildGroup2(body, options)]);
  }
});
var styleMap = {
  "display": Style$1.DISPLAY,
  "text": Style$1.TEXT,
  "script": Style$1.SCRIPT,
  "scriptscript": Style$1.SCRIPTSCRIPT
};
defineFunction({
  type: "styling",
  names: ["\\displaystyle", "\\textstyle", "\\scriptstyle", "\\scriptscriptstyle"],
  props: {
    numArgs: 0,
    allowedInText: true,
    primitive: true
  },
  handler(_ref, args) {
    var {
      breakOnTokenText,
      funcName,
      parser
    } = _ref;
    var body = parser.parseExpression(true, breakOnTokenText);
    var style2 = funcName.slice(1, funcName.length - 5);
    return {
      type: "styling",
      mode: parser.mode,
      // Figure out what style to use by pulling out the style from
      // the function name
      style: style2,
      body
    };
  },
  htmlBuilder(group, options) {
    var newStyle = styleMap[group.style];
    var newOptions = options.havingStyle(newStyle).withFont("");
    return sizingGroup(group.body, newOptions, options);
  },
  mathmlBuilder(group, options) {
    var newStyle = styleMap[group.style];
    var newOptions = options.havingStyle(newStyle);
    var inner2 = buildExpression2(group.body, newOptions);
    var node = new mathMLTree.MathNode("mstyle", inner2);
    var styleAttributes = {
      "display": ["0", "true"],
      "text": ["0", "false"],
      "script": ["1", "false"],
      "scriptscript": ["2", "false"]
    };
    var attr = styleAttributes[group.style];
    node.setAttribute("scriptlevel", attr[0]);
    node.setAttribute("displaystyle", attr[1]);
    return node;
  }
});
var htmlBuilderDelegate = function htmlBuilderDelegate2(group, options) {
  var base2 = group.base;
  if (!base2) {
    return null;
  } else if (base2.type === "op") {
    var delegate = base2.limits && (options.style.size === Style$1.DISPLAY.size || base2.alwaysHandleSupSub);
    return delegate ? htmlBuilder$2 : null;
  } else if (base2.type === "operatorname") {
    var _delegate = base2.alwaysHandleSupSub && (options.style.size === Style$1.DISPLAY.size || base2.limits);
    return _delegate ? htmlBuilder$1 : null;
  } else if (base2.type === "accent") {
    return utils.isCharacterBox(base2.base) ? htmlBuilder$a : null;
  } else if (base2.type === "horizBrace") {
    var isSup = !group.sub;
    return isSup === base2.isOver ? htmlBuilder$3 : null;
  } else {
    return null;
  }
};
defineFunctionBuilders({
  type: "supsub",
  htmlBuilder(group, options) {
    var builderDelegate = htmlBuilderDelegate(group, options);
    if (builderDelegate) {
      return builderDelegate(group, options);
    }
    var {
      base: valueBase,
      sup: valueSup,
      sub: valueSub
    } = group;
    var base2 = buildGroup$1(valueBase, options);
    var supm;
    var subm;
    var metrics = options.fontMetrics();
    var supShift = 0;
    var subShift = 0;
    var isCharacterBox3 = valueBase && utils.isCharacterBox(valueBase);
    if (valueSup) {
      var newOptions = options.havingStyle(options.style.sup());
      supm = buildGroup$1(valueSup, newOptions, options);
      if (!isCharacterBox3) {
        supShift = base2.height - newOptions.fontMetrics().supDrop * newOptions.sizeMultiplier / options.sizeMultiplier;
      }
    }
    if (valueSub) {
      var _newOptions = options.havingStyle(options.style.sub());
      subm = buildGroup$1(valueSub, _newOptions, options);
      if (!isCharacterBox3) {
        subShift = base2.depth + _newOptions.fontMetrics().subDrop * _newOptions.sizeMultiplier / options.sizeMultiplier;
      }
    }
    var minSupShift;
    if (options.style === Style$1.DISPLAY) {
      minSupShift = metrics.sup1;
    } else if (options.style.cramped) {
      minSupShift = metrics.sup3;
    } else {
      minSupShift = metrics.sup2;
    }
    var multiplier = options.sizeMultiplier;
    var marginRight = makeEm(0.5 / metrics.ptPerEm / multiplier);
    var marginLeft = null;
    if (subm) {
      var isOiint = group.base && group.base.type === "op" && group.base.name && (group.base.name === "\\oiint" || group.base.name === "\\oiiint");
      if (base2 instanceof SymbolNode || isOiint) {
        marginLeft = makeEm(-base2.italic);
      }
    }
    var supsub;
    if (supm && subm) {
      supShift = Math.max(supShift, minSupShift, supm.depth + 0.25 * metrics.xHeight);
      subShift = Math.max(subShift, metrics.sub2);
      var ruleWidth = metrics.defaultRuleThickness;
      var maxWidth = 4 * ruleWidth;
      if (supShift - supm.depth - (subm.height - subShift) < maxWidth) {
        subShift = maxWidth - (supShift - supm.depth) + subm.height;
        var psi = 0.8 * metrics.xHeight - (supShift - supm.depth);
        if (psi > 0) {
          supShift += psi;
          subShift -= psi;
        }
      }
      var vlistElem = [{
        type: "elem",
        elem: subm,
        shift: subShift,
        marginRight,
        marginLeft
      }, {
        type: "elem",
        elem: supm,
        shift: -supShift,
        marginRight
      }];
      supsub = buildCommon.makeVList({
        positionType: "individualShift",
        children: vlistElem
      }, options);
    } else if (subm) {
      subShift = Math.max(subShift, metrics.sub1, subm.height - 0.8 * metrics.xHeight);
      var _vlistElem = [{
        type: "elem",
        elem: subm,
        marginLeft,
        marginRight
      }];
      supsub = buildCommon.makeVList({
        positionType: "shift",
        positionData: subShift,
        children: _vlistElem
      }, options);
    } else if (supm) {
      supShift = Math.max(supShift, minSupShift, supm.depth + 0.25 * metrics.xHeight);
      supsub = buildCommon.makeVList({
        positionType: "shift",
        positionData: -supShift,
        children: [{
          type: "elem",
          elem: supm,
          marginRight
        }]
      }, options);
    } else {
      throw new Error("supsub must have either sup or sub.");
    }
    var mclass = getTypeOfDomTree(base2, "right") || "mord";
    return buildCommon.makeSpan([mclass], [base2, buildCommon.makeSpan(["msupsub"], [supsub])], options);
  },
  mathmlBuilder(group, options) {
    var isBrace = false;
    var isOver;
    var isSup;
    if (group.base && group.base.type === "horizBrace") {
      isSup = !!group.sup;
      if (isSup === group.base.isOver) {
        isBrace = true;
        isOver = group.base.isOver;
      }
    }
    if (group.base && (group.base.type === "op" || group.base.type === "operatorname")) {
      group.base.parentIsSupSub = true;
    }
    var children = [buildGroup2(group.base, options)];
    if (group.sub) {
      children.push(buildGroup2(group.sub, options));
    }
    if (group.sup) {
      children.push(buildGroup2(group.sup, options));
    }
    var nodeType;
    if (isBrace) {
      nodeType = isOver ? "mover" : "munder";
    } else if (!group.sub) {
      var base2 = group.base;
      if (base2 && base2.type === "op" && base2.limits && (options.style === Style$1.DISPLAY || base2.alwaysHandleSupSub)) {
        nodeType = "mover";
      } else if (base2 && base2.type === "operatorname" && base2.alwaysHandleSupSub && (base2.limits || options.style === Style$1.DISPLAY)) {
        nodeType = "mover";
      } else {
        nodeType = "msup";
      }
    } else if (!group.sup) {
      var _base = group.base;
      if (_base && _base.type === "op" && _base.limits && (options.style === Style$1.DISPLAY || _base.alwaysHandleSupSub)) {
        nodeType = "munder";
      } else if (_base && _base.type === "operatorname" && _base.alwaysHandleSupSub && (_base.limits || options.style === Style$1.DISPLAY)) {
        nodeType = "munder";
      } else {
        nodeType = "msub";
      }
    } else {
      var _base2 = group.base;
      if (_base2 && _base2.type === "op" && _base2.limits && options.style === Style$1.DISPLAY) {
        nodeType = "munderover";
      } else if (_base2 && _base2.type === "operatorname" && _base2.alwaysHandleSupSub && (options.style === Style$1.DISPLAY || _base2.limits)) {
        nodeType = "munderover";
      } else {
        nodeType = "msubsup";
      }
    }
    return new mathMLTree.MathNode(nodeType, children);
  }
});
defineFunctionBuilders({
  type: "atom",
  htmlBuilder(group, options) {
    return buildCommon.mathsym(group.text, group.mode, options, ["m" + group.family]);
  },
  mathmlBuilder(group, options) {
    var node = new mathMLTree.MathNode("mo", [makeText(group.text, group.mode)]);
    if (group.family === "bin") {
      var variant = getVariant(group, options);
      if (variant === "bold-italic") {
        node.setAttribute("mathvariant", variant);
      }
    } else if (group.family === "punct") {
      node.setAttribute("separator", "true");
    } else if (group.family === "open" || group.family === "close") {
      node.setAttribute("stretchy", "false");
    }
    return node;
  }
});
var defaultVariant = {
  "mi": "italic",
  "mn": "normal",
  "mtext": "normal"
};
defineFunctionBuilders({
  type: "mathord",
  htmlBuilder(group, options) {
    return buildCommon.makeOrd(group, options, "mathord");
  },
  mathmlBuilder(group, options) {
    var node = new mathMLTree.MathNode("mi", [makeText(group.text, group.mode, options)]);
    var variant = getVariant(group, options) || "italic";
    if (variant !== defaultVariant[node.type]) {
      node.setAttribute("mathvariant", variant);
    }
    return node;
  }
});
defineFunctionBuilders({
  type: "textord",
  htmlBuilder(group, options) {
    return buildCommon.makeOrd(group, options, "textord");
  },
  mathmlBuilder(group, options) {
    var text5 = makeText(group.text, group.mode, options);
    var variant = getVariant(group, options) || "normal";
    var node;
    if (group.mode === "text") {
      node = new mathMLTree.MathNode("mtext", [text5]);
    } else if (/[0-9]/.test(group.text)) {
      node = new mathMLTree.MathNode("mn", [text5]);
    } else if (group.text === "\\prime") {
      node = new mathMLTree.MathNode("mo", [text5]);
    } else {
      node = new mathMLTree.MathNode("mi", [text5]);
    }
    if (variant !== defaultVariant[node.type]) {
      node.setAttribute("mathvariant", variant);
    }
    return node;
  }
});
var cssSpace = {
  "\\nobreak": "nobreak",
  "\\allowbreak": "allowbreak"
};
var regularSpace = {
  " ": {},
  "\\ ": {},
  "~": {
    className: "nobreak"
  },
  "\\space": {},
  "\\nobreakspace": {
    className: "nobreak"
  }
};
defineFunctionBuilders({
  type: "spacing",
  htmlBuilder(group, options) {
    if (regularSpace.hasOwnProperty(group.text)) {
      var className = regularSpace[group.text].className || "";
      if (group.mode === "text") {
        var ord = buildCommon.makeOrd(group, options, "textord");
        ord.classes.push(className);
        return ord;
      } else {
        return buildCommon.makeSpan(["mspace", className], [buildCommon.mathsym(group.text, group.mode, options)], options);
      }
    } else if (cssSpace.hasOwnProperty(group.text)) {
      return buildCommon.makeSpan(["mspace", cssSpace[group.text]], [], options);
    } else {
      throw new ParseError('Unknown type of space "' + group.text + '"');
    }
  },
  mathmlBuilder(group, options) {
    var node;
    if (regularSpace.hasOwnProperty(group.text)) {
      node = new mathMLTree.MathNode("mtext", [new mathMLTree.TextNode("\xA0")]);
    } else if (cssSpace.hasOwnProperty(group.text)) {
      return new mathMLTree.MathNode("mspace");
    } else {
      throw new ParseError('Unknown type of space "' + group.text + '"');
    }
    return node;
  }
});
var pad = () => {
  var padNode = new mathMLTree.MathNode("mtd", []);
  padNode.setAttribute("width", "50%");
  return padNode;
};
defineFunctionBuilders({
  type: "tag",
  mathmlBuilder(group, options) {
    var table = new mathMLTree.MathNode("mtable", [new mathMLTree.MathNode("mtr", [pad(), new mathMLTree.MathNode("mtd", [buildExpressionRow(group.body, options)]), pad(), new mathMLTree.MathNode("mtd", [buildExpressionRow(group.tag, options)])])]);
    table.setAttribute("width", "100%");
    return table;
  }
});
var textFontFamilies = {
  "\\text": void 0,
  "\\textrm": "textrm",
  "\\textsf": "textsf",
  "\\texttt": "texttt",
  "\\textnormal": "textrm"
};
var textFontWeights = {
  "\\textbf": "textbf",
  "\\textmd": "textmd"
};
var textFontShapes = {
  "\\textit": "textit",
  "\\textup": "textup"
};
var optionsWithFont = (group, options) => {
  var font = group.font;
  if (!font) {
    return options;
  } else if (textFontFamilies[font]) {
    return options.withTextFontFamily(textFontFamilies[font]);
  } else if (textFontWeights[font]) {
    return options.withTextFontWeight(textFontWeights[font]);
  } else if (font === "\\emph") {
    return options.fontShape === "textit" ? options.withTextFontShape("textup") : options.withTextFontShape("textit");
  }
  return options.withTextFontShape(textFontShapes[font]);
};
defineFunction({
  type: "text",
  names: [
    // Font families
    "\\text",
    "\\textrm",
    "\\textsf",
    "\\texttt",
    "\\textnormal",
    // Font weights
    "\\textbf",
    "\\textmd",
    // Font Shapes
    "\\textit",
    "\\textup",
    "\\emph"
  ],
  props: {
    numArgs: 1,
    argTypes: ["text"],
    allowedInArgument: true,
    allowedInText: true
  },
  handler(_ref, args) {
    var {
      parser,
      funcName
    } = _ref;
    var body = args[0];
    return {
      type: "text",
      mode: parser.mode,
      body: ordargument(body),
      font: funcName
    };
  },
  htmlBuilder(group, options) {
    var newOptions = optionsWithFont(group, options);
    var inner2 = buildExpression$1(group.body, newOptions, true);
    return buildCommon.makeSpan(["mord", "text"], inner2, newOptions);
  },
  mathmlBuilder(group, options) {
    var newOptions = optionsWithFont(group, options);
    return buildExpressionRow(group.body, newOptions);
  }
});
defineFunction({
  type: "underline",
  names: ["\\underline"],
  props: {
    numArgs: 1,
    allowedInText: true
  },
  handler(_ref, args) {
    var {
      parser
    } = _ref;
    return {
      type: "underline",
      mode: parser.mode,
      body: args[0]
    };
  },
  htmlBuilder(group, options) {
    var innerGroup = buildGroup$1(group.body, options);
    var line = buildCommon.makeLineSpan("underline-line", options);
    var defaultRuleThickness = options.fontMetrics().defaultRuleThickness;
    var vlist = buildCommon.makeVList({
      positionType: "top",
      positionData: innerGroup.height,
      children: [{
        type: "kern",
        size: defaultRuleThickness
      }, {
        type: "elem",
        elem: line
      }, {
        type: "kern",
        size: 3 * defaultRuleThickness
      }, {
        type: "elem",
        elem: innerGroup
      }]
    }, options);
    return buildCommon.makeSpan(["mord", "underline"], [vlist], options);
  },
  mathmlBuilder(group, options) {
    var operator3 = new mathMLTree.MathNode("mo", [new mathMLTree.TextNode("\u203E")]);
    operator3.setAttribute("stretchy", "true");
    var node = new mathMLTree.MathNode("munder", [buildGroup2(group.body, options), operator3]);
    node.setAttribute("accentunder", "true");
    return node;
  }
});
defineFunction({
  type: "vcenter",
  names: ["\\vcenter"],
  props: {
    numArgs: 1,
    argTypes: ["original"],
    // In LaTeX, \vcenter can act only on a box.
    allowedInText: false
  },
  handler(_ref, args) {
    var {
      parser
    } = _ref;
    return {
      type: "vcenter",
      mode: parser.mode,
      body: args[0]
    };
  },
  htmlBuilder(group, options) {
    var body = buildGroup$1(group.body, options);
    var axisHeight = options.fontMetrics().axisHeight;
    var dy = 0.5 * (body.height - axisHeight - (body.depth + axisHeight));
    return buildCommon.makeVList({
      positionType: "shift",
      positionData: dy,
      children: [{
        type: "elem",
        elem: body
      }]
    }, options);
  },
  mathmlBuilder(group, options) {
    return new mathMLTree.MathNode("mpadded", [buildGroup2(group.body, options)], ["vcenter"]);
  }
});
defineFunction({
  type: "verb",
  names: ["\\verb"],
  props: {
    numArgs: 0,
    allowedInText: true
  },
  handler(context, args, optArgs) {
    throw new ParseError("\\verb ended by end of line instead of matching delimiter");
  },
  htmlBuilder(group, options) {
    var text5 = makeVerb(group);
    var body = [];
    var newOptions = options.havingStyle(options.style.text());
    for (var i = 0; i < text5.length; i++) {
      var c = text5[i];
      if (c === "~") {
        c = "\\textasciitilde";
      }
      body.push(buildCommon.makeSymbol(c, "Typewriter-Regular", group.mode, newOptions, ["mord", "texttt"]));
    }
    return buildCommon.makeSpan(["mord", "text"].concat(newOptions.sizingClasses(options)), buildCommon.tryCombineChars(body), newOptions);
  },
  mathmlBuilder(group, options) {
    var text5 = new mathMLTree.TextNode(makeVerb(group));
    var node = new mathMLTree.MathNode("mtext", [text5]);
    node.setAttribute("mathvariant", "monospace");
    return node;
  }
});
var makeVerb = (group) => group.body.replace(/ /g, group.star ? "\u2423" : "\xA0");
var functions = _functions;
var spaceRegexString = "[ \r\n	]";
var controlWordRegexString = "\\\\[a-zA-Z@]+";
var controlSymbolRegexString = "\\\\[^\uD800-\uDFFF]";
var controlWordWhitespaceRegexString = "(" + controlWordRegexString + ")" + spaceRegexString + "*";
var controlSpaceRegexString = "\\\\(\n|[ \r	]+\n?)[ \r	]*";
var combiningDiacriticalMarkString = "[\u0300-\u036F]";
var combiningDiacriticalMarksEndRegex = new RegExp(combiningDiacriticalMarkString + "+$");
var tokenRegexString = "(" + spaceRegexString + "+)|" + // whitespace
(controlSpaceRegexString + "|") + // \whitespace
"([!-\\[\\]-\u2027\u202A-\uD7FF\uF900-\uFFFF]" + // single codepoint
(combiningDiacriticalMarkString + "*") + // ...plus accents
"|[\uD800-\uDBFF][\uDC00-\uDFFF]" + // surrogate pair
(combiningDiacriticalMarkString + "*") + // ...plus accents
"|\\\\verb\\*([^]).*?\\4|\\\\verb([^*a-zA-Z]).*?\\5" + // \verb unstarred
("|" + controlWordWhitespaceRegexString) + // \macroName + spaces
("|" + controlSymbolRegexString + ")");
var Lexer = class {
  // Category codes. The lexer only supports comment characters (14) for now.
  // MacroExpander additionally distinguishes active (13).
  constructor(input, settings) {
    this.input = void 0;
    this.settings = void 0;
    this.tokenRegex = void 0;
    this.catcodes = void 0;
    this.input = input;
    this.settings = settings;
    this.tokenRegex = new RegExp(tokenRegexString, "g");
    this.catcodes = {
      "%": 14,
      // comment character
      "~": 13
      // active character
    };
  }
  setCatcode(char, code) {
    this.catcodes[char] = code;
  }
  /**
   * This function lexes a single token.
   */
  lex() {
    var input = this.input;
    var pos = this.tokenRegex.lastIndex;
    if (pos === input.length) {
      return new Token("EOF", new SourceLocation(this, pos, pos));
    }
    var match = this.tokenRegex.exec(input);
    if (match === null || match.index !== pos) {
      throw new ParseError("Unexpected character: '" + input[pos] + "'", new Token(input[pos], new SourceLocation(this, pos, pos + 1)));
    }
    var text5 = match[6] || match[3] || (match[2] ? "\\ " : " ");
    if (this.catcodes[text5] === 14) {
      var nlIndex = input.indexOf("\n", this.tokenRegex.lastIndex);
      if (nlIndex === -1) {
        this.tokenRegex.lastIndex = input.length;
        this.settings.reportNonstrict("commentAtEnd", "% comment has no terminating newline; LaTeX would fail because of commenting the end of math mode (e.g. $)");
      } else {
        this.tokenRegex.lastIndex = nlIndex + 1;
      }
      return this.lex();
    }
    return new Token(text5, new SourceLocation(this, pos, this.tokenRegex.lastIndex));
  }
};
var Namespace = class {
  /**
   * Both arguments are optional.  The first argument is an object of
   * built-in mappings which never change.  The second argument is an object
   * of initial (global-level) mappings, which will constantly change
   * according to any global/top-level `set`s done.
   */
  constructor(builtins, globalMacros) {
    if (builtins === void 0) {
      builtins = {};
    }
    if (globalMacros === void 0) {
      globalMacros = {};
    }
    this.current = void 0;
    this.builtins = void 0;
    this.undefStack = void 0;
    this.current = globalMacros;
    this.builtins = builtins;
    this.undefStack = [];
  }
  /**
   * Start a new nested group, affecting future local `set`s.
   */
  beginGroup() {
    this.undefStack.push({});
  }
  /**
   * End current nested group, restoring values before the group began.
   */
  endGroup() {
    if (this.undefStack.length === 0) {
      throw new ParseError("Unbalanced namespace destruction: attempt to pop global namespace; please report this as a bug");
    }
    var undefs = this.undefStack.pop();
    for (var undef in undefs) {
      if (undefs.hasOwnProperty(undef)) {
        if (undefs[undef] == null) {
          delete this.current[undef];
        } else {
          this.current[undef] = undefs[undef];
        }
      }
    }
  }
  /**
   * Ends all currently nested groups (if any), restoring values before the
   * groups began.  Useful in case of an error in the middle of parsing.
   */
  endGroups() {
    while (this.undefStack.length > 0) {
      this.endGroup();
    }
  }
  /**
   * Detect whether `name` has a definition.  Equivalent to
   * `get(name) != null`.
   */
  has(name) {
    return this.current.hasOwnProperty(name) || this.builtins.hasOwnProperty(name);
  }
  /**
   * Get the current value of a name, or `undefined` if there is no value.
   *
   * Note: Do not use `if (namespace.get(...))` to detect whether a macro
   * is defined, as the definition may be the empty string which evaluates
   * to `false` in JavaScript.  Use `if (namespace.get(...) != null)` or
   * `if (namespace.has(...))`.
   */
  get(name) {
    if (this.current.hasOwnProperty(name)) {
      return this.current[name];
    } else {
      return this.builtins[name];
    }
  }
  /**
   * Set the current value of a name, and optionally set it globally too.
   * Local set() sets the current value and (when appropriate) adds an undo
   * operation to the undo stack.  Global set() may change the undo
   * operation at every level, so takes time linear in their number.
   * A value of undefined means to delete existing definitions.
   */
  set(name, value, global) {
    if (global === void 0) {
      global = false;
    }
    if (global) {
      for (var i = 0; i < this.undefStack.length; i++) {
        delete this.undefStack[i][name];
      }
      if (this.undefStack.length > 0) {
        this.undefStack[this.undefStack.length - 1][name] = value;
      }
    } else {
      var top = this.undefStack[this.undefStack.length - 1];
      if (top && !top.hasOwnProperty(name)) {
        top[name] = this.current[name];
      }
    }
    if (value == null) {
      delete this.current[name];
    } else {
      this.current[name] = value;
    }
  }
};
var macros = _macros;
defineMacro("\\noexpand", function(context) {
  var t = context.popToken();
  if (context.isExpandable(t.text)) {
    t.noexpand = true;
    t.treatAsRelax = true;
  }
  return {
    tokens: [t],
    numArgs: 0
  };
});
defineMacro("\\expandafter", function(context) {
  var t = context.popToken();
  context.expandOnce(true);
  return {
    tokens: [t],
    numArgs: 0
  };
});
defineMacro("\\@firstoftwo", function(context) {
  var args = context.consumeArgs(2);
  return {
    tokens: args[0],
    numArgs: 0
  };
});
defineMacro("\\@secondoftwo", function(context) {
  var args = context.consumeArgs(2);
  return {
    tokens: args[1],
    numArgs: 0
  };
});
defineMacro("\\@ifnextchar", function(context) {
  var args = context.consumeArgs(3);
  context.consumeSpaces();
  var nextToken = context.future();
  if (args[0].length === 1 && args[0][0].text === nextToken.text) {
    return {
      tokens: args[1],
      numArgs: 0
    };
  } else {
    return {
      tokens: args[2],
      numArgs: 0
    };
  }
});
defineMacro("\\@ifstar", "\\@ifnextchar *{\\@firstoftwo{#1}}");
defineMacro("\\TextOrMath", function(context) {
  var args = context.consumeArgs(2);
  if (context.mode === "text") {
    return {
      tokens: args[0],
      numArgs: 0
    };
  } else {
    return {
      tokens: args[1],
      numArgs: 0
    };
  }
});
var digitToNumber = {
  "0": 0,
  "1": 1,
  "2": 2,
  "3": 3,
  "4": 4,
  "5": 5,
  "6": 6,
  "7": 7,
  "8": 8,
  "9": 9,
  "a": 10,
  "A": 10,
  "b": 11,
  "B": 11,
  "c": 12,
  "C": 12,
  "d": 13,
  "D": 13,
  "e": 14,
  "E": 14,
  "f": 15,
  "F": 15
};
defineMacro("\\char", function(context) {
  var token = context.popToken();
  var base2;
  var number2 = "";
  if (token.text === "'") {
    base2 = 8;
    token = context.popToken();
  } else if (token.text === '"') {
    base2 = 16;
    token = context.popToken();
  } else if (token.text === "`") {
    token = context.popToken();
    if (token.text[0] === "\\") {
      number2 = token.text.charCodeAt(1);
    } else if (token.text === "EOF") {
      throw new ParseError("\\char` missing argument");
    } else {
      number2 = token.text.charCodeAt(0);
    }
  } else {
    base2 = 10;
  }
  if (base2) {
    number2 = digitToNumber[token.text];
    if (number2 == null || number2 >= base2) {
      throw new ParseError("Invalid base-" + base2 + " digit " + token.text);
    }
    var digit;
    while ((digit = digitToNumber[context.future().text]) != null && digit < base2) {
      number2 *= base2;
      number2 += digit;
      context.popToken();
    }
  }
  return "\\@char{" + number2 + "}";
});
var newcommand = (context, existsOK, nonexistsOK, skipIfExists) => {
  var arg = context.consumeArg().tokens;
  if (arg.length !== 1) {
    throw new ParseError("\\newcommand's first argument must be a macro name");
  }
  var name = arg[0].text;
  var exists = context.isDefined(name);
  if (exists && !existsOK) {
    throw new ParseError("\\newcommand{" + name + "} attempting to redefine " + (name + "; use \\renewcommand"));
  }
  if (!exists && !nonexistsOK) {
    throw new ParseError("\\renewcommand{" + name + "} when command " + name + " does not yet exist; use \\newcommand");
  }
  var numArgs = 0;
  arg = context.consumeArg().tokens;
  if (arg.length === 1 && arg[0].text === "[") {
    var argText = "";
    var token = context.expandNextToken();
    while (token.text !== "]" && token.text !== "EOF") {
      argText += token.text;
      token = context.expandNextToken();
    }
    if (!argText.match(/^\s*[0-9]+\s*$/)) {
      throw new ParseError("Invalid number of arguments: " + argText);
    }
    numArgs = parseInt(argText);
    arg = context.consumeArg().tokens;
  }
  if (!(exists && skipIfExists)) {
    context.macros.set(name, {
      tokens: arg,
      numArgs
    });
  }
  return "";
};
defineMacro("\\newcommand", (context) => newcommand(context, false, true, false));
defineMacro("\\renewcommand", (context) => newcommand(context, true, false, false));
defineMacro("\\providecommand", (context) => newcommand(context, true, true, true));
defineMacro("\\message", (context) => {
  var arg = context.consumeArgs(1)[0];
  console.log(arg.reverse().map((token) => token.text).join(""));
  return "";
});
defineMacro("\\errmessage", (context) => {
  var arg = context.consumeArgs(1)[0];
  console.error(arg.reverse().map((token) => token.text).join(""));
  return "";
});
defineMacro("\\show", (context) => {
  var tok = context.popToken();
  var name = tok.text;
  console.log(tok, context.macros.get(name), functions[name], symbols.math[name], symbols.text[name]);
  return "";
});
defineMacro("\\bgroup", "{");
defineMacro("\\egroup", "}");
defineMacro("~", "\\nobreakspace");
defineMacro("\\lq", "`");
defineMacro("\\rq", "'");
defineMacro("\\aa", "\\r a");
defineMacro("\\AA", "\\r A");
defineMacro("\\textcopyright", "\\html@mathml{\\textcircled{c}}{\\char`\xA9}");
defineMacro("\\copyright", "\\TextOrMath{\\textcopyright}{\\text{\\textcopyright}}");
defineMacro("\\textregistered", "\\html@mathml{\\textcircled{\\scriptsize R}}{\\char`\xAE}");
defineMacro("\u212C", "\\mathscr{B}");
defineMacro("\u2130", "\\mathscr{E}");
defineMacro("\u2131", "\\mathscr{F}");
defineMacro("\u210B", "\\mathscr{H}");
defineMacro("\u2110", "\\mathscr{I}");
defineMacro("\u2112", "\\mathscr{L}");
defineMacro("\u2133", "\\mathscr{M}");
defineMacro("\u211B", "\\mathscr{R}");
defineMacro("\u212D", "\\mathfrak{C}");
defineMacro("\u210C", "\\mathfrak{H}");
defineMacro("\u2128", "\\mathfrak{Z}");
defineMacro("\\Bbbk", "\\Bbb{k}");
defineMacro("\xB7", "\\cdotp");
defineMacro("\\llap", "\\mathllap{\\textrm{#1}}");
defineMacro("\\rlap", "\\mathrlap{\\textrm{#1}}");
defineMacro("\\clap", "\\mathclap{\\textrm{#1}}");
defineMacro("\\mathstrut", "\\vphantom{(}");
defineMacro("\\underbar", "\\underline{\\text{#1}}");
defineMacro("\\not", '\\html@mathml{\\mathrel{\\mathrlap\\@not}}{\\char"338}');
defineMacro("\\neq", "\\html@mathml{\\mathrel{\\not=}}{\\mathrel{\\char`\u2260}}");
defineMacro("\\ne", "\\neq");
defineMacro("\u2260", "\\neq");
defineMacro("\\notin", "\\html@mathml{\\mathrel{{\\in}\\mathllap{/\\mskip1mu}}}{\\mathrel{\\char`\u2209}}");
defineMacro("\u2209", "\\notin");
defineMacro("\u2258", "\\html@mathml{\\mathrel{=\\kern{-1em}\\raisebox{0.4em}{$\\scriptsize\\frown$}}}{\\mathrel{\\char`\u2258}}");
defineMacro("\u2259", "\\html@mathml{\\stackrel{\\tiny\\wedge}{=}}{\\mathrel{\\char`\u2258}}");
defineMacro("\u225A", "\\html@mathml{\\stackrel{\\tiny\\vee}{=}}{\\mathrel{\\char`\u225A}}");
defineMacro("\u225B", "\\html@mathml{\\stackrel{\\scriptsize\\star}{=}}{\\mathrel{\\char`\u225B}}");
defineMacro("\u225D", "\\html@mathml{\\stackrel{\\tiny\\mathrm{def}}{=}}{\\mathrel{\\char`\u225D}}");
defineMacro("\u225E", "\\html@mathml{\\stackrel{\\tiny\\mathrm{m}}{=}}{\\mathrel{\\char`\u225E}}");
defineMacro("\u225F", "\\html@mathml{\\stackrel{\\tiny?}{=}}{\\mathrel{\\char`\u225F}}");
defineMacro("\u27C2", "\\perp");
defineMacro("\u203C", "\\mathclose{!\\mkern-0.8mu!}");
defineMacro("\u220C", "\\notni");
defineMacro("\u231C", "\\ulcorner");
defineMacro("\u231D", "\\urcorner");
defineMacro("\u231E", "\\llcorner");
defineMacro("\u231F", "\\lrcorner");
defineMacro("\xA9", "\\copyright");
defineMacro("\xAE", "\\textregistered");
defineMacro("\uFE0F", "\\textregistered");
defineMacro("\\ulcorner", '\\html@mathml{\\@ulcorner}{\\mathop{\\char"231c}}');
defineMacro("\\urcorner", '\\html@mathml{\\@urcorner}{\\mathop{\\char"231d}}');
defineMacro("\\llcorner", '\\html@mathml{\\@llcorner}{\\mathop{\\char"231e}}');
defineMacro("\\lrcorner", '\\html@mathml{\\@lrcorner}{\\mathop{\\char"231f}}');
defineMacro("\\vdots", "{\\varvdots\\rule{0pt}{15pt}}");
defineMacro("\u22EE", "\\vdots");
defineMacro("\\varGamma", "\\mathit{\\Gamma}");
defineMacro("\\varDelta", "\\mathit{\\Delta}");
defineMacro("\\varTheta", "\\mathit{\\Theta}");
defineMacro("\\varLambda", "\\mathit{\\Lambda}");
defineMacro("\\varXi", "\\mathit{\\Xi}");
defineMacro("\\varPi", "\\mathit{\\Pi}");
defineMacro("\\varSigma", "\\mathit{\\Sigma}");
defineMacro("\\varUpsilon", "\\mathit{\\Upsilon}");
defineMacro("\\varPhi", "\\mathit{\\Phi}");
defineMacro("\\varPsi", "\\mathit{\\Psi}");
defineMacro("\\varOmega", "\\mathit{\\Omega}");
defineMacro("\\substack", "\\begin{subarray}{c}#1\\end{subarray}");
defineMacro("\\colon", "\\nobreak\\mskip2mu\\mathpunct{}\\mathchoice{\\mkern-3mu}{\\mkern-3mu}{}{}{:}\\mskip6mu\\relax");
defineMacro("\\boxed", "\\fbox{$\\displaystyle{#1}$}");
defineMacro("\\iff", "\\DOTSB\\;\\Longleftrightarrow\\;");
defineMacro("\\implies", "\\DOTSB\\;\\Longrightarrow\\;");
defineMacro("\\impliedby", "\\DOTSB\\;\\Longleftarrow\\;");
defineMacro("\\dddot", "{\\overset{\\raisebox{-0.1ex}{\\normalsize ...}}{#1}}");
defineMacro("\\ddddot", "{\\overset{\\raisebox{-0.1ex}{\\normalsize ....}}{#1}}");
var dotsByToken = {
  ",": "\\dotsc",
  "\\not": "\\dotsb",
  // \keybin@ checks for the following:
  "+": "\\dotsb",
  "=": "\\dotsb",
  "<": "\\dotsb",
  ">": "\\dotsb",
  "-": "\\dotsb",
  "*": "\\dotsb",
  ":": "\\dotsb",
  // Symbols whose definition starts with \DOTSB:
  "\\DOTSB": "\\dotsb",
  "\\coprod": "\\dotsb",
  "\\bigvee": "\\dotsb",
  "\\bigwedge": "\\dotsb",
  "\\biguplus": "\\dotsb",
  "\\bigcap": "\\dotsb",
  "\\bigcup": "\\dotsb",
  "\\prod": "\\dotsb",
  "\\sum": "\\dotsb",
  "\\bigotimes": "\\dotsb",
  "\\bigoplus": "\\dotsb",
  "\\bigodot": "\\dotsb",
  "\\bigsqcup": "\\dotsb",
  "\\And": "\\dotsb",
  "\\longrightarrow": "\\dotsb",
  "\\Longrightarrow": "\\dotsb",
  "\\longleftarrow": "\\dotsb",
  "\\Longleftarrow": "\\dotsb",
  "\\longleftrightarrow": "\\dotsb",
  "\\Longleftrightarrow": "\\dotsb",
  "\\mapsto": "\\dotsb",
  "\\longmapsto": "\\dotsb",
  "\\hookrightarrow": "\\dotsb",
  "\\doteq": "\\dotsb",
  // Symbols whose definition starts with \mathbin:
  "\\mathbin": "\\dotsb",
  // Symbols whose definition starts with \mathrel:
  "\\mathrel": "\\dotsb",
  "\\relbar": "\\dotsb",
  "\\Relbar": "\\dotsb",
  "\\xrightarrow": "\\dotsb",
  "\\xleftarrow": "\\dotsb",
  // Symbols whose definition starts with \DOTSI:
  "\\DOTSI": "\\dotsi",
  "\\int": "\\dotsi",
  "\\oint": "\\dotsi",
  "\\iint": "\\dotsi",
  "\\iiint": "\\dotsi",
  "\\iiiint": "\\dotsi",
  "\\idotsint": "\\dotsi",
  // Symbols whose definition starts with \DOTSX:
  "\\DOTSX": "\\dotsx"
};
defineMacro("\\dots", function(context) {
  var thedots = "\\dotso";
  var next = context.expandAfterFuture().text;
  if (next in dotsByToken) {
    thedots = dotsByToken[next];
  } else if (next.slice(0, 4) === "\\not") {
    thedots = "\\dotsb";
  } else if (next in symbols.math) {
    if (utils.contains(["bin", "rel"], symbols.math[next].group)) {
      thedots = "\\dotsb";
    }
  }
  return thedots;
});
var spaceAfterDots = {
  // \rightdelim@ checks for the following:
  ")": true,
  "]": true,
  "\\rbrack": true,
  "\\}": true,
  "\\rbrace": true,
  "\\rangle": true,
  "\\rceil": true,
  "\\rfloor": true,
  "\\rgroup": true,
  "\\rmoustache": true,
  "\\right": true,
  "\\bigr": true,
  "\\biggr": true,
  "\\Bigr": true,
  "\\Biggr": true,
  // \extra@ also tests for the following:
  "$": true,
  // \extrap@ checks for the following:
  ";": true,
  ".": true,
  ",": true
};
defineMacro("\\dotso", function(context) {
  var next = context.future().text;
  if (next in spaceAfterDots) {
    return "\\ldots\\,";
  } else {
    return "\\ldots";
  }
});
defineMacro("\\dotsc", function(context) {
  var next = context.future().text;
  if (next in spaceAfterDots && next !== ",") {
    return "\\ldots\\,";
  } else {
    return "\\ldots";
  }
});
defineMacro("\\cdots", function(context) {
  var next = context.future().text;
  if (next in spaceAfterDots) {
    return "\\@cdots\\,";
  } else {
    return "\\@cdots";
  }
});
defineMacro("\\dotsb", "\\cdots");
defineMacro("\\dotsm", "\\cdots");
defineMacro("\\dotsi", "\\!\\cdots");
defineMacro("\\dotsx", "\\ldots\\,");
defineMacro("\\DOTSI", "\\relax");
defineMacro("\\DOTSB", "\\relax");
defineMacro("\\DOTSX", "\\relax");
defineMacro("\\tmspace", "\\TextOrMath{\\kern#1#3}{\\mskip#1#2}\\relax");
defineMacro("\\,", "\\tmspace+{3mu}{.1667em}");
defineMacro("\\thinspace", "\\,");
defineMacro("\\>", "\\mskip{4mu}");
defineMacro("\\:", "\\tmspace+{4mu}{.2222em}");
defineMacro("\\medspace", "\\:");
defineMacro("\\;", "\\tmspace+{5mu}{.2777em}");
defineMacro("\\thickspace", "\\;");
defineMacro("\\!", "\\tmspace-{3mu}{.1667em}");
defineMacro("\\negthinspace", "\\!");
defineMacro("\\negmedspace", "\\tmspace-{4mu}{.2222em}");
defineMacro("\\negthickspace", "\\tmspace-{5mu}{.277em}");
defineMacro("\\enspace", "\\kern.5em ");
defineMacro("\\enskip", "\\hskip.5em\\relax");
defineMacro("\\quad", "\\hskip1em\\relax");
defineMacro("\\qquad", "\\hskip2em\\relax");
defineMacro("\\tag", "\\@ifstar\\tag@literal\\tag@paren");
defineMacro("\\tag@paren", "\\tag@literal{({#1})}");
defineMacro("\\tag@literal", (context) => {
  if (context.macros.get("\\df@tag")) {
    throw new ParseError("Multiple \\tag");
  }
  return "\\gdef\\df@tag{\\text{#1}}";
});
defineMacro("\\bmod", "\\mathchoice{\\mskip1mu}{\\mskip1mu}{\\mskip5mu}{\\mskip5mu}\\mathbin{\\rm mod}\\mathchoice{\\mskip1mu}{\\mskip1mu}{\\mskip5mu}{\\mskip5mu}");
defineMacro("\\pod", "\\allowbreak\\mathchoice{\\mkern18mu}{\\mkern8mu}{\\mkern8mu}{\\mkern8mu}(#1)");
defineMacro("\\pmod", "\\pod{{\\rm mod}\\mkern6mu#1}");
defineMacro("\\mod", "\\allowbreak\\mathchoice{\\mkern18mu}{\\mkern12mu}{\\mkern12mu}{\\mkern12mu}{\\rm mod}\\,\\,#1");
defineMacro("\\newline", "\\\\\\relax");
defineMacro("\\TeX", "\\textrm{\\html@mathml{T\\kern-.1667em\\raisebox{-.5ex}{E}\\kern-.125emX}{TeX}}");
var latexRaiseA = makeEm(fontMetricsData["Main-Regular"]["T".charCodeAt(0)][1] - 0.7 * fontMetricsData["Main-Regular"]["A".charCodeAt(0)][1]);
defineMacro("\\LaTeX", "\\textrm{\\html@mathml{" + ("L\\kern-.36em\\raisebox{" + latexRaiseA + "}{\\scriptstyle A}") + "\\kern-.15em\\TeX}{LaTeX}}");
defineMacro("\\KaTeX", "\\textrm{\\html@mathml{" + ("K\\kern-.17em\\raisebox{" + latexRaiseA + "}{\\scriptstyle A}") + "\\kern-.15em\\TeX}{KaTeX}}");
defineMacro("\\hspace", "\\@ifstar\\@hspacer\\@hspace");
defineMacro("\\@hspace", "\\hskip #1\\relax");
defineMacro("\\@hspacer", "\\rule{0pt}{0pt}\\hskip #1\\relax");
defineMacro("\\ordinarycolon", ":");
defineMacro("\\vcentcolon", "\\mathrel{\\mathop\\ordinarycolon}");
defineMacro("\\dblcolon", '\\html@mathml{\\mathrel{\\vcentcolon\\mathrel{\\mkern-.9mu}\\vcentcolon}}{\\mathop{\\char"2237}}');
defineMacro("\\coloneqq", '\\html@mathml{\\mathrel{\\vcentcolon\\mathrel{\\mkern-1.2mu}=}}{\\mathop{\\char"2254}}');
defineMacro("\\Coloneqq", '\\html@mathml{\\mathrel{\\dblcolon\\mathrel{\\mkern-1.2mu}=}}{\\mathop{\\char"2237\\char"3d}}');
defineMacro("\\coloneq", '\\html@mathml{\\mathrel{\\vcentcolon\\mathrel{\\mkern-1.2mu}\\mathrel{-}}}{\\mathop{\\char"3a\\char"2212}}');
defineMacro("\\Coloneq", '\\html@mathml{\\mathrel{\\dblcolon\\mathrel{\\mkern-1.2mu}\\mathrel{-}}}{\\mathop{\\char"2237\\char"2212}}');
defineMacro("\\eqqcolon", '\\html@mathml{\\mathrel{=\\mathrel{\\mkern-1.2mu}\\vcentcolon}}{\\mathop{\\char"2255}}');
defineMacro("\\Eqqcolon", '\\html@mathml{\\mathrel{=\\mathrel{\\mkern-1.2mu}\\dblcolon}}{\\mathop{\\char"3d\\char"2237}}');
defineMacro("\\eqcolon", '\\html@mathml{\\mathrel{\\mathrel{-}\\mathrel{\\mkern-1.2mu}\\vcentcolon}}{\\mathop{\\char"2239}}');
defineMacro("\\Eqcolon", '\\html@mathml{\\mathrel{\\mathrel{-}\\mathrel{\\mkern-1.2mu}\\dblcolon}}{\\mathop{\\char"2212\\char"2237}}');
defineMacro("\\colonapprox", '\\html@mathml{\\mathrel{\\vcentcolon\\mathrel{\\mkern-1.2mu}\\approx}}{\\mathop{\\char"3a\\char"2248}}');
defineMacro("\\Colonapprox", '\\html@mathml{\\mathrel{\\dblcolon\\mathrel{\\mkern-1.2mu}\\approx}}{\\mathop{\\char"2237\\char"2248}}');
defineMacro("\\colonsim", '\\html@mathml{\\mathrel{\\vcentcolon\\mathrel{\\mkern-1.2mu}\\sim}}{\\mathop{\\char"3a\\char"223c}}');
defineMacro("\\Colonsim", '\\html@mathml{\\mathrel{\\dblcolon\\mathrel{\\mkern-1.2mu}\\sim}}{\\mathop{\\char"2237\\char"223c}}');
defineMacro("\u2237", "\\dblcolon");
defineMacro("\u2239", "\\eqcolon");
defineMacro("\u2254", "\\coloneqq");
defineMacro("\u2255", "\\eqqcolon");
defineMacro("\u2A74", "\\Coloneqq");
defineMacro("\\ratio", "\\vcentcolon");
defineMacro("\\coloncolon", "\\dblcolon");
defineMacro("\\colonequals", "\\coloneqq");
defineMacro("\\coloncolonequals", "\\Coloneqq");
defineMacro("\\equalscolon", "\\eqqcolon");
defineMacro("\\equalscoloncolon", "\\Eqqcolon");
defineMacro("\\colonminus", "\\coloneq");
defineMacro("\\coloncolonminus", "\\Coloneq");
defineMacro("\\minuscolon", "\\eqcolon");
defineMacro("\\minuscoloncolon", "\\Eqcolon");
defineMacro("\\coloncolonapprox", "\\Colonapprox");
defineMacro("\\coloncolonsim", "\\Colonsim");
defineMacro("\\simcolon", "\\mathrel{\\sim\\mathrel{\\mkern-1.2mu}\\vcentcolon}");
defineMacro("\\simcoloncolon", "\\mathrel{\\sim\\mathrel{\\mkern-1.2mu}\\dblcolon}");
defineMacro("\\approxcolon", "\\mathrel{\\approx\\mathrel{\\mkern-1.2mu}\\vcentcolon}");
defineMacro("\\approxcoloncolon", "\\mathrel{\\approx\\mathrel{\\mkern-1.2mu}\\dblcolon}");
defineMacro("\\notni", "\\html@mathml{\\not\\ni}{\\mathrel{\\char`\u220C}}");
defineMacro("\\limsup", "\\DOTSB\\operatorname*{lim\\,sup}");
defineMacro("\\liminf", "\\DOTSB\\operatorname*{lim\\,inf}");
defineMacro("\\injlim", "\\DOTSB\\operatorname*{inj\\,lim}");
defineMacro("\\projlim", "\\DOTSB\\operatorname*{proj\\,lim}");
defineMacro("\\varlimsup", "\\DOTSB\\operatorname*{\\overline{lim}}");
defineMacro("\\varliminf", "\\DOTSB\\operatorname*{\\underline{lim}}");
defineMacro("\\varinjlim", "\\DOTSB\\operatorname*{\\underrightarrow{lim}}");
defineMacro("\\varprojlim", "\\DOTSB\\operatorname*{\\underleftarrow{lim}}");
defineMacro("\\gvertneqq", "\\html@mathml{\\@gvertneqq}{\u2269}");
defineMacro("\\lvertneqq", "\\html@mathml{\\@lvertneqq}{\u2268}");
defineMacro("\\ngeqq", "\\html@mathml{\\@ngeqq}{\u2271}");
defineMacro("\\ngeqslant", "\\html@mathml{\\@ngeqslant}{\u2271}");
defineMacro("\\nleqq", "\\html@mathml{\\@nleqq}{\u2270}");
defineMacro("\\nleqslant", "\\html@mathml{\\@nleqslant}{\u2270}");
defineMacro("\\nshortmid", "\\html@mathml{\\@nshortmid}{\u2224}");
defineMacro("\\nshortparallel", "\\html@mathml{\\@nshortparallel}{\u2226}");
defineMacro("\\nsubseteqq", "\\html@mathml{\\@nsubseteqq}{\u2288}");
defineMacro("\\nsupseteqq", "\\html@mathml{\\@nsupseteqq}{\u2289}");
defineMacro("\\varsubsetneq", "\\html@mathml{\\@varsubsetneq}{\u228A}");
defineMacro("\\varsubsetneqq", "\\html@mathml{\\@varsubsetneqq}{\u2ACB}");
defineMacro("\\varsupsetneq", "\\html@mathml{\\@varsupsetneq}{\u228B}");
defineMacro("\\varsupsetneqq", "\\html@mathml{\\@varsupsetneqq}{\u2ACC}");
defineMacro("\\imath", "\\html@mathml{\\@imath}{\u0131}");
defineMacro("\\jmath", "\\html@mathml{\\@jmath}{\u0237}");
defineMacro("\\llbracket", "\\html@mathml{\\mathopen{[\\mkern-3.2mu[}}{\\mathopen{\\char`\u27E6}}");
defineMacro("\\rrbracket", "\\html@mathml{\\mathclose{]\\mkern-3.2mu]}}{\\mathclose{\\char`\u27E7}}");
defineMacro("\u27E6", "\\llbracket");
defineMacro("\u27E7", "\\rrbracket");
defineMacro("\\lBrace", "\\html@mathml{\\mathopen{\\{\\mkern-3.2mu[}}{\\mathopen{\\char`\u2983}}");
defineMacro("\\rBrace", "\\html@mathml{\\mathclose{]\\mkern-3.2mu\\}}}{\\mathclose{\\char`\u2984}}");
defineMacro("\u2983", "\\lBrace");
defineMacro("\u2984", "\\rBrace");
defineMacro("\\minuso", "\\mathbin{\\html@mathml{{\\mathrlap{\\mathchoice{\\kern{0.145em}}{\\kern{0.145em}}{\\kern{0.1015em}}{\\kern{0.0725em}}\\circ}{-}}}{\\char`\u29B5}}");
defineMacro("\u29B5", "\\minuso");
defineMacro("\\darr", "\\downarrow");
defineMacro("\\dArr", "\\Downarrow");
defineMacro("\\Darr", "\\Downarrow");
defineMacro("\\lang", "\\langle");
defineMacro("\\rang", "\\rangle");
defineMacro("\\uarr", "\\uparrow");
defineMacro("\\uArr", "\\Uparrow");
defineMacro("\\Uarr", "\\Uparrow");
defineMacro("\\N", "\\mathbb{N}");
defineMacro("\\R", "\\mathbb{R}");
defineMacro("\\Z", "\\mathbb{Z}");
defineMacro("\\alef", "\\aleph");
defineMacro("\\alefsym", "\\aleph");
defineMacro("\\Alpha", "\\mathrm{A}");
defineMacro("\\Beta", "\\mathrm{B}");
defineMacro("\\bull", "\\bullet");
defineMacro("\\Chi", "\\mathrm{X}");
defineMacro("\\clubs", "\\clubsuit");
defineMacro("\\cnums", "\\mathbb{C}");
defineMacro("\\Complex", "\\mathbb{C}");
defineMacro("\\Dagger", "\\ddagger");
defineMacro("\\diamonds", "\\diamondsuit");
defineMacro("\\empty", "\\emptyset");
defineMacro("\\Epsilon", "\\mathrm{E}");
defineMacro("\\Eta", "\\mathrm{H}");
defineMacro("\\exist", "\\exists");
defineMacro("\\harr", "\\leftrightarrow");
defineMacro("\\hArr", "\\Leftrightarrow");
defineMacro("\\Harr", "\\Leftrightarrow");
defineMacro("\\hearts", "\\heartsuit");
defineMacro("\\image", "\\Im");
defineMacro("\\infin", "\\infty");
defineMacro("\\Iota", "\\mathrm{I}");
defineMacro("\\isin", "\\in");
defineMacro("\\Kappa", "\\mathrm{K}");
defineMacro("\\larr", "\\leftarrow");
defineMacro("\\lArr", "\\Leftarrow");
defineMacro("\\Larr", "\\Leftarrow");
defineMacro("\\lrarr", "\\leftrightarrow");
defineMacro("\\lrArr", "\\Leftrightarrow");
defineMacro("\\Lrarr", "\\Leftrightarrow");
defineMacro("\\Mu", "\\mathrm{M}");
defineMacro("\\natnums", "\\mathbb{N}");
defineMacro("\\Nu", "\\mathrm{N}");
defineMacro("\\Omicron", "\\mathrm{O}");
defineMacro("\\plusmn", "\\pm");
defineMacro("\\rarr", "\\rightarrow");
defineMacro("\\rArr", "\\Rightarrow");
defineMacro("\\Rarr", "\\Rightarrow");
defineMacro("\\real", "\\Re");
defineMacro("\\reals", "\\mathbb{R}");
defineMacro("\\Reals", "\\mathbb{R}");
defineMacro("\\Rho", "\\mathrm{P}");
defineMacro("\\sdot", "\\cdot");
defineMacro("\\sect", "\\S");
defineMacro("\\spades", "\\spadesuit");
defineMacro("\\sub", "\\subset");
defineMacro("\\sube", "\\subseteq");
defineMacro("\\supe", "\\supseteq");
defineMacro("\\Tau", "\\mathrm{T}");
defineMacro("\\thetasym", "\\vartheta");
defineMacro("\\weierp", "\\wp");
defineMacro("\\Zeta", "\\mathrm{Z}");
defineMacro("\\argmin", "\\DOTSB\\operatorname*{arg\\,min}");
defineMacro("\\argmax", "\\DOTSB\\operatorname*{arg\\,max}");
defineMacro("\\plim", "\\DOTSB\\mathop{\\operatorname{plim}}\\limits");
defineMacro("\\bra", "\\mathinner{\\langle{#1}|}");
defineMacro("\\ket", "\\mathinner{|{#1}\\rangle}");
defineMacro("\\braket", "\\mathinner{\\langle{#1}\\rangle}");
defineMacro("\\Bra", "\\left\\langle#1\\right|");
defineMacro("\\Ket", "\\left|#1\\right\\rangle");
var braketHelper = (one) => (context) => {
  var left = context.consumeArg().tokens;
  var middle = context.consumeArg().tokens;
  var middleDouble = context.consumeArg().tokens;
  var right = context.consumeArg().tokens;
  var oldMiddle = context.macros.get("|");
  var oldMiddleDouble = context.macros.get("\\|");
  context.macros.beginGroup();
  var midMacro = (double) => (context2) => {
    if (one) {
      context2.macros.set("|", oldMiddle);
      if (middleDouble.length) {
        context2.macros.set("\\|", oldMiddleDouble);
      }
    }
    var doubled = double;
    if (!double && middleDouble.length) {
      var nextToken = context2.future();
      if (nextToken.text === "|") {
        context2.popToken();
        doubled = true;
      }
    }
    return {
      tokens: doubled ? middleDouble : middle,
      numArgs: 0
    };
  };
  context.macros.set("|", midMacro(false));
  if (middleDouble.length) {
    context.macros.set("\\|", midMacro(true));
  }
  var arg = context.consumeArg().tokens;
  var expanded = context.expandTokens([
    ...right,
    ...arg,
    ...left
    // reversed
  ]);
  context.macros.endGroup();
  return {
    tokens: expanded.reverse(),
    numArgs: 0
  };
};
defineMacro("\\bra@ket", braketHelper(false));
defineMacro("\\bra@set", braketHelper(true));
defineMacro("\\Braket", "\\bra@ket{\\left\\langle}{\\,\\middle\\vert\\,}{\\,\\middle\\vert\\,}{\\right\\rangle}");
defineMacro("\\Set", "\\bra@set{\\left\\{\\:}{\\;\\middle\\vert\\;}{\\;\\middle\\Vert\\;}{\\:\\right\\}}");
defineMacro("\\set", "\\bra@set{\\{\\,}{\\mid}{}{\\,\\}}");
defineMacro("\\angln", "{\\angl n}");
defineMacro("\\blue", "\\textcolor{##6495ed}{#1}");
defineMacro("\\orange", "\\textcolor{##ffa500}{#1}");
defineMacro("\\pink", "\\textcolor{##ff00af}{#1}");
defineMacro("\\red", "\\textcolor{##df0030}{#1}");
defineMacro("\\green", "\\textcolor{##28ae7b}{#1}");
defineMacro("\\gray", "\\textcolor{gray}{#1}");
defineMacro("\\purple", "\\textcolor{##9d38bd}{#1}");
defineMacro("\\blueA", "\\textcolor{##ccfaff}{#1}");
defineMacro("\\blueB", "\\textcolor{##80f6ff}{#1}");
defineMacro("\\blueC", "\\textcolor{##63d9ea}{#1}");
defineMacro("\\blueD", "\\textcolor{##11accd}{#1}");
defineMacro("\\blueE", "\\textcolor{##0c7f99}{#1}");
defineMacro("\\tealA", "\\textcolor{##94fff5}{#1}");
defineMacro("\\tealB", "\\textcolor{##26edd5}{#1}");
defineMacro("\\tealC", "\\textcolor{##01d1c1}{#1}");
defineMacro("\\tealD", "\\textcolor{##01a995}{#1}");
defineMacro("\\tealE", "\\textcolor{##208170}{#1}");
defineMacro("\\greenA", "\\textcolor{##b6ffb0}{#1}");
defineMacro("\\greenB", "\\textcolor{##8af281}{#1}");
defineMacro("\\greenC", "\\textcolor{##74cf70}{#1}");
defineMacro("\\greenD", "\\textcolor{##1fab54}{#1}");
defineMacro("\\greenE", "\\textcolor{##0d923f}{#1}");
defineMacro("\\goldA", "\\textcolor{##ffd0a9}{#1}");
defineMacro("\\goldB", "\\textcolor{##ffbb71}{#1}");
defineMacro("\\goldC", "\\textcolor{##ff9c39}{#1}");
defineMacro("\\goldD", "\\textcolor{##e07d10}{#1}");
defineMacro("\\goldE", "\\textcolor{##a75a05}{#1}");
defineMacro("\\redA", "\\textcolor{##fca9a9}{#1}");
defineMacro("\\redB", "\\textcolor{##ff8482}{#1}");
defineMacro("\\redC", "\\textcolor{##f9685d}{#1}");
defineMacro("\\redD", "\\textcolor{##e84d39}{#1}");
defineMacro("\\redE", "\\textcolor{##bc2612}{#1}");
defineMacro("\\maroonA", "\\textcolor{##ffbde0}{#1}");
defineMacro("\\maroonB", "\\textcolor{##ff92c6}{#1}");
defineMacro("\\maroonC", "\\textcolor{##ed5fa6}{#1}");
defineMacro("\\maroonD", "\\textcolor{##ca337c}{#1}");
defineMacro("\\maroonE", "\\textcolor{##9e034e}{#1}");
defineMacro("\\purpleA", "\\textcolor{##ddd7ff}{#1}");
defineMacro("\\purpleB", "\\textcolor{##c6b9fc}{#1}");
defineMacro("\\purpleC", "\\textcolor{##aa87ff}{#1}");
defineMacro("\\purpleD", "\\textcolor{##7854ab}{#1}");
defineMacro("\\purpleE", "\\textcolor{##543b78}{#1}");
defineMacro("\\mintA", "\\textcolor{##f5f9e8}{#1}");
defineMacro("\\mintB", "\\textcolor{##edf2df}{#1}");
defineMacro("\\mintC", "\\textcolor{##e0e5cc}{#1}");
defineMacro("\\grayA", "\\textcolor{##f6f7f7}{#1}");
defineMacro("\\grayB", "\\textcolor{##f0f1f2}{#1}");
defineMacro("\\grayC", "\\textcolor{##e3e5e6}{#1}");
defineMacro("\\grayD", "\\textcolor{##d6d8da}{#1}");
defineMacro("\\grayE", "\\textcolor{##babec2}{#1}");
defineMacro("\\grayF", "\\textcolor{##888d93}{#1}");
defineMacro("\\grayG", "\\textcolor{##626569}{#1}");
defineMacro("\\grayH", "\\textcolor{##3b3e40}{#1}");
defineMacro("\\grayI", "\\textcolor{##21242c}{#1}");
defineMacro("\\kaBlue", "\\textcolor{##314453}{#1}");
defineMacro("\\kaGreen", "\\textcolor{##71B307}{#1}");
var implicitCommands = {
  "^": true,
  // Parser.js
  "_": true,
  // Parser.js
  "\\limits": true,
  // Parser.js
  "\\nolimits": true
  // Parser.js
};
var MacroExpander = class {
  constructor(input, settings, mode) {
    this.settings = void 0;
    this.expansionCount = void 0;
    this.lexer = void 0;
    this.macros = void 0;
    this.stack = void 0;
    this.mode = void 0;
    this.settings = settings;
    this.expansionCount = 0;
    this.feed(input);
    this.macros = new Namespace(macros, settings.macros);
    this.mode = mode;
    this.stack = [];
  }
  /**
   * Feed a new input string to the same MacroExpander
   * (with existing macros etc.).
   */
  feed(input) {
    this.lexer = new Lexer(input, this.settings);
  }
  /**
   * Switches between "text" and "math" modes.
   */
  switchMode(newMode) {
    this.mode = newMode;
  }
  /**
   * Start a new group nesting within all namespaces.
   */
  beginGroup() {
    this.macros.beginGroup();
  }
  /**
   * End current group nesting within all namespaces.
   */
  endGroup() {
    this.macros.endGroup();
  }
  /**
   * Ends all currently nested groups (if any), restoring values before the
   * groups began.  Useful in case of an error in the middle of parsing.
   */
  endGroups() {
    this.macros.endGroups();
  }
  /**
   * Returns the topmost token on the stack, without expanding it.
   * Similar in behavior to TeX's `\futurelet`.
   */
  future() {
    if (this.stack.length === 0) {
      this.pushToken(this.lexer.lex());
    }
    return this.stack[this.stack.length - 1];
  }
  /**
   * Remove and return the next unexpanded token.
   */
  popToken() {
    this.future();
    return this.stack.pop();
  }
  /**
   * Add a given token to the token stack.  In particular, this get be used
   * to put back a token returned from one of the other methods.
   */
  pushToken(token) {
    this.stack.push(token);
  }
  /**
   * Append an array of tokens to the token stack.
   */
  pushTokens(tokens) {
    this.stack.push(...tokens);
  }
  /**
   * Find an macro argument without expanding tokens and append the array of
   * tokens to the token stack. Uses Token as a container for the result.
   */
  scanArgument(isOptional) {
    var start;
    var end;
    var tokens;
    if (isOptional) {
      this.consumeSpaces();
      if (this.future().text !== "[") {
        return null;
      }
      start = this.popToken();
      ({
        tokens,
        end
      } = this.consumeArg(["]"]));
    } else {
      ({
        tokens,
        start,
        end
      } = this.consumeArg());
    }
    this.pushToken(new Token("EOF", end.loc));
    this.pushTokens(tokens);
    return start.range(end, "");
  }
  /**
   * Consume all following space tokens, without expansion.
   */
  consumeSpaces() {
    for (; ; ) {
      var token = this.future();
      if (token.text === " ") {
        this.stack.pop();
      } else {
        break;
      }
    }
  }
  /**
   * Consume an argument from the token stream, and return the resulting array
   * of tokens and start/end token.
   */
  consumeArg(delims) {
    var tokens = [];
    var isDelimited = delims && delims.length > 0;
    if (!isDelimited) {
      this.consumeSpaces();
    }
    var start = this.future();
    var tok;
    var depth = 0;
    var match = 0;
    do {
      tok = this.popToken();
      tokens.push(tok);
      if (tok.text === "{") {
        ++depth;
      } else if (tok.text === "}") {
        --depth;
        if (depth === -1) {
          throw new ParseError("Extra }", tok);
        }
      } else if (tok.text === "EOF") {
        throw new ParseError("Unexpected end of input in a macro argument, expected '" + (delims && isDelimited ? delims[match] : "}") + "'", tok);
      }
      if (delims && isDelimited) {
        if ((depth === 0 || depth === 1 && delims[match] === "{") && tok.text === delims[match]) {
          ++match;
          if (match === delims.length) {
            tokens.splice(-match, match);
            break;
          }
        } else {
          match = 0;
        }
      }
    } while (depth !== 0 || isDelimited);
    if (start.text === "{" && tokens[tokens.length - 1].text === "}") {
      tokens.pop();
      tokens.shift();
    }
    tokens.reverse();
    return {
      tokens,
      start,
      end: tok
    };
  }
  /**
   * Consume the specified number of (delimited) arguments from the token
   * stream and return the resulting array of arguments.
   */
  consumeArgs(numArgs, delimiters2) {
    if (delimiters2) {
      if (delimiters2.length !== numArgs + 1) {
        throw new ParseError("The length of delimiters doesn't match the number of args!");
      }
      var delims = delimiters2[0];
      for (var i = 0; i < delims.length; i++) {
        var tok = this.popToken();
        if (delims[i] !== tok.text) {
          throw new ParseError("Use of the macro doesn't match its definition", tok);
        }
      }
    }
    var args = [];
    for (var _i = 0; _i < numArgs; _i++) {
      args.push(this.consumeArg(delimiters2 && delimiters2[_i + 1]).tokens);
    }
    return args;
  }
  /**
   * Increment `expansionCount` by the specified amount.
   * Throw an error if it exceeds `maxExpand`.
   */
  countExpansion(amount3) {
    this.expansionCount += amount3;
    if (this.expansionCount > this.settings.maxExpand) {
      throw new ParseError("Too many expansions: infinite loop or need to increase maxExpand setting");
    }
  }
  /**
   * Expand the next token only once if possible.
   *
   * If the token is expanded, the resulting tokens will be pushed onto
   * the stack in reverse order, and the number of such tokens will be
   * returned.  This number might be zero or positive.
   *
   * If not, the return value is `false`, and the next token remains at the
   * top of the stack.
   *
   * In either case, the next token will be on the top of the stack,
   * or the stack will be empty (in case of empty expansion
   * and no other tokens).
   *
   * Used to implement `expandAfterFuture` and `expandNextToken`.
   *
   * If expandableOnly, only expandable tokens are expanded and
   * an undefined control sequence results in an error.
   */
  expandOnce(expandableOnly) {
    var topToken = this.popToken();
    var name = topToken.text;
    var expansion = !topToken.noexpand ? this._getExpansion(name) : null;
    if (expansion == null || expandableOnly && expansion.unexpandable) {
      if (expandableOnly && expansion == null && name[0] === "\\" && !this.isDefined(name)) {
        throw new ParseError("Undefined control sequence: " + name);
      }
      this.pushToken(topToken);
      return false;
    }
    this.countExpansion(1);
    var tokens = expansion.tokens;
    var args = this.consumeArgs(expansion.numArgs, expansion.delimiters);
    if (expansion.numArgs) {
      tokens = tokens.slice();
      for (var i = tokens.length - 1; i >= 0; --i) {
        var tok = tokens[i];
        if (tok.text === "#") {
          if (i === 0) {
            throw new ParseError("Incomplete placeholder at end of macro body", tok);
          }
          tok = tokens[--i];
          if (tok.text === "#") {
            tokens.splice(i + 1, 1);
          } else if (/^[1-9]$/.test(tok.text)) {
            tokens.splice(i, 2, ...args[+tok.text - 1]);
          } else {
            throw new ParseError("Not a valid argument number", tok);
          }
        }
      }
    }
    this.pushTokens(tokens);
    return tokens.length;
  }
  /**
   * Expand the next token only once (if possible), and return the resulting
   * top token on the stack (without removing anything from the stack).
   * Similar in behavior to TeX's `\expandafter\futurelet`.
   * Equivalent to expandOnce() followed by future().
   */
  expandAfterFuture() {
    this.expandOnce();
    return this.future();
  }
  /**
   * Recursively expand first token, then return first non-expandable token.
   */
  expandNextToken() {
    for (; ; ) {
      if (this.expandOnce() === false) {
        var token = this.stack.pop();
        if (token.treatAsRelax) {
          token.text = "\\relax";
        }
        return token;
      }
    }
    throw new Error();
  }
  /**
   * Fully expand the given macro name and return the resulting list of
   * tokens, or return `undefined` if no such macro is defined.
   */
  expandMacro(name) {
    return this.macros.has(name) ? this.expandTokens([new Token(name)]) : void 0;
  }
  /**
   * Fully expand the given token stream and return the resulting list of
   * tokens.  Note that the input tokens are in reverse order, but the
   * output tokens are in forward order.
   */
  expandTokens(tokens) {
    var output7 = [];
    var oldStackLength = this.stack.length;
    this.pushTokens(tokens);
    while (this.stack.length > oldStackLength) {
      if (this.expandOnce(true) === false) {
        var token = this.stack.pop();
        if (token.treatAsRelax) {
          token.noexpand = false;
          token.treatAsRelax = false;
        }
        output7.push(token);
      }
    }
    this.countExpansion(output7.length);
    return output7;
  }
  /**
   * Fully expand the given macro name and return the result as a string,
   * or return `undefined` if no such macro is defined.
   */
  expandMacroAsText(name) {
    var tokens = this.expandMacro(name);
    if (tokens) {
      return tokens.map((token) => token.text).join("");
    } else {
      return tokens;
    }
  }
  /**
   * Returns the expanded macro as a reversed array of tokens and a macro
   * argument count.  Or returns `null` if no such macro.
   */
  _getExpansion(name) {
    var definition = this.macros.get(name);
    if (definition == null) {
      return definition;
    }
    if (name.length === 1) {
      var catcode = this.lexer.catcodes[name];
      if (catcode != null && catcode !== 13) {
        return;
      }
    }
    var expansion = typeof definition === "function" ? definition(this) : definition;
    if (typeof expansion === "string") {
      var numArgs = 0;
      if (expansion.indexOf("#") !== -1) {
        var stripped = expansion.replace(/##/g, "");
        while (stripped.indexOf("#" + (numArgs + 1)) !== -1) {
          ++numArgs;
        }
      }
      var bodyLexer = new Lexer(expansion, this.settings);
      var tokens = [];
      var tok = bodyLexer.lex();
      while (tok.text !== "EOF") {
        tokens.push(tok);
        tok = bodyLexer.lex();
      }
      tokens.reverse();
      var expanded = {
        tokens,
        numArgs
      };
      return expanded;
    }
    return expansion;
  }
  /**
   * Determine whether a command is currently "defined" (has some
   * functionality), meaning that it's a macro (in the current group),
   * a function, a symbol, or one of the special commands listed in
   * `implicitCommands`.
   */
  isDefined(name) {
    return this.macros.has(name) || functions.hasOwnProperty(name) || symbols.math.hasOwnProperty(name) || symbols.text.hasOwnProperty(name) || implicitCommands.hasOwnProperty(name);
  }
  /**
   * Determine whether a command is expandable.
   */
  isExpandable(name) {
    var macro = this.macros.get(name);
    return macro != null ? typeof macro === "string" || typeof macro === "function" || !macro.unexpandable : functions.hasOwnProperty(name) && !functions[name].primitive;
  }
};
var unicodeSubRegEx = /^[₊₋₌₍₎₀₁₂₃₄₅₆₇₈₉ₐₑₕᵢⱼₖₗₘₙₒₚᵣₛₜᵤᵥₓᵦᵧᵨᵩᵪ]/;
var uSubsAndSups = Object.freeze({
  "\u208A": "+",
  "\u208B": "-",
  "\u208C": "=",
  "\u208D": "(",
  "\u208E": ")",
  "\u2080": "0",
  "\u2081": "1",
  "\u2082": "2",
  "\u2083": "3",
  "\u2084": "4",
  "\u2085": "5",
  "\u2086": "6",
  "\u2087": "7",
  "\u2088": "8",
  "\u2089": "9",
  "\u2090": "a",
  "\u2091": "e",
  "\u2095": "h",
  "\u1D62": "i",
  "\u2C7C": "j",
  "\u2096": "k",
  "\u2097": "l",
  "\u2098": "m",
  "\u2099": "n",
  "\u2092": "o",
  "\u209A": "p",
  "\u1D63": "r",
  "\u209B": "s",
  "\u209C": "t",
  "\u1D64": "u",
  "\u1D65": "v",
  "\u2093": "x",
  "\u1D66": "\u03B2",
  "\u1D67": "\u03B3",
  "\u1D68": "\u03C1",
  "\u1D69": "\u03D5",
  "\u1D6A": "\u03C7",
  "\u207A": "+",
  "\u207B": "-",
  "\u207C": "=",
  "\u207D": "(",
  "\u207E": ")",
  "\u2070": "0",
  "\xB9": "1",
  "\xB2": "2",
  "\xB3": "3",
  "\u2074": "4",
  "\u2075": "5",
  "\u2076": "6",
  "\u2077": "7",
  "\u2078": "8",
  "\u2079": "9",
  "\u1D2C": "A",
  "\u1D2E": "B",
  "\u1D30": "D",
  "\u1D31": "E",
  "\u1D33": "G",
  "\u1D34": "H",
  "\u1D35": "I",
  "\u1D36": "J",
  "\u1D37": "K",
  "\u1D38": "L",
  "\u1D39": "M",
  "\u1D3A": "N",
  "\u1D3C": "O",
  "\u1D3E": "P",
  "\u1D3F": "R",
  "\u1D40": "T",
  "\u1D41": "U",
  "\u2C7D": "V",
  "\u1D42": "W",
  "\u1D43": "a",
  "\u1D47": "b",
  "\u1D9C": "c",
  "\u1D48": "d",
  "\u1D49": "e",
  "\u1DA0": "f",
  "\u1D4D": "g",
  "\u02B0": "h",
  "\u2071": "i",
  "\u02B2": "j",
  "\u1D4F": "k",
  "\u02E1": "l",
  "\u1D50": "m",
  "\u207F": "n",
  "\u1D52": "o",
  "\u1D56": "p",
  "\u02B3": "r",
  "\u02E2": "s",
  "\u1D57": "t",
  "\u1D58": "u",
  "\u1D5B": "v",
  "\u02B7": "w",
  "\u02E3": "x",
  "\u02B8": "y",
  "\u1DBB": "z",
  "\u1D5D": "\u03B2",
  "\u1D5E": "\u03B3",
  "\u1D5F": "\u03B4",
  "\u1D60": "\u03D5",
  "\u1D61": "\u03C7",
  "\u1DBF": "\u03B8"
});
var unicodeAccents = {
  "\u0301": {
    "text": "\\'",
    "math": "\\acute"
  },
  "\u0300": {
    "text": "\\`",
    "math": "\\grave"
  },
  "\u0308": {
    "text": '\\"',
    "math": "\\ddot"
  },
  "\u0303": {
    "text": "\\~",
    "math": "\\tilde"
  },
  "\u0304": {
    "text": "\\=",
    "math": "\\bar"
  },
  "\u0306": {
    "text": "\\u",
    "math": "\\breve"
  },
  "\u030C": {
    "text": "\\v",
    "math": "\\check"
  },
  "\u0302": {
    "text": "\\^",
    "math": "\\hat"
  },
  "\u0307": {
    "text": "\\.",
    "math": "\\dot"
  },
  "\u030A": {
    "text": "\\r",
    "math": "\\mathring"
  },
  "\u030B": {
    "text": "\\H"
  },
  "\u0327": {
    "text": "\\c"
  }
};
var unicodeSymbols = {
  "\xE1": "a\u0301",
  "\xE0": "a\u0300",
  "\xE4": "a\u0308",
  "\u01DF": "a\u0308\u0304",
  "\xE3": "a\u0303",
  "\u0101": "a\u0304",
  "\u0103": "a\u0306",
  "\u1EAF": "a\u0306\u0301",
  "\u1EB1": "a\u0306\u0300",
  "\u1EB5": "a\u0306\u0303",
  "\u01CE": "a\u030C",
  "\xE2": "a\u0302",
  "\u1EA5": "a\u0302\u0301",
  "\u1EA7": "a\u0302\u0300",
  "\u1EAB": "a\u0302\u0303",
  "\u0227": "a\u0307",
  "\u01E1": "a\u0307\u0304",
  "\xE5": "a\u030A",
  "\u01FB": "a\u030A\u0301",
  "\u1E03": "b\u0307",
  "\u0107": "c\u0301",
  "\u1E09": "c\u0327\u0301",
  "\u010D": "c\u030C",
  "\u0109": "c\u0302",
  "\u010B": "c\u0307",
  "\xE7": "c\u0327",
  "\u010F": "d\u030C",
  "\u1E0B": "d\u0307",
  "\u1E11": "d\u0327",
  "\xE9": "e\u0301",
  "\xE8": "e\u0300",
  "\xEB": "e\u0308",
  "\u1EBD": "e\u0303",
  "\u0113": "e\u0304",
  "\u1E17": "e\u0304\u0301",
  "\u1E15": "e\u0304\u0300",
  "\u0115": "e\u0306",
  "\u1E1D": "e\u0327\u0306",
  "\u011B": "e\u030C",
  "\xEA": "e\u0302",
  "\u1EBF": "e\u0302\u0301",
  "\u1EC1": "e\u0302\u0300",
  "\u1EC5": "e\u0302\u0303",
  "\u0117": "e\u0307",
  "\u0229": "e\u0327",
  "\u1E1F": "f\u0307",
  "\u01F5": "g\u0301",
  "\u1E21": "g\u0304",
  "\u011F": "g\u0306",
  "\u01E7": "g\u030C",
  "\u011D": "g\u0302",
  "\u0121": "g\u0307",
  "\u0123": "g\u0327",
  "\u1E27": "h\u0308",
  "\u021F": "h\u030C",
  "\u0125": "h\u0302",
  "\u1E23": "h\u0307",
  "\u1E29": "h\u0327",
  "\xED": "i\u0301",
  "\xEC": "i\u0300",
  "\xEF": "i\u0308",
  "\u1E2F": "i\u0308\u0301",
  "\u0129": "i\u0303",
  "\u012B": "i\u0304",
  "\u012D": "i\u0306",
  "\u01D0": "i\u030C",
  "\xEE": "i\u0302",
  "\u01F0": "j\u030C",
  "\u0135": "j\u0302",
  "\u1E31": "k\u0301",
  "\u01E9": "k\u030C",
  "\u0137": "k\u0327",
  "\u013A": "l\u0301",
  "\u013E": "l\u030C",
  "\u013C": "l\u0327",
  "\u1E3F": "m\u0301",
  "\u1E41": "m\u0307",
  "\u0144": "n\u0301",
  "\u01F9": "n\u0300",
  "\xF1": "n\u0303",
  "\u0148": "n\u030C",
  "\u1E45": "n\u0307",
  "\u0146": "n\u0327",
  "\xF3": "o\u0301",
  "\xF2": "o\u0300",
  "\xF6": "o\u0308",
  "\u022B": "o\u0308\u0304",
  "\xF5": "o\u0303",
  "\u1E4D": "o\u0303\u0301",
  "\u1E4F": "o\u0303\u0308",
  "\u022D": "o\u0303\u0304",
  "\u014D": "o\u0304",
  "\u1E53": "o\u0304\u0301",
  "\u1E51": "o\u0304\u0300",
  "\u014F": "o\u0306",
  "\u01D2": "o\u030C",
  "\xF4": "o\u0302",
  "\u1ED1": "o\u0302\u0301",
  "\u1ED3": "o\u0302\u0300",
  "\u1ED7": "o\u0302\u0303",
  "\u022F": "o\u0307",
  "\u0231": "o\u0307\u0304",
  "\u0151": "o\u030B",
  "\u1E55": "p\u0301",
  "\u1E57": "p\u0307",
  "\u0155": "r\u0301",
  "\u0159": "r\u030C",
  "\u1E59": "r\u0307",
  "\u0157": "r\u0327",
  "\u015B": "s\u0301",
  "\u1E65": "s\u0301\u0307",
  "\u0161": "s\u030C",
  "\u1E67": "s\u030C\u0307",
  "\u015D": "s\u0302",
  "\u1E61": "s\u0307",
  "\u015F": "s\u0327",
  "\u1E97": "t\u0308",
  "\u0165": "t\u030C",
  "\u1E6B": "t\u0307",
  "\u0163": "t\u0327",
  "\xFA": "u\u0301",
  "\xF9": "u\u0300",
  "\xFC": "u\u0308",
  "\u01D8": "u\u0308\u0301",
  "\u01DC": "u\u0308\u0300",
  "\u01D6": "u\u0308\u0304",
  "\u01DA": "u\u0308\u030C",
  "\u0169": "u\u0303",
  "\u1E79": "u\u0303\u0301",
  "\u016B": "u\u0304",
  "\u1E7B": "u\u0304\u0308",
  "\u016D": "u\u0306",
  "\u01D4": "u\u030C",
  "\xFB": "u\u0302",
  "\u016F": "u\u030A",
  "\u0171": "u\u030B",
  "\u1E7D": "v\u0303",
  "\u1E83": "w\u0301",
  "\u1E81": "w\u0300",
  "\u1E85": "w\u0308",
  "\u0175": "w\u0302",
  "\u1E87": "w\u0307",
  "\u1E98": "w\u030A",
  "\u1E8D": "x\u0308",
  "\u1E8B": "x\u0307",
  "\xFD": "y\u0301",
  "\u1EF3": "y\u0300",
  "\xFF": "y\u0308",
  "\u1EF9": "y\u0303",
  "\u0233": "y\u0304",
  "\u0177": "y\u0302",
  "\u1E8F": "y\u0307",
  "\u1E99": "y\u030A",
  "\u017A": "z\u0301",
  "\u017E": "z\u030C",
  "\u1E91": "z\u0302",
  "\u017C": "z\u0307",
  "\xC1": "A\u0301",
  "\xC0": "A\u0300",
  "\xC4": "A\u0308",
  "\u01DE": "A\u0308\u0304",
  "\xC3": "A\u0303",
  "\u0100": "A\u0304",
  "\u0102": "A\u0306",
  "\u1EAE": "A\u0306\u0301",
  "\u1EB0": "A\u0306\u0300",
  "\u1EB4": "A\u0306\u0303",
  "\u01CD": "A\u030C",
  "\xC2": "A\u0302",
  "\u1EA4": "A\u0302\u0301",
  "\u1EA6": "A\u0302\u0300",
  "\u1EAA": "A\u0302\u0303",
  "\u0226": "A\u0307",
  "\u01E0": "A\u0307\u0304",
  "\xC5": "A\u030A",
  "\u01FA": "A\u030A\u0301",
  "\u1E02": "B\u0307",
  "\u0106": "C\u0301",
  "\u1E08": "C\u0327\u0301",
  "\u010C": "C\u030C",
  "\u0108": "C\u0302",
  "\u010A": "C\u0307",
  "\xC7": "C\u0327",
  "\u010E": "D\u030C",
  "\u1E0A": "D\u0307",
  "\u1E10": "D\u0327",
  "\xC9": "E\u0301",
  "\xC8": "E\u0300",
  "\xCB": "E\u0308",
  "\u1EBC": "E\u0303",
  "\u0112": "E\u0304",
  "\u1E16": "E\u0304\u0301",
  "\u1E14": "E\u0304\u0300",
  "\u0114": "E\u0306",
  "\u1E1C": "E\u0327\u0306",
  "\u011A": "E\u030C",
  "\xCA": "E\u0302",
  "\u1EBE": "E\u0302\u0301",
  "\u1EC0": "E\u0302\u0300",
  "\u1EC4": "E\u0302\u0303",
  "\u0116": "E\u0307",
  "\u0228": "E\u0327",
  "\u1E1E": "F\u0307",
  "\u01F4": "G\u0301",
  "\u1E20": "G\u0304",
  "\u011E": "G\u0306",
  "\u01E6": "G\u030C",
  "\u011C": "G\u0302",
  "\u0120": "G\u0307",
  "\u0122": "G\u0327",
  "\u1E26": "H\u0308",
  "\u021E": "H\u030C",
  "\u0124": "H\u0302",
  "\u1E22": "H\u0307",
  "\u1E28": "H\u0327",
  "\xCD": "I\u0301",
  "\xCC": "I\u0300",
  "\xCF": "I\u0308",
  "\u1E2E": "I\u0308\u0301",
  "\u0128": "I\u0303",
  "\u012A": "I\u0304",
  "\u012C": "I\u0306",
  "\u01CF": "I\u030C",
  "\xCE": "I\u0302",
  "\u0130": "I\u0307",
  "\u0134": "J\u0302",
  "\u1E30": "K\u0301",
  "\u01E8": "K\u030C",
  "\u0136": "K\u0327",
  "\u0139": "L\u0301",
  "\u013D": "L\u030C",
  "\u013B": "L\u0327",
  "\u1E3E": "M\u0301",
  "\u1E40": "M\u0307",
  "\u0143": "N\u0301",
  "\u01F8": "N\u0300",
  "\xD1": "N\u0303",
  "\u0147": "N\u030C",
  "\u1E44": "N\u0307",
  "\u0145": "N\u0327",
  "\xD3": "O\u0301",
  "\xD2": "O\u0300",
  "\xD6": "O\u0308",
  "\u022A": "O\u0308\u0304",
  "\xD5": "O\u0303",
  "\u1E4C": "O\u0303\u0301",
  "\u1E4E": "O\u0303\u0308",
  "\u022C": "O\u0303\u0304",
  "\u014C": "O\u0304",
  "\u1E52": "O\u0304\u0301",
  "\u1E50": "O\u0304\u0300",
  "\u014E": "O\u0306",
  "\u01D1": "O\u030C",
  "\xD4": "O\u0302",
  "\u1ED0": "O\u0302\u0301",
  "\u1ED2": "O\u0302\u0300",
  "\u1ED6": "O\u0302\u0303",
  "\u022E": "O\u0307",
  "\u0230": "O\u0307\u0304",
  "\u0150": "O\u030B",
  "\u1E54": "P\u0301",
  "\u1E56": "P\u0307",
  "\u0154": "R\u0301",
  "\u0158": "R\u030C",
  "\u1E58": "R\u0307",
  "\u0156": "R\u0327",
  "\u015A": "S\u0301",
  "\u1E64": "S\u0301\u0307",
  "\u0160": "S\u030C",
  "\u1E66": "S\u030C\u0307",
  "\u015C": "S\u0302",
  "\u1E60": "S\u0307",
  "\u015E": "S\u0327",
  "\u0164": "T\u030C",
  "\u1E6A": "T\u0307",
  "\u0162": "T\u0327",
  "\xDA": "U\u0301",
  "\xD9": "U\u0300",
  "\xDC": "U\u0308",
  "\u01D7": "U\u0308\u0301",
  "\u01DB": "U\u0308\u0300",
  "\u01D5": "U\u0308\u0304",
  "\u01D9": "U\u0308\u030C",
  "\u0168": "U\u0303",
  "\u1E78": "U\u0303\u0301",
  "\u016A": "U\u0304",
  "\u1E7A": "U\u0304\u0308",
  "\u016C": "U\u0306",
  "\u01D3": "U\u030C",
  "\xDB": "U\u0302",
  "\u016E": "U\u030A",
  "\u0170": "U\u030B",
  "\u1E7C": "V\u0303",
  "\u1E82": "W\u0301",
  "\u1E80": "W\u0300",
  "\u1E84": "W\u0308",
  "\u0174": "W\u0302",
  "\u1E86": "W\u0307",
  "\u1E8C": "X\u0308",
  "\u1E8A": "X\u0307",
  "\xDD": "Y\u0301",
  "\u1EF2": "Y\u0300",
  "\u0178": "Y\u0308",
  "\u1EF8": "Y\u0303",
  "\u0232": "Y\u0304",
  "\u0176": "Y\u0302",
  "\u1E8E": "Y\u0307",
  "\u0179": "Z\u0301",
  "\u017D": "Z\u030C",
  "\u1E90": "Z\u0302",
  "\u017B": "Z\u0307",
  "\u03AC": "\u03B1\u0301",
  "\u1F70": "\u03B1\u0300",
  "\u1FB1": "\u03B1\u0304",
  "\u1FB0": "\u03B1\u0306",
  "\u03AD": "\u03B5\u0301",
  "\u1F72": "\u03B5\u0300",
  "\u03AE": "\u03B7\u0301",
  "\u1F74": "\u03B7\u0300",
  "\u03AF": "\u03B9\u0301",
  "\u1F76": "\u03B9\u0300",
  "\u03CA": "\u03B9\u0308",
  "\u0390": "\u03B9\u0308\u0301",
  "\u1FD2": "\u03B9\u0308\u0300",
  "\u1FD1": "\u03B9\u0304",
  "\u1FD0": "\u03B9\u0306",
  "\u03CC": "\u03BF\u0301",
  "\u1F78": "\u03BF\u0300",
  "\u03CD": "\u03C5\u0301",
  "\u1F7A": "\u03C5\u0300",
  "\u03CB": "\u03C5\u0308",
  "\u03B0": "\u03C5\u0308\u0301",
  "\u1FE2": "\u03C5\u0308\u0300",
  "\u1FE1": "\u03C5\u0304",
  "\u1FE0": "\u03C5\u0306",
  "\u03CE": "\u03C9\u0301",
  "\u1F7C": "\u03C9\u0300",
  "\u038E": "\u03A5\u0301",
  "\u1FEA": "\u03A5\u0300",
  "\u03AB": "\u03A5\u0308",
  "\u1FE9": "\u03A5\u0304",
  "\u1FE8": "\u03A5\u0306",
  "\u038F": "\u03A9\u0301",
  "\u1FFA": "\u03A9\u0300"
};
var Parser = class _Parser {
  constructor(input, settings) {
    this.mode = void 0;
    this.gullet = void 0;
    this.settings = void 0;
    this.leftrightDepth = void 0;
    this.nextToken = void 0;
    this.mode = "math";
    this.gullet = new MacroExpander(input, settings, this.mode);
    this.settings = settings;
    this.leftrightDepth = 0;
  }
  /**
   * Checks a result to make sure it has the right type, and throws an
   * appropriate error otherwise.
   */
  expect(text5, consume) {
    if (consume === void 0) {
      consume = true;
    }
    if (this.fetch().text !== text5) {
      throw new ParseError("Expected '" + text5 + "', got '" + this.fetch().text + "'", this.fetch());
    }
    if (consume) {
      this.consume();
    }
  }
  /**
   * Discards the current lookahead token, considering it consumed.
   */
  consume() {
    this.nextToken = null;
  }
  /**
   * Return the current lookahead token, or if there isn't one (at the
   * beginning, or if the previous lookahead token was consume()d),
   * fetch the next token as the new lookahead token and return it.
   */
  fetch() {
    if (this.nextToken == null) {
      this.nextToken = this.gullet.expandNextToken();
    }
    return this.nextToken;
  }
  /**
   * Switches between "text" and "math" modes.
   */
  switchMode(newMode) {
    this.mode = newMode;
    this.gullet.switchMode(newMode);
  }
  /**
   * Main parsing function, which parses an entire input.
   */
  parse() {
    if (!this.settings.globalGroup) {
      this.gullet.beginGroup();
    }
    if (this.settings.colorIsTextColor) {
      this.gullet.macros.set("\\color", "\\textcolor");
    }
    try {
      var parse = this.parseExpression(false);
      this.expect("EOF");
      if (!this.settings.globalGroup) {
        this.gullet.endGroup();
      }
      return parse;
    } finally {
      this.gullet.endGroups();
    }
  }
  /**
   * Fully parse a separate sequence of tokens as a separate job.
   * Tokens should be specified in reverse order, as in a MacroDefinition.
   */
  subparse(tokens) {
    var oldToken = this.nextToken;
    this.consume();
    this.gullet.pushToken(new Token("}"));
    this.gullet.pushTokens(tokens);
    var parse = this.parseExpression(false);
    this.expect("}");
    this.nextToken = oldToken;
    return parse;
  }
  /**
   * Parses an "expression", which is a list of atoms.
   *
   * `breakOnInfix`: Should the parsing stop when we hit infix nodes? This
   *                 happens when functions have higher precedence han infix
   *                 nodes in implicit parses.
   *
   * `breakOnTokenText`: The text of the token that the expression should end
   *                     with, or `null` if something else should end the
   *                     expression.
   */
  parseExpression(breakOnInfix, breakOnTokenText) {
    var body = [];
    while (true) {
      if (this.mode === "math") {
        this.consumeSpaces();
      }
      var lex = this.fetch();
      if (_Parser.endOfExpression.indexOf(lex.text) !== -1) {
        break;
      }
      if (breakOnTokenText && lex.text === breakOnTokenText) {
        break;
      }
      if (breakOnInfix && functions[lex.text] && functions[lex.text].infix) {
        break;
      }
      var atom = this.parseAtom(breakOnTokenText);
      if (!atom) {
        break;
      } else if (atom.type === "internal") {
        continue;
      }
      body.push(atom);
    }
    if (this.mode === "text") {
      this.formLigatures(body);
    }
    return this.handleInfixNodes(body);
  }
  /**
   * Rewrites infix operators such as \over with corresponding commands such
   * as \frac.
   *
   * There can only be one infix operator per group.  If there's more than one
   * then the expression is ambiguous.  This can be resolved by adding {}.
   */
  handleInfixNodes(body) {
    var overIndex = -1;
    var funcName;
    for (var i = 0; i < body.length; i++) {
      if (body[i].type === "infix") {
        if (overIndex !== -1) {
          throw new ParseError("only one infix operator per group", body[i].token);
        }
        overIndex = i;
        funcName = body[i].replaceWith;
      }
    }
    if (overIndex !== -1 && funcName) {
      var numerNode;
      var denomNode;
      var numerBody = body.slice(0, overIndex);
      var denomBody = body.slice(overIndex + 1);
      if (numerBody.length === 1 && numerBody[0].type === "ordgroup") {
        numerNode = numerBody[0];
      } else {
        numerNode = {
          type: "ordgroup",
          mode: this.mode,
          body: numerBody
        };
      }
      if (denomBody.length === 1 && denomBody[0].type === "ordgroup") {
        denomNode = denomBody[0];
      } else {
        denomNode = {
          type: "ordgroup",
          mode: this.mode,
          body: denomBody
        };
      }
      var node;
      if (funcName === "\\\\abovefrac") {
        node = this.callFunction(funcName, [numerNode, body[overIndex], denomNode], []);
      } else {
        node = this.callFunction(funcName, [numerNode, denomNode], []);
      }
      return [node];
    } else {
      return body;
    }
  }
  /**
   * Handle a subscript or superscript with nice errors.
   */
  handleSupSubscript(name) {
    var symbolToken = this.fetch();
    var symbol = symbolToken.text;
    this.consume();
    this.consumeSpaces();
    var group;
    do {
      var _group;
      group = this.parseGroup(name);
    } while (((_group = group) == null ? void 0 : _group.type) === "internal");
    if (!group) {
      throw new ParseError("Expected group after '" + symbol + "'", symbolToken);
    }
    return group;
  }
  /**
   * Converts the textual input of an unsupported command into a text node
   * contained within a color node whose color is determined by errorColor
   */
  formatUnsupportedCmd(text5) {
    var textordArray = [];
    for (var i = 0; i < text5.length; i++) {
      textordArray.push({
        type: "textord",
        mode: "text",
        text: text5[i]
      });
    }
    var textNode = {
      type: "text",
      mode: this.mode,
      body: textordArray
    };
    var colorNode = {
      type: "color",
      mode: this.mode,
      color: this.settings.errorColor,
      body: [textNode]
    };
    return colorNode;
  }
  /**
   * Parses a group with optional super/subscripts.
   */
  parseAtom(breakOnTokenText) {
    var base2 = this.parseGroup("atom", breakOnTokenText);
    if ((base2 == null ? void 0 : base2.type) === "internal") {
      return base2;
    }
    if (this.mode === "text") {
      return base2;
    }
    var superscript;
    var subscript;
    while (true) {
      this.consumeSpaces();
      var lex = this.fetch();
      if (lex.text === "\\limits" || lex.text === "\\nolimits") {
        if (base2 && base2.type === "op") {
          var limits = lex.text === "\\limits";
          base2.limits = limits;
          base2.alwaysHandleSupSub = true;
        } else if (base2 && base2.type === "operatorname") {
          if (base2.alwaysHandleSupSub) {
            base2.limits = lex.text === "\\limits";
          }
        } else {
          throw new ParseError("Limit controls must follow a math operator", lex);
        }
        this.consume();
      } else if (lex.text === "^") {
        if (superscript) {
          throw new ParseError("Double superscript", lex);
        }
        superscript = this.handleSupSubscript("superscript");
      } else if (lex.text === "_") {
        if (subscript) {
          throw new ParseError("Double subscript", lex);
        }
        subscript = this.handleSupSubscript("subscript");
      } else if (lex.text === "'") {
        if (superscript) {
          throw new ParseError("Double superscript", lex);
        }
        var prime = {
          type: "textord",
          mode: this.mode,
          text: "\\prime"
        };
        var primes = [prime];
        this.consume();
        while (this.fetch().text === "'") {
          primes.push(prime);
          this.consume();
        }
        if (this.fetch().text === "^") {
          primes.push(this.handleSupSubscript("superscript"));
        }
        superscript = {
          type: "ordgroup",
          mode: this.mode,
          body: primes
        };
      } else if (uSubsAndSups[lex.text]) {
        var isSub = unicodeSubRegEx.test(lex.text);
        var subsupTokens = [];
        subsupTokens.push(new Token(uSubsAndSups[lex.text]));
        this.consume();
        while (true) {
          var token = this.fetch().text;
          if (!uSubsAndSups[token]) {
            break;
          }
          if (unicodeSubRegEx.test(token) !== isSub) {
            break;
          }
          subsupTokens.unshift(new Token(uSubsAndSups[token]));
          this.consume();
        }
        var body = this.subparse(subsupTokens);
        if (isSub) {
          subscript = {
            type: "ordgroup",
            mode: "math",
            body
          };
        } else {
          superscript = {
            type: "ordgroup",
            mode: "math",
            body
          };
        }
      } else {
        break;
      }
    }
    if (superscript || subscript) {
      return {
        type: "supsub",
        mode: this.mode,
        base: base2,
        sup: superscript,
        sub: subscript
      };
    } else {
      return base2;
    }
  }
  /**
   * Parses an entire function, including its base and all of its arguments.
   */
  parseFunction(breakOnTokenText, name) {
    var token = this.fetch();
    var func = token.text;
    var funcData = functions[func];
    if (!funcData) {
      return null;
    }
    this.consume();
    if (name && name !== "atom" && !funcData.allowedInArgument) {
      throw new ParseError("Got function '" + func + "' with no arguments" + (name ? " as " + name : ""), token);
    } else if (this.mode === "text" && !funcData.allowedInText) {
      throw new ParseError("Can't use function '" + func + "' in text mode", token);
    } else if (this.mode === "math" && funcData.allowedInMath === false) {
      throw new ParseError("Can't use function '" + func + "' in math mode", token);
    }
    var {
      args,
      optArgs
    } = this.parseArguments(func, funcData);
    return this.callFunction(func, args, optArgs, token, breakOnTokenText);
  }
  /**
   * Call a function handler with a suitable context and arguments.
   */
  callFunction(name, args, optArgs, token, breakOnTokenText) {
    var context = {
      funcName: name,
      parser: this,
      token,
      breakOnTokenText
    };
    var func = functions[name];
    if (func && func.handler) {
      return func.handler(context, args, optArgs);
    } else {
      throw new ParseError("No function handler for " + name);
    }
  }
  /**
   * Parses the arguments of a function or environment
   */
  parseArguments(func, funcData) {
    var totalArgs = funcData.numArgs + funcData.numOptionalArgs;
    if (totalArgs === 0) {
      return {
        args: [],
        optArgs: []
      };
    }
    var args = [];
    var optArgs = [];
    for (var i = 0; i < totalArgs; i++) {
      var argType = funcData.argTypes && funcData.argTypes[i];
      var isOptional = i < funcData.numOptionalArgs;
      if (funcData.primitive && argType == null || // \sqrt expands into primitive if optional argument doesn't exist
      funcData.type === "sqrt" && i === 1 && optArgs[0] == null) {
        argType = "primitive";
      }
      var arg = this.parseGroupOfType("argument to '" + func + "'", argType, isOptional);
      if (isOptional) {
        optArgs.push(arg);
      } else if (arg != null) {
        args.push(arg);
      } else {
        throw new ParseError("Null argument, please report this as a bug");
      }
    }
    return {
      args,
      optArgs
    };
  }
  /**
   * Parses a group when the mode is changing.
   */
  parseGroupOfType(name, type, optional) {
    switch (type) {
      case "color":
        return this.parseColorGroup(optional);
      case "size":
        return this.parseSizeGroup(optional);
      case "url":
        return this.parseUrlGroup(optional);
      case "math":
      case "text":
        return this.parseArgumentGroup(optional, type);
      case "hbox": {
        var group = this.parseArgumentGroup(optional, "text");
        return group != null ? {
          type: "styling",
          mode: group.mode,
          body: [group],
          style: "text"
          // simulate \textstyle
        } : null;
      }
      case "raw": {
        var token = this.parseStringGroup("raw", optional);
        return token != null ? {
          type: "raw",
          mode: "text",
          string: token.text
        } : null;
      }
      case "primitive": {
        if (optional) {
          throw new ParseError("A primitive argument cannot be optional");
        }
        var _group2 = this.parseGroup(name);
        if (_group2 == null) {
          throw new ParseError("Expected group as " + name, this.fetch());
        }
        return _group2;
      }
      case "original":
      case null:
      case void 0:
        return this.parseArgumentGroup(optional);
      default:
        throw new ParseError("Unknown group type as " + name, this.fetch());
    }
  }
  /**
   * Discard any space tokens, fetching the next non-space token.
   */
  consumeSpaces() {
    while (this.fetch().text === " ") {
      this.consume();
    }
  }
  /**
   * Parses a group, essentially returning the string formed by the
   * brace-enclosed tokens plus some position information.
   */
  parseStringGroup(modeName, optional) {
    var argToken = this.gullet.scanArgument(optional);
    if (argToken == null) {
      return null;
    }
    var str = "";
    var nextToken;
    while ((nextToken = this.fetch()).text !== "EOF") {
      str += nextToken.text;
      this.consume();
    }
    this.consume();
    argToken.text = str;
    return argToken;
  }
  /**
   * Parses a regex-delimited group: the largest sequence of tokens
   * whose concatenated strings match `regex`. Returns the string
   * formed by the tokens plus some position information.
   */
  parseRegexGroup(regex, modeName) {
    var firstToken = this.fetch();
    var lastToken = firstToken;
    var str = "";
    var nextToken;
    while ((nextToken = this.fetch()).text !== "EOF" && regex.test(str + nextToken.text)) {
      lastToken = nextToken;
      str += lastToken.text;
      this.consume();
    }
    if (str === "") {
      throw new ParseError("Invalid " + modeName + ": '" + firstToken.text + "'", firstToken);
    }
    return firstToken.range(lastToken, str);
  }
  /**
   * Parses a color description.
   */
  parseColorGroup(optional) {
    var res = this.parseStringGroup("color", optional);
    if (res == null) {
      return null;
    }
    var match = /^(#[a-f0-9]{3}|#?[a-f0-9]{6}|[a-z]+)$/i.exec(res.text);
    if (!match) {
      throw new ParseError("Invalid color: '" + res.text + "'", res);
    }
    var color = match[0];
    if (/^[0-9a-f]{6}$/i.test(color)) {
      color = "#" + color;
    }
    return {
      type: "color-token",
      mode: this.mode,
      color
    };
  }
  /**
   * Parses a size specification, consisting of magnitude and unit.
   */
  parseSizeGroup(optional) {
    var res;
    var isBlank = false;
    this.gullet.consumeSpaces();
    if (!optional && this.gullet.future().text !== "{") {
      res = this.parseRegexGroup(/^[-+]? *(?:$|\d+|\d+\.\d*|\.\d*) *[a-z]{0,2} *$/, "size");
    } else {
      res = this.parseStringGroup("size", optional);
    }
    if (!res) {
      return null;
    }
    if (!optional && res.text.length === 0) {
      res.text = "0pt";
      isBlank = true;
    }
    var match = /([-+]?) *(\d+(?:\.\d*)?|\.\d+) *([a-z]{2})/.exec(res.text);
    if (!match) {
      throw new ParseError("Invalid size: '" + res.text + "'", res);
    }
    var data = {
      number: +(match[1] + match[2]),
      // sign + magnitude, cast to number
      unit: match[3]
    };
    if (!validUnit(data)) {
      throw new ParseError("Invalid unit: '" + data.unit + "'", res);
    }
    return {
      type: "size",
      mode: this.mode,
      value: data,
      isBlank
    };
  }
  /**
   * Parses an URL, checking escaped letters and allowed protocols,
   * and setting the catcode of % as an active character (as in \hyperref).
   */
  parseUrlGroup(optional) {
    this.gullet.lexer.setCatcode("%", 13);
    this.gullet.lexer.setCatcode("~", 12);
    var res = this.parseStringGroup("url", optional);
    this.gullet.lexer.setCatcode("%", 14);
    this.gullet.lexer.setCatcode("~", 13);
    if (res == null) {
      return null;
    }
    var url = res.text.replace(/\\([#$%&~_^{}])/g, "$1");
    return {
      type: "url",
      mode: this.mode,
      url
    };
  }
  /**
   * Parses an argument with the mode specified.
   */
  parseArgumentGroup(optional, mode) {
    var argToken = this.gullet.scanArgument(optional);
    if (argToken == null) {
      return null;
    }
    var outerMode = this.mode;
    if (mode) {
      this.switchMode(mode);
    }
    this.gullet.beginGroup();
    var expression = this.parseExpression(false, "EOF");
    this.expect("EOF");
    this.gullet.endGroup();
    var result = {
      type: "ordgroup",
      mode: this.mode,
      loc: argToken.loc,
      body: expression
    };
    if (mode) {
      this.switchMode(outerMode);
    }
    return result;
  }
  /**
   * Parses an ordinary group, which is either a single nucleus (like "x")
   * or an expression in braces (like "{x+y}") or an implicit group, a group
   * that starts at the current position, and ends right before a higher explicit
   * group ends, or at EOF.
   */
  parseGroup(name, breakOnTokenText) {
    var firstToken = this.fetch();
    var text5 = firstToken.text;
    var result;
    if (text5 === "{" || text5 === "\\begingroup") {
      this.consume();
      var groupEnd = text5 === "{" ? "}" : "\\endgroup";
      this.gullet.beginGroup();
      var expression = this.parseExpression(false, groupEnd);
      var lastToken = this.fetch();
      this.expect(groupEnd);
      this.gullet.endGroup();
      result = {
        type: "ordgroup",
        mode: this.mode,
        loc: SourceLocation.range(firstToken, lastToken),
        body: expression,
        // A group formed by \begingroup...\endgroup is a semi-simple group
        // which doesn't affect spacing in math mode, i.e., is transparent.
        // https://tex.stackexchange.com/questions/1930/when-should-one-
        // use-begingroup-instead-of-bgroup
        semisimple: text5 === "\\begingroup" || void 0
      };
    } else {
      result = this.parseFunction(breakOnTokenText, name) || this.parseSymbol();
      if (result == null && text5[0] === "\\" && !implicitCommands.hasOwnProperty(text5)) {
        if (this.settings.throwOnError) {
          throw new ParseError("Undefined control sequence: " + text5, firstToken);
        }
        result = this.formatUnsupportedCmd(text5);
        this.consume();
      }
    }
    return result;
  }
  /**
   * Form ligature-like combinations of characters for text mode.
   * This includes inputs like "--", "---", "``" and "''".
   * The result will simply replace multiple textord nodes with a single
   * character in each value by a single textord node having multiple
   * characters in its value.  The representation is still ASCII source.
   * The group will be modified in place.
   */
  formLigatures(group) {
    var n = group.length - 1;
    for (var i = 0; i < n; ++i) {
      var a2 = group[i];
      var v = a2.text;
      if (v === "-" && group[i + 1].text === "-") {
        if (i + 1 < n && group[i + 2].text === "-") {
          group.splice(i, 3, {
            type: "textord",
            mode: "text",
            loc: SourceLocation.range(a2, group[i + 2]),
            text: "---"
          });
          n -= 2;
        } else {
          group.splice(i, 2, {
            type: "textord",
            mode: "text",
            loc: SourceLocation.range(a2, group[i + 1]),
            text: "--"
          });
          n -= 1;
        }
      }
      if ((v === "'" || v === "`") && group[i + 1].text === v) {
        group.splice(i, 2, {
          type: "textord",
          mode: "text",
          loc: SourceLocation.range(a2, group[i + 1]),
          text: v + v
        });
        n -= 1;
      }
    }
  }
  /**
   * Parse a single symbol out of the string. Here, we handle single character
   * symbols and special functions like \verb.
   */
  parseSymbol() {
    var nucleus = this.fetch();
    var text5 = nucleus.text;
    if (/^\\verb[^a-zA-Z]/.test(text5)) {
      this.consume();
      var arg = text5.slice(5);
      var star = arg.charAt(0) === "*";
      if (star) {
        arg = arg.slice(1);
      }
      if (arg.length < 2 || arg.charAt(0) !== arg.slice(-1)) {
        throw new ParseError("\\verb assertion failed --\n                    please report what input caused this bug");
      }
      arg = arg.slice(1, -1);
      return {
        type: "verb",
        mode: "text",
        body: arg,
        star
      };
    }
    if (unicodeSymbols.hasOwnProperty(text5[0]) && !symbols[this.mode][text5[0]]) {
      if (this.settings.strict && this.mode === "math") {
        this.settings.reportNonstrict("unicodeTextInMathMode", 'Accented Unicode text character "' + text5[0] + '" used in math mode', nucleus);
      }
      text5 = unicodeSymbols[text5[0]] + text5.slice(1);
    }
    var match = combiningDiacriticalMarksEndRegex.exec(text5);
    if (match) {
      text5 = text5.substring(0, match.index);
      if (text5 === "i") {
        text5 = "\u0131";
      } else if (text5 === "j") {
        text5 = "\u0237";
      }
    }
    var symbol;
    if (symbols[this.mode][text5]) {
      if (this.settings.strict && this.mode === "math" && extraLatin.indexOf(text5) >= 0) {
        this.settings.reportNonstrict("unicodeTextInMathMode", 'Latin-1/Unicode text character "' + text5[0] + '" used in math mode', nucleus);
      }
      var group = symbols[this.mode][text5].group;
      var loc = SourceLocation.range(nucleus);
      var s;
      if (ATOMS.hasOwnProperty(group)) {
        var family = group;
        s = {
          type: "atom",
          mode: this.mode,
          family,
          loc,
          text: text5
        };
      } else {
        s = {
          type: group,
          mode: this.mode,
          loc,
          text: text5
        };
      }
      symbol = s;
    } else if (text5.charCodeAt(0) >= 128) {
      if (this.settings.strict) {
        if (!supportedCodepoint(text5.charCodeAt(0))) {
          this.settings.reportNonstrict("unknownSymbol", 'Unrecognized Unicode character "' + text5[0] + '"' + (" (" + text5.charCodeAt(0) + ")"), nucleus);
        } else if (this.mode === "math") {
          this.settings.reportNonstrict("unicodeTextInMathMode", 'Unicode text character "' + text5[0] + '" used in math mode', nucleus);
        }
      }
      symbol = {
        type: "textord",
        mode: "text",
        loc: SourceLocation.range(nucleus),
        text: text5
      };
    } else {
      return null;
    }
    this.consume();
    if (match) {
      for (var i = 0; i < match[0].length; i++) {
        var accent2 = match[0][i];
        if (!unicodeAccents[accent2]) {
          throw new ParseError("Unknown accent ' " + accent2 + "'", nucleus);
        }
        var command2 = unicodeAccents[accent2][this.mode] || unicodeAccents[accent2].text;
        if (!command2) {
          throw new ParseError("Accent " + accent2 + " unsupported in " + this.mode + " mode", nucleus);
        }
        symbol = {
          type: "accent",
          mode: this.mode,
          loc: SourceLocation.range(nucleus),
          label: command2,
          isStretchy: false,
          isShifty: true,
          // $FlowFixMe
          base: symbol
        };
      }
    }
    return symbol;
  }
};
Parser.endOfExpression = ["}", "\\endgroup", "\\end", "\\right", "&"];
var parseTree = function parseTree2(toParse, settings) {
  if (!(typeof toParse === "string" || toParse instanceof String)) {
    throw new TypeError("KaTeX can only parse string typed expression");
  }
  var parser = new Parser(toParse, settings);
  delete parser.gullet.macros.current["\\df@tag"];
  var tree = parser.parse();
  delete parser.gullet.macros.current["\\current@color"];
  delete parser.gullet.macros.current["\\color"];
  if (parser.gullet.macros.get("\\df@tag")) {
    if (!settings.displayMode) {
      throw new ParseError("\\tag works only in display equations");
    }
    tree = [{
      type: "tag",
      mode: "text",
      body: tree,
      tag: parser.subparse([new Token("\\df@tag")])
    }];
  }
  return tree;
};
var render = function render2(expression, baseNode, options) {
  baseNode.textContent = "";
  var node = renderToDomTree(expression, options).toNode();
  baseNode.appendChild(node);
};
if (typeof document !== "undefined") {
  if (document.compatMode !== "CSS1Compat") {
    typeof console !== "undefined" && console.warn("Warning: KaTeX doesn't work in quirks mode. Make sure your website has a suitable doctype.");
    render = function render3() {
      throw new ParseError("KaTeX doesn't work in quirks mode.");
    };
  }
}
var renderToString = function renderToString2(expression, options) {
  var markup = renderToDomTree(expression, options).toMarkup();
  return markup;
};
var generateParseTree = function generateParseTree2(expression, options) {
  var settings = new Settings(options);
  return parseTree(expression, settings);
};
var renderError = function renderError2(error, expression, options) {
  if (options.throwOnError || !(error instanceof ParseError)) {
    throw error;
  }
  var node = buildCommon.makeSpan(["katex-error"], [new SymbolNode(expression)]);
  node.setAttribute("title", error.toString());
  node.setAttribute("style", "color:" + options.errorColor);
  return node;
};
var renderToDomTree = function renderToDomTree2(expression, options) {
  var settings = new Settings(options);
  try {
    var tree = parseTree(expression, settings);
    return buildTree2(tree, expression, settings);
  } catch (error) {
    return renderError(error, expression, settings);
  }
};
var renderToHTMLTree = function renderToHTMLTree2(expression, options) {
  var settings = new Settings(options);
  try {
    var tree = parseTree(expression, settings);
    return buildHTMLTree(tree, expression, settings);
  } catch (error) {
    return renderError(error, expression, settings);
  }
};
var version = "0.16.22";
var __domTree = {
  Span,
  Anchor,
  SymbolNode,
  SvgNode,
  PathNode,
  LineNode
};
var katex = {
  /**
   * Current KaTeX version
   */
  version,
  /**
   * Renders the given LaTeX into an HTML+MathML combination, and adds
   * it as a child to the specified DOM node.
   */
  render,
  /**
   * Renders the given LaTeX into an HTML+MathML combination string,
   * for sending to the client.
   */
  renderToString,
  /**
   * KaTeX error, usually during parsing.
   */
  ParseError,
  /**
   * The schema of Settings
   */
  SETTINGS_SCHEMA,
  /**
   * Parses the given LaTeX into KaTeX's internal parse tree structure,
   * without rendering to HTML or MathML.
   *
   * NOTE: This method is not currently recommended for public use.
   * The internal tree representation is unstable and is very likely
   * to change. Use at your own risk.
   */
  __parse: generateParseTree,
  /**
   * Renders the given LaTeX into an HTML+MathML internal DOM tree
   * representation, without flattening that representation to a string.
   *
   * NOTE: This method is not currently recommended for public use.
   * The internal tree representation is unstable and is very likely
   * to change. Use at your own risk.
   */
  __renderToDomTree: renderToDomTree,
  /**
   * Renders the given LaTeX into an HTML internal DOM tree representation,
   * without MathML and without flattening that representation to a string.
   *
   * NOTE: This method is not currently recommended for public use.
   * The internal tree representation is unstable and is very likely
   * to change. Use at your own risk.
   */
  __renderToHTMLTree: renderToHTMLTree,
  /**
   * extends internal font metrics object with a new object
   * each key in the new object represents a font name
  */
  __setFontMetrics: setFontMetrics,
  /**
   * adds a new symbol to builtin symbols table
   */
  __defineSymbol: defineSymbol,
  /**
   * adds a new function to builtin function list,
   * which directly produce parse tree elements
   * and have their own html/mathml builders
   */
  __defineFunction: defineFunction,
  /**
   * adds a new macro to builtin macro list
   */
  __defineMacro: defineMacro,
  /**
   * Expose the dom tree node types, which can be useful for type checking nodes.
   *
   * NOTE: These methods are not currently recommended for public use.
   * The internal tree representation is unstable and is very likely
   * to change. Use at your own risk.
   */
  __domTree
};

// ../../node_modules/.pnpm/katex@0.16.22/node_modules/katex/dist/contrib/mhchem.mjs
katex.__defineMacro("\\ce", function(context) {
  return chemParse(context.consumeArgs(1)[0], "ce");
});
katex.__defineMacro("\\pu", function(context) {
  return chemParse(context.consumeArgs(1)[0], "pu");
});
katex.__defineMacro("\\tripledash", "{\\vphantom{-}\\raisebox{2.56mu}{$\\mkern2mu\\tiny\\text{-}\\mkern1mu\\text{-}\\mkern1mu\\text{-}\\mkern2mu$}}");
var chemParse = function chemParse2(tokens, stateMachine) {
  var str = "";
  var expectedLoc = tokens.length && tokens[tokens.length - 1].loc.start;
  for (var i = tokens.length - 1; i >= 0; i--) {
    if (tokens[i].loc.start > expectedLoc) {
      str += " ";
      expectedLoc = tokens[i].loc.start;
    }
    str += tokens[i].text;
    expectedLoc += tokens[i].text.length;
  }
  var tex = texify.go(mhchemParser.go(str, stateMachine));
  return tex;
};
var mhchemParser = {
  //
  // Parses mchem \ce syntax
  //
  // Call like
  //   go("H2O");
  //
  go: function go(input, stateMachine) {
    if (!input) {
      return [];
    }
    if (stateMachine === void 0) {
      stateMachine = "ce";
    }
    var state = "0";
    var buffer = {};
    buffer["parenthesisLevel"] = 0;
    input = input.replace(/\n/g, " ");
    input = input.replace(/[\u2212\u2013\u2014\u2010]/g, "-");
    input = input.replace(/[\u2026]/g, "...");
    var lastInput;
    var watchdog = 10;
    var output7 = [];
    while (true) {
      if (lastInput !== input) {
        watchdog = 10;
        lastInput = input;
      } else {
        watchdog--;
      }
      var machine = mhchemParser.stateMachines[stateMachine];
      var t = machine.transitions[state] || machine.transitions["*"];
      iterateTransitions: for (var i = 0; i < t.length; i++) {
        var matches2 = mhchemParser.patterns.match_(t[i].pattern, input);
        if (matches2) {
          var task = t[i].task;
          for (var iA = 0; iA < task.action_.length; iA++) {
            var o2;
            if (machine.actions[task.action_[iA].type_]) {
              o2 = machine.actions[task.action_[iA].type_](buffer, matches2.match_, task.action_[iA].option);
            } else if (mhchemParser.actions[task.action_[iA].type_]) {
              o2 = mhchemParser.actions[task.action_[iA].type_](buffer, matches2.match_, task.action_[iA].option);
            } else {
              throw ["MhchemBugA", "mhchem bug A. Please report. (" + task.action_[iA].type_ + ")"];
            }
            mhchemParser.concatArray(output7, o2);
          }
          state = task.nextState || state;
          if (input.length > 0) {
            if (!task.revisit) {
              input = matches2.remainder;
            }
            if (!task.toContinue) {
              break iterateTransitions;
            }
          } else {
            return output7;
          }
        }
      }
      if (watchdog <= 0) {
        throw ["MhchemBugU", "mhchem bug U. Please report."];
      }
    }
  },
  concatArray: function concatArray(a2, b2) {
    if (b2) {
      if (Array.isArray(b2)) {
        for (var iB = 0; iB < b2.length; iB++) {
          a2.push(b2[iB]);
        }
      } else {
        a2.push(b2);
      }
    }
  },
  patterns: {
    //
    // Matching patterns
    // either regexps or function that return null or {match_:"a", remainder:"bc"}
    //
    patterns: {
      // property names must not look like integers ("2") for correct property traversal order, later on
      "empty": /^$/,
      "else": /^./,
      "else2": /^./,
      "space": /^\s/,
      "space A": /^\s(?=[A-Z\\$])/,
      "space$": /^\s$/,
      "a-z": /^[a-z]/,
      "x": /^x/,
      "x$": /^x$/,
      "i$": /^i$/,
      "letters": /^(?:[a-zA-Z\u03B1-\u03C9\u0391-\u03A9?@]|(?:\\(?:alpha|beta|gamma|delta|epsilon|zeta|eta|theta|iota|kappa|lambda|mu|nu|xi|omicron|pi|rho|sigma|tau|upsilon|phi|chi|psi|omega|Gamma|Delta|Theta|Lambda|Xi|Pi|Sigma|Upsilon|Phi|Psi|Omega)(?:\s+|\{\}|(?![a-zA-Z]))))+/,
      "\\greek": /^\\(?:alpha|beta|gamma|delta|epsilon|zeta|eta|theta|iota|kappa|lambda|mu|nu|xi|omicron|pi|rho|sigma|tau|upsilon|phi|chi|psi|omega|Gamma|Delta|Theta|Lambda|Xi|Pi|Sigma|Upsilon|Phi|Psi|Omega)(?:\s+|\{\}|(?![a-zA-Z]))/,
      "one lowercase latin letter $": /^(?:([a-z])(?:$|[^a-zA-Z]))$/,
      "$one lowercase latin letter$ $": /^\$(?:([a-z])(?:$|[^a-zA-Z]))\$$/,
      "one lowercase greek letter $": /^(?:\$?[\u03B1-\u03C9]\$?|\$?\\(?:alpha|beta|gamma|delta|epsilon|zeta|eta|theta|iota|kappa|lambda|mu|nu|xi|omicron|pi|rho|sigma|tau|upsilon|phi|chi|psi|omega)\s*\$?)(?:\s+|\{\}|(?![a-zA-Z]))$/,
      "digits": /^[0-9]+/,
      "-9.,9": /^[+\-]?(?:[0-9]+(?:[,.][0-9]+)?|[0-9]*(?:\.[0-9]+))/,
      "-9.,9 no missing 0": /^[+\-]?[0-9]+(?:[.,][0-9]+)?/,
      "(-)(9.,9)(e)(99)": function e99(input) {
        var m = input.match(/^(\+\-|\+\/\-|\+|\-|\\pm\s?)?([0-9]+(?:[,.][0-9]+)?|[0-9]*(?:\.[0-9]+))?(\((?:[0-9]+(?:[,.][0-9]+)?|[0-9]*(?:\.[0-9]+))\))?(?:([eE]|\s*(\*|x|\\times|\u00D7)\s*10\^)([+\-]?[0-9]+|\{[+\-]?[0-9]+\}))?/);
        if (m && m[0]) {
          return {
            match_: m.splice(1),
            remainder: input.substr(m[0].length)
          };
        }
        return null;
      },
      "(-)(9)^(-9)": function _(input) {
        var m = input.match(/^(\+\-|\+\/\-|\+|\-|\\pm\s?)?([0-9]+(?:[,.][0-9]+)?|[0-9]*(?:\.[0-9]+)?)\^([+\-]?[0-9]+|\{[+\-]?[0-9]+\})/);
        if (m && m[0]) {
          return {
            match_: m.splice(1),
            remainder: input.substr(m[0].length)
          };
        }
        return null;
      },
      "state of aggregation $": function stateOfAggregation$(input) {
        var a2 = mhchemParser.patterns.findObserveGroups(input, "", /^\([a-z]{1,3}(?=[\),])/, ")", "");
        if (a2 && a2.remainder.match(/^($|[\s,;\)\]\}])/)) {
          return a2;
        }
        var m = input.match(/^(?:\((?:\\ca\s?)?\$[amothc]\$\))/);
        if (m) {
          return {
            match_: m[0],
            remainder: input.substr(m[0].length)
          };
        }
        return null;
      },
      "_{(state of aggregation)}$": /^_\{(\([a-z]{1,3}\))\}/,
      "{[(": /^(?:\\\{|\[|\()/,
      ")]}": /^(?:\)|\]|\\\})/,
      ", ": /^[,;]\s*/,
      ",": /^[,;]/,
      ".": /^[.]/,
      ". ": /^([.\u22C5\u00B7\u2022])\s*/,
      "...": /^\.\.\.(?=$|[^.])/,
      "* ": /^([*])\s*/,
      "^{(...)}": function _2(input) {
        return mhchemParser.patterns.findObserveGroups(input, "^{", "", "", "}");
      },
      "^($...$)": function $$(input) {
        return mhchemParser.patterns.findObserveGroups(input, "^", "$", "$", "");
      },
      "^a": /^\^([0-9]+|[^\\_])/,
      "^\\x{}{}": function x(input) {
        return mhchemParser.patterns.findObserveGroups(input, "^", /^\\[a-zA-Z]+\{/, "}", "", "", "{", "}", "", true);
      },
      "^\\x{}": function x2(input) {
        return mhchemParser.patterns.findObserveGroups(input, "^", /^\\[a-zA-Z]+\{/, "}", "");
      },
      "^\\x": /^\^(\\[a-zA-Z]+)\s*/,
      "^(-1)": /^\^(-?\d+)/,
      "'": /^'/,
      "_{(...)}": function _3(input) {
        return mhchemParser.patterns.findObserveGroups(input, "_{", "", "", "}");
      },
      "_($...$)": function _$$(input) {
        return mhchemParser.patterns.findObserveGroups(input, "_", "$", "$", "");
      },
      "_9": /^_([+\-]?[0-9]+|[^\\])/,
      "_\\x{}{}": function _X(input) {
        return mhchemParser.patterns.findObserveGroups(input, "_", /^\\[a-zA-Z]+\{/, "}", "", "", "{", "}", "", true);
      },
      "_\\x{}": function _X2(input) {
        return mhchemParser.patterns.findObserveGroups(input, "_", /^\\[a-zA-Z]+\{/, "}", "");
      },
      "_\\x": /^_(\\[a-zA-Z]+)\s*/,
      "^_": /^(?:\^(?=_)|\_(?=\^)|[\^_]$)/,
      "{}": /^\{\}/,
      "{...}": function _4(input) {
        return mhchemParser.patterns.findObserveGroups(input, "", "{", "}", "");
      },
      "{(...)}": function _5(input) {
        return mhchemParser.patterns.findObserveGroups(input, "{", "", "", "}");
      },
      "$...$": function $$2(input) {
        return mhchemParser.patterns.findObserveGroups(input, "", "$", "$", "");
      },
      "${(...)}$": function $$3(input) {
        return mhchemParser.patterns.findObserveGroups(input, "${", "", "", "}$");
      },
      "$(...)$": function $$4(input) {
        return mhchemParser.patterns.findObserveGroups(input, "$", "", "", "$");
      },
      "=<>": /^[=<>]/,
      "#": /^[#\u2261]/,
      "+": /^\+/,
      "-$": /^-(?=[\s_},;\]/]|$|\([a-z]+\))/,
      // -space -, -; -] -/ -$ -state-of-aggregation
      "-9": /^-(?=[0-9])/,
      "- orbital overlap": /^-(?=(?:[spd]|sp)(?:$|[\s,;\)\]\}]))/,
      "-": /^-/,
      "pm-operator": /^(?:\\pm|\$\\pm\$|\+-|\+\/-)/,
      "operator": /^(?:\+|(?:[\-=<>]|<<|>>|\\approx|\$\\approx\$)(?=\s|$|-?[0-9]))/,
      "arrowUpDown": /^(?:v|\(v\)|\^|\(\^\))(?=$|[\s,;\)\]\}])/,
      "\\bond{(...)}": function bond(input) {
        return mhchemParser.patterns.findObserveGroups(input, "\\bond{", "", "", "}");
      },
      "->": /^(?:<->|<-->|->|<-|<=>>|<<=>|<=>|[\u2192\u27F6\u21CC])/,
      "CMT": /^[CMT](?=\[)/,
      "[(...)]": function _6(input) {
        return mhchemParser.patterns.findObserveGroups(input, "[", "", "", "]");
      },
      "1st-level escape": /^(&|\\\\|\\hline)\s*/,
      "\\,": /^(?:\\[,\ ;:])/,
      // \\x - but output no space before
      "\\x{}{}": function x3(input) {
        return mhchemParser.patterns.findObserveGroups(input, "", /^\\[a-zA-Z]+\{/, "}", "", "", "{", "}", "", true);
      },
      "\\x{}": function x4(input) {
        return mhchemParser.patterns.findObserveGroups(input, "", /^\\[a-zA-Z]+\{/, "}", "");
      },
      "\\ca": /^\\ca(?:\s+|(?![a-zA-Z]))/,
      "\\x": /^(?:\\[a-zA-Z]+\s*|\\[_&{}%])/,
      "orbital": /^(?:[0-9]{1,2}[spdfgh]|[0-9]{0,2}sp)(?=$|[^a-zA-Z])/,
      // only those with numbers in front, because the others will be formatted correctly anyway
      "others": /^[\/~|]/,
      "\\frac{(...)}": function frac(input) {
        return mhchemParser.patterns.findObserveGroups(input, "\\frac{", "", "", "}", "{", "", "", "}");
      },
      "\\overset{(...)}": function overset(input) {
        return mhchemParser.patterns.findObserveGroups(input, "\\overset{", "", "", "}", "{", "", "", "}");
      },
      "\\underset{(...)}": function underset(input) {
        return mhchemParser.patterns.findObserveGroups(input, "\\underset{", "", "", "}", "{", "", "", "}");
      },
      "\\underbrace{(...)}": function underbrace(input) {
        return mhchemParser.patterns.findObserveGroups(input, "\\underbrace{", "", "", "}_", "{", "", "", "}");
      },
      "\\color{(...)}0": function color0(input) {
        return mhchemParser.patterns.findObserveGroups(input, "\\color{", "", "", "}");
      },
      "\\color{(...)}{(...)}1": function color1(input) {
        return mhchemParser.patterns.findObserveGroups(input, "\\color{", "", "", "}", "{", "", "", "}");
      },
      "\\color(...){(...)}2": function color2(input) {
        return mhchemParser.patterns.findObserveGroups(input, "\\color", "\\", "", /^(?=\{)/, "{", "", "", "}");
      },
      "\\ce{(...)}": function ce(input) {
        return mhchemParser.patterns.findObserveGroups(input, "\\ce{", "", "", "}");
      },
      "oxidation$": /^(?:[+-][IVX]+|\\pm\s*0|\$\\pm\$\s*0)$/,
      "d-oxidation$": /^(?:[+-]?\s?[IVX]+|\\pm\s*0|\$\\pm\$\s*0)$/,
      // 0 could be oxidation or charge
      "roman numeral": /^[IVX]+/,
      "1/2$": /^[+\-]?(?:[0-9]+|\$[a-z]\$|[a-z])\/[0-9]+(?:\$[a-z]\$|[a-z])?$/,
      "amount": function amount(input) {
        var match;
        match = input.match(/^(?:(?:(?:\([+\-]?[0-9]+\/[0-9]+\)|[+\-]?(?:[0-9]+|\$[a-z]\$|[a-z])\/[0-9]+|[+\-]?[0-9]+[.,][0-9]+|[+\-]?\.[0-9]+|[+\-]?[0-9]+)(?:[a-z](?=\s*[A-Z]))?)|[+\-]?[a-z](?=\s*[A-Z])|\+(?!\s))/);
        if (match) {
          return {
            match_: match[0],
            remainder: input.substr(match[0].length)
          };
        }
        var a2 = mhchemParser.patterns.findObserveGroups(input, "", "$", "$", "");
        if (a2) {
          match = a2.match_.match(/^\$(?:\(?[+\-]?(?:[0-9]*[a-z]?[+\-])?[0-9]*[a-z](?:[+\-][0-9]*[a-z]?)?\)?|\+|-)\$$/);
          if (match) {
            return {
              match_: match[0],
              remainder: input.substr(match[0].length)
            };
          }
        }
        return null;
      },
      "amount2": function amount2(input) {
        return this["amount"](input);
      },
      "(KV letters),": /^(?:[A-Z][a-z]{0,2}|i)(?=,)/,
      "formula$": function formula$(input) {
        if (input.match(/^\([a-z]+\)$/)) {
          return null;
        }
        var match = input.match(/^(?:[a-z]|(?:[0-9\ \+\-\,\.\(\)]+[a-z])+[0-9\ \+\-\,\.\(\)]*|(?:[a-z][0-9\ \+\-\,\.\(\)]+)+[a-z]?)$/);
        if (match) {
          return {
            match_: match[0],
            remainder: input.substr(match[0].length)
          };
        }
        return null;
      },
      "uprightEntities": /^(?:pH|pOH|pC|pK|iPr|iBu)(?=$|[^a-zA-Z])/,
      "/": /^\s*(\/)\s*/,
      "//": /^\s*(\/\/)\s*/,
      "*": /^\s*[*.]\s*/
    },
    findObserveGroups: function findObserveGroups(input, begExcl, begIncl, endIncl, endExcl, beg2Excl, beg2Incl, end2Incl, end2Excl, combine) {
      var _match = function _match2(input2, pattern) {
        if (typeof pattern === "string") {
          if (input2.indexOf(pattern) !== 0) {
            return null;
          }
          return pattern;
        } else {
          var match2 = input2.match(pattern);
          if (!match2) {
            return null;
          }
          return match2[0];
        }
      };
      var _findObserveGroups = function _findObserveGroups2(input2, i, endChars) {
        var braces = 0;
        while (i < input2.length) {
          var a2 = input2.charAt(i);
          var match2 = _match(input2.substr(i), endChars);
          if (match2 !== null && braces === 0) {
            return {
              endMatchBegin: i,
              endMatchEnd: i + match2.length
            };
          } else if (a2 === "{") {
            braces++;
          } else if (a2 === "}") {
            if (braces === 0) {
              throw ["ExtraCloseMissingOpen", "Extra close brace or missing open brace"];
            } else {
              braces--;
            }
          }
          i++;
        }
        if (braces > 0) {
          return null;
        }
        return null;
      };
      var match = _match(input, begExcl);
      if (match === null) {
        return null;
      }
      input = input.substr(match.length);
      match = _match(input, begIncl);
      if (match === null) {
        return null;
      }
      var e = _findObserveGroups(input, match.length, endIncl || endExcl);
      if (e === null) {
        return null;
      }
      var match1 = input.substring(0, endIncl ? e.endMatchEnd : e.endMatchBegin);
      if (!(beg2Excl || beg2Incl)) {
        return {
          match_: match1,
          remainder: input.substr(e.endMatchEnd)
        };
      } else {
        var group2 = this.findObserveGroups(input.substr(e.endMatchEnd), beg2Excl, beg2Incl, end2Incl, end2Excl);
        if (group2 === null) {
          return null;
        }
        var matchRet = [match1, group2.match_];
        return {
          match_: combine ? matchRet.join("") : matchRet,
          remainder: group2.remainder
        };
      }
    },
    //
    // Matching function
    // e.g. match("a", input) will look for the regexp called "a" and see if it matches
    // returns null or {match_:"a", remainder:"bc"}
    //
    match_: function match_(m, input) {
      var pattern = mhchemParser.patterns.patterns[m];
      if (pattern === void 0) {
        throw ["MhchemBugP", "mhchem bug P. Please report. (" + m + ")"];
      } else if (typeof pattern === "function") {
        return mhchemParser.patterns.patterns[m](input);
      } else {
        var match = input.match(pattern);
        if (match) {
          var mm;
          if (match[2]) {
            mm = [match[1], match[2]];
          } else if (match[1]) {
            mm = match[1];
          } else {
            mm = match[0];
          }
          return {
            match_: mm,
            remainder: input.substr(match[0].length)
          };
        }
        return null;
      }
    }
  },
  //
  // Generic state machine actions
  //
  actions: {
    "a=": function a(buffer, m) {
      buffer.a = (buffer.a || "") + m;
    },
    "b=": function b(buffer, m) {
      buffer.b = (buffer.b || "") + m;
    },
    "p=": function p(buffer, m) {
      buffer.p = (buffer.p || "") + m;
    },
    "o=": function o(buffer, m) {
      buffer.o = (buffer.o || "") + m;
    },
    "q=": function q(buffer, m) {
      buffer.q = (buffer.q || "") + m;
    },
    "d=": function d(buffer, m) {
      buffer.d = (buffer.d || "") + m;
    },
    "rm=": function rm2(buffer, m) {
      buffer.rm = (buffer.rm || "") + m;
    },
    "text=": function text2(buffer, m) {
      buffer.text_ = (buffer.text_ || "") + m;
    },
    "insert": function insert(buffer, m, a2) {
      return {
        type_: a2
      };
    },
    "insert+p1": function insertP1(buffer, m, a2) {
      return {
        type_: a2,
        p1: m
      };
    },
    "insert+p1+p2": function insertP1P2(buffer, m, a2) {
      return {
        type_: a2,
        p1: m[0],
        p2: m[1]
      };
    },
    "copy": function copy2(buffer, m) {
      return m;
    },
    "rm": function rm3(buffer, m) {
      return {
        type_: "rm",
        p1: m || ""
      };
    },
    "text": function text3(buffer, m) {
      return mhchemParser.go(m, "text");
    },
    "{text}": function text4(buffer, m) {
      var ret = ["{"];
      mhchemParser.concatArray(ret, mhchemParser.go(m, "text"));
      ret.push("}");
      return ret;
    },
    "tex-math": function texMath(buffer, m) {
      return mhchemParser.go(m, "tex-math");
    },
    "tex-math tight": function texMathTight(buffer, m) {
      return mhchemParser.go(m, "tex-math tight");
    },
    "bond": function bond2(buffer, m, k) {
      return {
        type_: "bond",
        kind_: k || m
      };
    },
    "color0-output": function color0Output(buffer, m) {
      return {
        type_: "color0",
        color: m[0]
      };
    },
    "ce": function ce2(buffer, m) {
      return mhchemParser.go(m);
    },
    "1/2": function _7(buffer, m) {
      var ret = [];
      if (m.match(/^[+\-]/)) {
        ret.push(m.substr(0, 1));
        m = m.substr(1);
      }
      var n = m.match(/^([0-9]+|\$[a-z]\$|[a-z])\/([0-9]+)(\$[a-z]\$|[a-z])?$/);
      n[1] = n[1].replace(/\$/g, "");
      ret.push({
        type_: "frac",
        p1: n[1],
        p2: n[2]
      });
      if (n[3]) {
        n[3] = n[3].replace(/\$/g, "");
        ret.push({
          type_: "tex-math",
          p1: n[3]
        });
      }
      return ret;
    },
    "9,9": function _8(buffer, m) {
      return mhchemParser.go(m, "9,9");
    }
  },
  //
  // createTransitions
  // convert  { 'letter': { 'state': { action_: 'output' } } }  to  { 'state' => [ { pattern: 'letter', task: { action_: [{type_: 'output'}] } } ] }
  // with expansion of 'a|b' to 'a' and 'b' (at 2 places)
  //
  createTransitions: function createTransitions(o2) {
    var pattern, state;
    var stateArray;
    var i;
    var transitions = {};
    for (pattern in o2) {
      for (state in o2[pattern]) {
        stateArray = state.split("|");
        o2[pattern][state].stateArray = stateArray;
        for (i = 0; i < stateArray.length; i++) {
          transitions[stateArray[i]] = [];
        }
      }
    }
    for (pattern in o2) {
      for (state in o2[pattern]) {
        stateArray = o2[pattern][state].stateArray || [];
        for (i = 0; i < stateArray.length; i++) {
          var p2 = o2[pattern][state];
          if (p2.action_) {
            p2.action_ = [].concat(p2.action_);
            for (var k = 0; k < p2.action_.length; k++) {
              if (typeof p2.action_[k] === "string") {
                p2.action_[k] = {
                  type_: p2.action_[k]
                };
              }
            }
          } else {
            p2.action_ = [];
          }
          var patternArray = pattern.split("|");
          for (var j = 0; j < patternArray.length; j++) {
            if (stateArray[i] === "*") {
              for (var t in transitions) {
                transitions[t].push({
                  pattern: patternArray[j],
                  task: p2
                });
              }
            } else {
              transitions[stateArray[i]].push({
                pattern: patternArray[j],
                task: p2
              });
            }
          }
        }
      }
    }
    return transitions;
  },
  stateMachines: {}
};
mhchemParser.stateMachines = {
  //
  // \ce state machines
  //
  //#region ce
  "ce": {
    // main parser
    transitions: mhchemParser.createTransitions({
      "empty": {
        "*": {
          action_: "output"
        }
      },
      "else": {
        "0|1|2": {
          action_: "beginsWithBond=false",
          revisit: true,
          toContinue: true
        }
      },
      "oxidation$": {
        "0": {
          action_: "oxidation-output"
        }
      },
      "CMT": {
        "r": {
          action_: "rdt=",
          nextState: "rt"
        },
        "rd": {
          action_: "rqt=",
          nextState: "rdt"
        }
      },
      "arrowUpDown": {
        "0|1|2|as": {
          action_: ["sb=false", "output", "operator"],
          nextState: "1"
        }
      },
      "uprightEntities": {
        "0|1|2": {
          action_: ["o=", "output"],
          nextState: "1"
        }
      },
      "orbital": {
        "0|1|2|3": {
          action_: "o=",
          nextState: "o"
        }
      },
      "->": {
        "0|1|2|3": {
          action_: "r=",
          nextState: "r"
        },
        "a|as": {
          action_: ["output", "r="],
          nextState: "r"
        },
        "*": {
          action_: ["output", "r="],
          nextState: "r"
        }
      },
      "+": {
        "o": {
          action_: "d= kv",
          nextState: "d"
        },
        "d|D": {
          action_: "d=",
          nextState: "d"
        },
        "q": {
          action_: "d=",
          nextState: "qd"
        },
        "qd|qD": {
          action_: "d=",
          nextState: "qd"
        },
        "dq": {
          action_: ["output", "d="],
          nextState: "d"
        },
        "3": {
          action_: ["sb=false", "output", "operator"],
          nextState: "0"
        }
      },
      "amount": {
        "0|2": {
          action_: "a=",
          nextState: "a"
        }
      },
      "pm-operator": {
        "0|1|2|a|as": {
          action_: ["sb=false", "output", {
            type_: "operator",
            option: "\\pm"
          }],
          nextState: "0"
        }
      },
      "operator": {
        "0|1|2|a|as": {
          action_: ["sb=false", "output", "operator"],
          nextState: "0"
        }
      },
      "-$": {
        "o|q": {
          action_: ["charge or bond", "output"],
          nextState: "qd"
        },
        "d": {
          action_: "d=",
          nextState: "d"
        },
        "D": {
          action_: ["output", {
            type_: "bond",
            option: "-"
          }],
          nextState: "3"
        },
        "q": {
          action_: "d=",
          nextState: "qd"
        },
        "qd": {
          action_: "d=",
          nextState: "qd"
        },
        "qD|dq": {
          action_: ["output", {
            type_: "bond",
            option: "-"
          }],
          nextState: "3"
        }
      },
      "-9": {
        "3|o": {
          action_: ["output", {
            type_: "insert",
            option: "hyphen"
          }],
          nextState: "3"
        }
      },
      "- orbital overlap": {
        "o": {
          action_: ["output", {
            type_: "insert",
            option: "hyphen"
          }],
          nextState: "2"
        },
        "d": {
          action_: ["output", {
            type_: "insert",
            option: "hyphen"
          }],
          nextState: "2"
        }
      },
      "-": {
        "0|1|2": {
          action_: [{
            type_: "output",
            option: 1
          }, "beginsWithBond=true", {
            type_: "bond",
            option: "-"
          }],
          nextState: "3"
        },
        "3": {
          action_: {
            type_: "bond",
            option: "-"
          }
        },
        "a": {
          action_: ["output", {
            type_: "insert",
            option: "hyphen"
          }],
          nextState: "2"
        },
        "as": {
          action_: [{
            type_: "output",
            option: 2
          }, {
            type_: "bond",
            option: "-"
          }],
          nextState: "3"
        },
        "b": {
          action_: "b="
        },
        "o": {
          action_: {
            type_: "- after o/d",
            option: false
          },
          nextState: "2"
        },
        "q": {
          action_: {
            type_: "- after o/d",
            option: false
          },
          nextState: "2"
        },
        "d|qd|dq": {
          action_: {
            type_: "- after o/d",
            option: true
          },
          nextState: "2"
        },
        "D|qD|p": {
          action_: ["output", {
            type_: "bond",
            option: "-"
          }],
          nextState: "3"
        }
      },
      "amount2": {
        "1|3": {
          action_: "a=",
          nextState: "a"
        }
      },
      "letters": {
        "0|1|2|3|a|as|b|p|bp|o": {
          action_: "o=",
          nextState: "o"
        },
        "q|dq": {
          action_: ["output", "o="],
          nextState: "o"
        },
        "d|D|qd|qD": {
          action_: "o after d",
          nextState: "o"
        }
      },
      "digits": {
        "o": {
          action_: "q=",
          nextState: "q"
        },
        "d|D": {
          action_: "q=",
          nextState: "dq"
        },
        "q": {
          action_: ["output", "o="],
          nextState: "o"
        },
        "a": {
          action_: "o=",
          nextState: "o"
        }
      },
      "space A": {
        "b|p|bp": {}
      },
      "space": {
        "a": {
          nextState: "as"
        },
        "0": {
          action_: "sb=false"
        },
        "1|2": {
          action_: "sb=true"
        },
        "r|rt|rd|rdt|rdq": {
          action_: "output",
          nextState: "0"
        },
        "*": {
          action_: ["output", "sb=true"],
          nextState: "1"
        }
      },
      "1st-level escape": {
        "1|2": {
          action_: ["output", {
            type_: "insert+p1",
            option: "1st-level escape"
          }]
        },
        "*": {
          action_: ["output", {
            type_: "insert+p1",
            option: "1st-level escape"
          }],
          nextState: "0"
        }
      },
      "[(...)]": {
        "r|rt": {
          action_: "rd=",
          nextState: "rd"
        },
        "rd|rdt": {
          action_: "rq=",
          nextState: "rdq"
        }
      },
      "...": {
        "o|d|D|dq|qd|qD": {
          action_: ["output", {
            type_: "bond",
            option: "..."
          }],
          nextState: "3"
        },
        "*": {
          action_: [{
            type_: "output",
            option: 1
          }, {
            type_: "insert",
            option: "ellipsis"
          }],
          nextState: "1"
        }
      },
      ". |* ": {
        "*": {
          action_: ["output", {
            type_: "insert",
            option: "addition compound"
          }],
          nextState: "1"
        }
      },
      "state of aggregation $": {
        "*": {
          action_: ["output", "state of aggregation"],
          nextState: "1"
        }
      },
      "{[(": {
        "a|as|o": {
          action_: ["o=", "output", "parenthesisLevel++"],
          nextState: "2"
        },
        "0|1|2|3": {
          action_: ["o=", "output", "parenthesisLevel++"],
          nextState: "2"
        },
        "*": {
          action_: ["output", "o=", "output", "parenthesisLevel++"],
          nextState: "2"
        }
      },
      ")]}": {
        "0|1|2|3|b|p|bp|o": {
          action_: ["o=", "parenthesisLevel--"],
          nextState: "o"
        },
        "a|as|d|D|q|qd|qD|dq": {
          action_: ["output", "o=", "parenthesisLevel--"],
          nextState: "o"
        }
      },
      ", ": {
        "*": {
          action_: ["output", "comma"],
          nextState: "0"
        }
      },
      "^_": {
        // ^ and _ without a sensible argument
        "*": {}
      },
      "^{(...)}|^($...$)": {
        "0|1|2|as": {
          action_: "b=",
          nextState: "b"
        },
        "p": {
          action_: "b=",
          nextState: "bp"
        },
        "3|o": {
          action_: "d= kv",
          nextState: "D"
        },
        "q": {
          action_: "d=",
          nextState: "qD"
        },
        "d|D|qd|qD|dq": {
          action_: ["output", "d="],
          nextState: "D"
        }
      },
      "^a|^\\x{}{}|^\\x{}|^\\x|'": {
        "0|1|2|as": {
          action_: "b=",
          nextState: "b"
        },
        "p": {
          action_: "b=",
          nextState: "bp"
        },
        "3|o": {
          action_: "d= kv",
          nextState: "d"
        },
        "q": {
          action_: "d=",
          nextState: "qd"
        },
        "d|qd|D|qD": {
          action_: "d="
        },
        "dq": {
          action_: ["output", "d="],
          nextState: "d"
        }
      },
      "_{(state of aggregation)}$": {
        "d|D|q|qd|qD|dq": {
          action_: ["output", "q="],
          nextState: "q"
        }
      },
      "_{(...)}|_($...$)|_9|_\\x{}{}|_\\x{}|_\\x": {
        "0|1|2|as": {
          action_: "p=",
          nextState: "p"
        },
        "b": {
          action_: "p=",
          nextState: "bp"
        },
        "3|o": {
          action_: "q=",
          nextState: "q"
        },
        "d|D": {
          action_: "q=",
          nextState: "dq"
        },
        "q|qd|qD|dq": {
          action_: ["output", "q="],
          nextState: "q"
        }
      },
      "=<>": {
        "0|1|2|3|a|as|o|q|d|D|qd|qD|dq": {
          action_: [{
            type_: "output",
            option: 2
          }, "bond"],
          nextState: "3"
        }
      },
      "#": {
        "0|1|2|3|a|as|o": {
          action_: [{
            type_: "output",
            option: 2
          }, {
            type_: "bond",
            option: "#"
          }],
          nextState: "3"
        }
      },
      "{}": {
        "*": {
          action_: {
            type_: "output",
            option: 1
          },
          nextState: "1"
        }
      },
      "{...}": {
        "0|1|2|3|a|as|b|p|bp": {
          action_: "o=",
          nextState: "o"
        },
        "o|d|D|q|qd|qD|dq": {
          action_: ["output", "o="],
          nextState: "o"
        }
      },
      "$...$": {
        "a": {
          action_: "a="
        },
        // 2$n$
        "0|1|2|3|as|b|p|bp|o": {
          action_: "o=",
          nextState: "o"
        },
        // not 'amount'
        "as|o": {
          action_: "o="
        },
        "q|d|D|qd|qD|dq": {
          action_: ["output", "o="],
          nextState: "o"
        }
      },
      "\\bond{(...)}": {
        "*": {
          action_: [{
            type_: "output",
            option: 2
          }, "bond"],
          nextState: "3"
        }
      },
      "\\frac{(...)}": {
        "*": {
          action_: [{
            type_: "output",
            option: 1
          }, "frac-output"],
          nextState: "3"
        }
      },
      "\\overset{(...)}": {
        "*": {
          action_: [{
            type_: "output",
            option: 2
          }, "overset-output"],
          nextState: "3"
        }
      },
      "\\underset{(...)}": {
        "*": {
          action_: [{
            type_: "output",
            option: 2
          }, "underset-output"],
          nextState: "3"
        }
      },
      "\\underbrace{(...)}": {
        "*": {
          action_: [{
            type_: "output",
            option: 2
          }, "underbrace-output"],
          nextState: "3"
        }
      },
      "\\color{(...)}{(...)}1|\\color(...){(...)}2": {
        "*": {
          action_: [{
            type_: "output",
            option: 2
          }, "color-output"],
          nextState: "3"
        }
      },
      "\\color{(...)}0": {
        "*": {
          action_: [{
            type_: "output",
            option: 2
          }, "color0-output"]
        }
      },
      "\\ce{(...)}": {
        "*": {
          action_: [{
            type_: "output",
            option: 2
          }, "ce"],
          nextState: "3"
        }
      },
      "\\,": {
        "*": {
          action_: [{
            type_: "output",
            option: 1
          }, "copy"],
          nextState: "1"
        }
      },
      "\\x{}{}|\\x{}|\\x": {
        "0|1|2|3|a|as|b|p|bp|o|c0": {
          action_: ["o=", "output"],
          nextState: "3"
        },
        "*": {
          action_: ["output", "o=", "output"],
          nextState: "3"
        }
      },
      "others": {
        "*": {
          action_: [{
            type_: "output",
            option: 1
          }, "copy"],
          nextState: "3"
        }
      },
      "else2": {
        "a": {
          action_: "a to o",
          nextState: "o",
          revisit: true
        },
        "as": {
          action_: ["output", "sb=true"],
          nextState: "1",
          revisit: true
        },
        "r|rt|rd|rdt|rdq": {
          action_: ["output"],
          nextState: "0",
          revisit: true
        },
        "*": {
          action_: ["output", "copy"],
          nextState: "3"
        }
      }
    }),
    actions: {
      "o after d": function oAfterD(buffer, m) {
        var ret;
        if ((buffer.d || "").match(/^[0-9]+$/)) {
          var tmp = buffer.d;
          buffer.d = void 0;
          ret = this["output"](buffer);
          buffer.b = tmp;
        } else {
          ret = this["output"](buffer);
        }
        mhchemParser.actions["o="](buffer, m);
        return ret;
      },
      "d= kv": function dKv(buffer, m) {
        buffer.d = m;
        buffer.dType = "kv";
      },
      "charge or bond": function chargeOrBond(buffer, m) {
        if (buffer["beginsWithBond"]) {
          var ret = [];
          mhchemParser.concatArray(ret, this["output"](buffer));
          mhchemParser.concatArray(ret, mhchemParser.actions["bond"](buffer, m, "-"));
          return ret;
        } else {
          buffer.d = m;
        }
      },
      "- after o/d": function afterOD(buffer, m, isAfterD) {
        var c1 = mhchemParser.patterns.match_("orbital", buffer.o || "");
        var c2 = mhchemParser.patterns.match_("one lowercase greek letter $", buffer.o || "");
        var c3 = mhchemParser.patterns.match_("one lowercase latin letter $", buffer.o || "");
        var c4 = mhchemParser.patterns.match_("$one lowercase latin letter$ $", buffer.o || "");
        var hyphenFollows = m === "-" && (c1 && c1.remainder === "" || c2 || c3 || c4);
        if (hyphenFollows && !buffer.a && !buffer.b && !buffer.p && !buffer.d && !buffer.q && !c1 && c3) {
          buffer.o = "$" + buffer.o + "$";
        }
        var ret = [];
        if (hyphenFollows) {
          mhchemParser.concatArray(ret, this["output"](buffer));
          ret.push({
            type_: "hyphen"
          });
        } else {
          c1 = mhchemParser.patterns.match_("digits", buffer.d || "");
          if (isAfterD && c1 && c1.remainder === "") {
            mhchemParser.concatArray(ret, mhchemParser.actions["d="](buffer, m));
            mhchemParser.concatArray(ret, this["output"](buffer));
          } else {
            mhchemParser.concatArray(ret, this["output"](buffer));
            mhchemParser.concatArray(ret, mhchemParser.actions["bond"](buffer, m, "-"));
          }
        }
        return ret;
      },
      "a to o": function aToO(buffer) {
        buffer.o = buffer.a;
        buffer.a = void 0;
      },
      "sb=true": function sbTrue(buffer) {
        buffer.sb = true;
      },
      "sb=false": function sbFalse(buffer) {
        buffer.sb = false;
      },
      "beginsWithBond=true": function beginsWithBondTrue(buffer) {
        buffer["beginsWithBond"] = true;
      },
      "beginsWithBond=false": function beginsWithBondFalse(buffer) {
        buffer["beginsWithBond"] = false;
      },
      "parenthesisLevel++": function parenthesisLevel(buffer) {
        buffer["parenthesisLevel"]++;
      },
      "parenthesisLevel--": function parenthesisLevel2(buffer) {
        buffer["parenthesisLevel"]--;
      },
      "state of aggregation": function stateOfAggregation(buffer, m) {
        return {
          type_: "state of aggregation",
          p1: mhchemParser.go(m, "o")
        };
      },
      "comma": function comma(buffer, m) {
        var a2 = m.replace(/\s*$/, "");
        var withSpace = a2 !== m;
        if (withSpace && buffer["parenthesisLevel"] === 0) {
          return {
            type_: "comma enumeration L",
            p1: a2
          };
        } else {
          return {
            type_: "comma enumeration M",
            p1: a2
          };
        }
      },
      "output": function output(buffer, m, entityFollows) {
        var ret;
        if (!buffer.r) {
          ret = [];
          if (!buffer.a && !buffer.b && !buffer.p && !buffer.o && !buffer.q && !buffer.d && !entityFollows) ;
          else {
            if (buffer.sb) {
              ret.push({
                type_: "entitySkip"
              });
            }
            if (!buffer.o && !buffer.q && !buffer.d && !buffer.b && !buffer.p && entityFollows !== 2) {
              buffer.o = buffer.a;
              buffer.a = void 0;
            } else if (!buffer.o && !buffer.q && !buffer.d && (buffer.b || buffer.p)) {
              buffer.o = buffer.a;
              buffer.d = buffer.b;
              buffer.q = buffer.p;
              buffer.a = buffer.b = buffer.p = void 0;
            } else {
              if (buffer.o && buffer.dType === "kv" && mhchemParser.patterns.match_("d-oxidation$", buffer.d || "")) {
                buffer.dType = "oxidation";
              } else if (buffer.o && buffer.dType === "kv" && !buffer.q) {
                buffer.dType = void 0;
              }
            }
            ret.push({
              type_: "chemfive",
              a: mhchemParser.go(buffer.a, "a"),
              b: mhchemParser.go(buffer.b, "bd"),
              p: mhchemParser.go(buffer.p, "pq"),
              o: mhchemParser.go(buffer.o, "o"),
              q: mhchemParser.go(buffer.q, "pq"),
              d: mhchemParser.go(buffer.d, buffer.dType === "oxidation" ? "oxidation" : "bd"),
              dType: buffer.dType
            });
          }
        } else {
          var rd2;
          if (buffer.rdt === "M") {
            rd2 = mhchemParser.go(buffer.rd, "tex-math");
          } else if (buffer.rdt === "T") {
            rd2 = [{
              type_: "text",
              p1: buffer.rd || ""
            }];
          } else {
            rd2 = mhchemParser.go(buffer.rd);
          }
          var rq2;
          if (buffer.rqt === "M") {
            rq2 = mhchemParser.go(buffer.rq, "tex-math");
          } else if (buffer.rqt === "T") {
            rq2 = [{
              type_: "text",
              p1: buffer.rq || ""
            }];
          } else {
            rq2 = mhchemParser.go(buffer.rq);
          }
          ret = {
            type_: "arrow",
            r: buffer.r,
            rd: rd2,
            rq: rq2
          };
        }
        for (var p2 in buffer) {
          if (p2 !== "parenthesisLevel" && p2 !== "beginsWithBond") {
            delete buffer[p2];
          }
        }
        return ret;
      },
      "oxidation-output": function oxidationOutput(buffer, m) {
        var ret = ["{"];
        mhchemParser.concatArray(ret, mhchemParser.go(m, "oxidation"));
        ret.push("}");
        return ret;
      },
      "frac-output": function fracOutput(buffer, m) {
        return {
          type_: "frac-ce",
          p1: mhchemParser.go(m[0]),
          p2: mhchemParser.go(m[1])
        };
      },
      "overset-output": function oversetOutput(buffer, m) {
        return {
          type_: "overset",
          p1: mhchemParser.go(m[0]),
          p2: mhchemParser.go(m[1])
        };
      },
      "underset-output": function undersetOutput(buffer, m) {
        return {
          type_: "underset",
          p1: mhchemParser.go(m[0]),
          p2: mhchemParser.go(m[1])
        };
      },
      "underbrace-output": function underbraceOutput(buffer, m) {
        return {
          type_: "underbrace",
          p1: mhchemParser.go(m[0]),
          p2: mhchemParser.go(m[1])
        };
      },
      "color-output": function colorOutput(buffer, m) {
        return {
          type_: "color",
          color1: m[0],
          color2: mhchemParser.go(m[1])
        };
      },
      "r=": function r(buffer, m) {
        buffer.r = m;
      },
      "rdt=": function rdt(buffer, m) {
        buffer.rdt = m;
      },
      "rd=": function rd(buffer, m) {
        buffer.rd = m;
      },
      "rqt=": function rqt(buffer, m) {
        buffer.rqt = m;
      },
      "rq=": function rq(buffer, m) {
        buffer.rq = m;
      },
      "operator": function operator(buffer, m, p1) {
        return {
          type_: "operator",
          kind_: p1 || m
        };
      }
    }
  },
  "a": {
    transitions: mhchemParser.createTransitions({
      "empty": {
        "*": {}
      },
      "1/2$": {
        "0": {
          action_: "1/2"
        }
      },
      "else": {
        "0": {
          nextState: "1",
          revisit: true
        }
      },
      "$(...)$": {
        "*": {
          action_: "tex-math tight",
          nextState: "1"
        }
      },
      ",": {
        "*": {
          action_: {
            type_: "insert",
            option: "commaDecimal"
          }
        }
      },
      "else2": {
        "*": {
          action_: "copy"
        }
      }
    }),
    actions: {}
  },
  "o": {
    transitions: mhchemParser.createTransitions({
      "empty": {
        "*": {}
      },
      "1/2$": {
        "0": {
          action_: "1/2"
        }
      },
      "else": {
        "0": {
          nextState: "1",
          revisit: true
        }
      },
      "letters": {
        "*": {
          action_: "rm"
        }
      },
      "\\ca": {
        "*": {
          action_: {
            type_: "insert",
            option: "circa"
          }
        }
      },
      "\\x{}{}|\\x{}|\\x": {
        "*": {
          action_: "copy"
        }
      },
      "${(...)}$|$(...)$": {
        "*": {
          action_: "tex-math"
        }
      },
      "{(...)}": {
        "*": {
          action_: "{text}"
        }
      },
      "else2": {
        "*": {
          action_: "copy"
        }
      }
    }),
    actions: {}
  },
  "text": {
    transitions: mhchemParser.createTransitions({
      "empty": {
        "*": {
          action_: "output"
        }
      },
      "{...}": {
        "*": {
          action_: "text="
        }
      },
      "${(...)}$|$(...)$": {
        "*": {
          action_: "tex-math"
        }
      },
      "\\greek": {
        "*": {
          action_: ["output", "rm"]
        }
      },
      "\\,|\\x{}{}|\\x{}|\\x": {
        "*": {
          action_: ["output", "copy"]
        }
      },
      "else": {
        "*": {
          action_: "text="
        }
      }
    }),
    actions: {
      "output": function output2(buffer) {
        if (buffer.text_) {
          var ret = {
            type_: "text",
            p1: buffer.text_
          };
          for (var p2 in buffer) {
            delete buffer[p2];
          }
          return ret;
        }
      }
    }
  },
  "pq": {
    transitions: mhchemParser.createTransitions({
      "empty": {
        "*": {}
      },
      "state of aggregation $": {
        "*": {
          action_: "state of aggregation"
        }
      },
      "i$": {
        "0": {
          nextState: "!f",
          revisit: true
        }
      },
      "(KV letters),": {
        "0": {
          action_: "rm",
          nextState: "0"
        }
      },
      "formula$": {
        "0": {
          nextState: "f",
          revisit: true
        }
      },
      "1/2$": {
        "0": {
          action_: "1/2"
        }
      },
      "else": {
        "0": {
          nextState: "!f",
          revisit: true
        }
      },
      "${(...)}$|$(...)$": {
        "*": {
          action_: "tex-math"
        }
      },
      "{(...)}": {
        "*": {
          action_: "text"
        }
      },
      "a-z": {
        "f": {
          action_: "tex-math"
        }
      },
      "letters": {
        "*": {
          action_: "rm"
        }
      },
      "-9.,9": {
        "*": {
          action_: "9,9"
        }
      },
      ",": {
        "*": {
          action_: {
            type_: "insert+p1",
            option: "comma enumeration S"
          }
        }
      },
      "\\color{(...)}{(...)}1|\\color(...){(...)}2": {
        "*": {
          action_: "color-output"
        }
      },
      "\\color{(...)}0": {
        "*": {
          action_: "color0-output"
        }
      },
      "\\ce{(...)}": {
        "*": {
          action_: "ce"
        }
      },
      "\\,|\\x{}{}|\\x{}|\\x": {
        "*": {
          action_: "copy"
        }
      },
      "else2": {
        "*": {
          action_: "copy"
        }
      }
    }),
    actions: {
      "state of aggregation": function stateOfAggregation2(buffer, m) {
        return {
          type_: "state of aggregation subscript",
          p1: mhchemParser.go(m, "o")
        };
      },
      "color-output": function colorOutput2(buffer, m) {
        return {
          type_: "color",
          color1: m[0],
          color2: mhchemParser.go(m[1], "pq")
        };
      }
    }
  },
  "bd": {
    transitions: mhchemParser.createTransitions({
      "empty": {
        "*": {}
      },
      "x$": {
        "0": {
          nextState: "!f",
          revisit: true
        }
      },
      "formula$": {
        "0": {
          nextState: "f",
          revisit: true
        }
      },
      "else": {
        "0": {
          nextState: "!f",
          revisit: true
        }
      },
      "-9.,9 no missing 0": {
        "*": {
          action_: "9,9"
        }
      },
      ".": {
        "*": {
          action_: {
            type_: "insert",
            option: "electron dot"
          }
        }
      },
      "a-z": {
        "f": {
          action_: "tex-math"
        }
      },
      "x": {
        "*": {
          action_: {
            type_: "insert",
            option: "KV x"
          }
        }
      },
      "letters": {
        "*": {
          action_: "rm"
        }
      },
      "'": {
        "*": {
          action_: {
            type_: "insert",
            option: "prime"
          }
        }
      },
      "${(...)}$|$(...)$": {
        "*": {
          action_: "tex-math"
        }
      },
      "{(...)}": {
        "*": {
          action_: "text"
        }
      },
      "\\color{(...)}{(...)}1|\\color(...){(...)}2": {
        "*": {
          action_: "color-output"
        }
      },
      "\\color{(...)}0": {
        "*": {
          action_: "color0-output"
        }
      },
      "\\ce{(...)}": {
        "*": {
          action_: "ce"
        }
      },
      "\\,|\\x{}{}|\\x{}|\\x": {
        "*": {
          action_: "copy"
        }
      },
      "else2": {
        "*": {
          action_: "copy"
        }
      }
    }),
    actions: {
      "color-output": function colorOutput3(buffer, m) {
        return {
          type_: "color",
          color1: m[0],
          color2: mhchemParser.go(m[1], "bd")
        };
      }
    }
  },
  "oxidation": {
    transitions: mhchemParser.createTransitions({
      "empty": {
        "*": {}
      },
      "roman numeral": {
        "*": {
          action_: "roman-numeral"
        }
      },
      "${(...)}$|$(...)$": {
        "*": {
          action_: "tex-math"
        }
      },
      "else": {
        "*": {
          action_: "copy"
        }
      }
    }),
    actions: {
      "roman-numeral": function romanNumeral(buffer, m) {
        return {
          type_: "roman numeral",
          p1: m || ""
        };
      }
    }
  },
  "tex-math": {
    transitions: mhchemParser.createTransitions({
      "empty": {
        "*": {
          action_: "output"
        }
      },
      "\\ce{(...)}": {
        "*": {
          action_: ["output", "ce"]
        }
      },
      "{...}|\\,|\\x{}{}|\\x{}|\\x": {
        "*": {
          action_: "o="
        }
      },
      "else": {
        "*": {
          action_: "o="
        }
      }
    }),
    actions: {
      "output": function output3(buffer) {
        if (buffer.o) {
          var ret = {
            type_: "tex-math",
            p1: buffer.o
          };
          for (var p2 in buffer) {
            delete buffer[p2];
          }
          return ret;
        }
      }
    }
  },
  "tex-math tight": {
    transitions: mhchemParser.createTransitions({
      "empty": {
        "*": {
          action_: "output"
        }
      },
      "\\ce{(...)}": {
        "*": {
          action_: ["output", "ce"]
        }
      },
      "{...}|\\,|\\x{}{}|\\x{}|\\x": {
        "*": {
          action_: "o="
        }
      },
      "-|+": {
        "*": {
          action_: "tight operator"
        }
      },
      "else": {
        "*": {
          action_: "o="
        }
      }
    }),
    actions: {
      "tight operator": function tightOperator(buffer, m) {
        buffer.o = (buffer.o || "") + "{" + m + "}";
      },
      "output": function output4(buffer) {
        if (buffer.o) {
          var ret = {
            type_: "tex-math",
            p1: buffer.o
          };
          for (var p2 in buffer) {
            delete buffer[p2];
          }
          return ret;
        }
      }
    }
  },
  "9,9": {
    transitions: mhchemParser.createTransitions({
      "empty": {
        "*": {}
      },
      ",": {
        "*": {
          action_: "comma"
        }
      },
      "else": {
        "*": {
          action_: "copy"
        }
      }
    }),
    actions: {
      "comma": function comma2() {
        return {
          type_: "commaDecimal"
        };
      }
    }
  },
  //#endregion
  //
  // \pu state machines
  //
  //#region pu
  "pu": {
    transitions: mhchemParser.createTransitions({
      "empty": {
        "*": {
          action_: "output"
        }
      },
      "space$": {
        "*": {
          action_: ["output", "space"]
        }
      },
      "{[(|)]}": {
        "0|a": {
          action_: "copy"
        }
      },
      "(-)(9)^(-9)": {
        "0": {
          action_: "number^",
          nextState: "a"
        }
      },
      "(-)(9.,9)(e)(99)": {
        "0": {
          action_: "enumber",
          nextState: "a"
        }
      },
      "space": {
        "0|a": {}
      },
      "pm-operator": {
        "0|a": {
          action_: {
            type_: "operator",
            option: "\\pm"
          },
          nextState: "0"
        }
      },
      "operator": {
        "0|a": {
          action_: "copy",
          nextState: "0"
        }
      },
      "//": {
        "d": {
          action_: "o=",
          nextState: "/"
        }
      },
      "/": {
        "d": {
          action_: "o=",
          nextState: "/"
        }
      },
      "{...}|else": {
        "0|d": {
          action_: "d=",
          nextState: "d"
        },
        "a": {
          action_: ["space", "d="],
          nextState: "d"
        },
        "/|q": {
          action_: "q=",
          nextState: "q"
        }
      }
    }),
    actions: {
      "enumber": function enumber(buffer, m) {
        var ret = [];
        if (m[0] === "+-" || m[0] === "+/-") {
          ret.push("\\pm ");
        } else if (m[0]) {
          ret.push(m[0]);
        }
        if (m[1]) {
          mhchemParser.concatArray(ret, mhchemParser.go(m[1], "pu-9,9"));
          if (m[2]) {
            if (m[2].match(/[,.]/)) {
              mhchemParser.concatArray(ret, mhchemParser.go(m[2], "pu-9,9"));
            } else {
              ret.push(m[2]);
            }
          }
          m[3] = m[4] || m[3];
          if (m[3]) {
            m[3] = m[3].trim();
            if (m[3] === "e" || m[3].substr(0, 1) === "*") {
              ret.push({
                type_: "cdot"
              });
            } else {
              ret.push({
                type_: "times"
              });
            }
          }
        }
        if (m[3]) {
          ret.push("10^{" + m[5] + "}");
        }
        return ret;
      },
      "number^": function number(buffer, m) {
        var ret = [];
        if (m[0] === "+-" || m[0] === "+/-") {
          ret.push("\\pm ");
        } else if (m[0]) {
          ret.push(m[0]);
        }
        mhchemParser.concatArray(ret, mhchemParser.go(m[1], "pu-9,9"));
        ret.push("^{" + m[2] + "}");
        return ret;
      },
      "operator": function operator2(buffer, m, p1) {
        return {
          type_: "operator",
          kind_: p1 || m
        };
      },
      "space": function space() {
        return {
          type_: "pu-space-1"
        };
      },
      "output": function output5(buffer) {
        var ret;
        var md = mhchemParser.patterns.match_("{(...)}", buffer.d || "");
        if (md && md.remainder === "") {
          buffer.d = md.match_;
        }
        var mq = mhchemParser.patterns.match_("{(...)}", buffer.q || "");
        if (mq && mq.remainder === "") {
          buffer.q = mq.match_;
        }
        if (buffer.d) {
          buffer.d = buffer.d.replace(/\u00B0C|\^oC|\^{o}C/g, "{}^{\\circ}C");
          buffer.d = buffer.d.replace(/\u00B0F|\^oF|\^{o}F/g, "{}^{\\circ}F");
        }
        if (buffer.q) {
          buffer.q = buffer.q.replace(/\u00B0C|\^oC|\^{o}C/g, "{}^{\\circ}C");
          buffer.q = buffer.q.replace(/\u00B0F|\^oF|\^{o}F/g, "{}^{\\circ}F");
          var b5 = {
            d: mhchemParser.go(buffer.d, "pu"),
            q: mhchemParser.go(buffer.q, "pu")
          };
          if (buffer.o === "//") {
            ret = {
              type_: "pu-frac",
              p1: b5.d,
              p2: b5.q
            };
          } else {
            ret = b5.d;
            if (b5.d.length > 1 || b5.q.length > 1) {
              ret.push({
                type_: " / "
              });
            } else {
              ret.push({
                type_: "/"
              });
            }
            mhchemParser.concatArray(ret, b5.q);
          }
        } else {
          ret = mhchemParser.go(buffer.d, "pu-2");
        }
        for (var p2 in buffer) {
          delete buffer[p2];
        }
        return ret;
      }
    }
  },
  "pu-2": {
    transitions: mhchemParser.createTransitions({
      "empty": {
        "*": {
          action_: "output"
        }
      },
      "*": {
        "*": {
          action_: ["output", "cdot"],
          nextState: "0"
        }
      },
      "\\x": {
        "*": {
          action_: "rm="
        }
      },
      "space": {
        "*": {
          action_: ["output", "space"],
          nextState: "0"
        }
      },
      "^{(...)}|^(-1)": {
        "1": {
          action_: "^(-1)"
        }
      },
      "-9.,9": {
        "0": {
          action_: "rm=",
          nextState: "0"
        },
        "1": {
          action_: "^(-1)",
          nextState: "0"
        }
      },
      "{...}|else": {
        "*": {
          action_: "rm=",
          nextState: "1"
        }
      }
    }),
    actions: {
      "cdot": function cdot() {
        return {
          type_: "tight cdot"
        };
      },
      "^(-1)": function _9(buffer, m) {
        buffer.rm += "^{" + m + "}";
      },
      "space": function space2() {
        return {
          type_: "pu-space-2"
        };
      },
      "output": function output6(buffer) {
        var ret = [];
        if (buffer.rm) {
          var mrm = mhchemParser.patterns.match_("{(...)}", buffer.rm || "");
          if (mrm && mrm.remainder === "") {
            ret = mhchemParser.go(mrm.match_, "pu");
          } else {
            ret = {
              type_: "rm",
              p1: buffer.rm
            };
          }
        }
        for (var p2 in buffer) {
          delete buffer[p2];
        }
        return ret;
      }
    }
  },
  "pu-9,9": {
    transitions: mhchemParser.createTransitions({
      "empty": {
        "0": {
          action_: "output-0"
        },
        "o": {
          action_: "output-o"
        }
      },
      ",": {
        "0": {
          action_: ["output-0", "comma"],
          nextState: "o"
        }
      },
      ".": {
        "0": {
          action_: ["output-0", "copy"],
          nextState: "o"
        }
      },
      "else": {
        "*": {
          action_: "text="
        }
      }
    }),
    actions: {
      "comma": function comma3() {
        return {
          type_: "commaDecimal"
        };
      },
      "output-0": function output0(buffer) {
        var ret = [];
        buffer.text_ = buffer.text_ || "";
        if (buffer.text_.length > 4) {
          var a2 = buffer.text_.length % 3;
          if (a2 === 0) {
            a2 = 3;
          }
          for (var i = buffer.text_.length - 3; i > 0; i -= 3) {
            ret.push(buffer.text_.substr(i, 3));
            ret.push({
              type_: "1000 separator"
            });
          }
          ret.push(buffer.text_.substr(0, a2));
          ret.reverse();
        } else {
          ret.push(buffer.text_);
        }
        for (var p2 in buffer) {
          delete buffer[p2];
        }
        return ret;
      },
      "output-o": function outputO(buffer) {
        var ret = [];
        buffer.text_ = buffer.text_ || "";
        if (buffer.text_.length > 4) {
          var a2 = buffer.text_.length - 3;
          for (var i = 0; i < a2; i += 3) {
            ret.push(buffer.text_.substr(i, 3));
            ret.push({
              type_: "1000 separator"
            });
          }
          ret.push(buffer.text_.substr(i));
        } else {
          ret.push(buffer.text_);
        }
        for (var p2 in buffer) {
          delete buffer[p2];
        }
        return ret;
      }
    }
  }
  //#endregion
};
var texify = {
  go: function go2(input, isInner) {
    if (!input) {
      return "";
    }
    var res = "";
    var cee = false;
    for (var i = 0; i < input.length; i++) {
      var inputi = input[i];
      if (typeof inputi === "string") {
        res += inputi;
      } else {
        res += texify._go2(inputi);
        if (inputi.type_ === "1st-level escape") {
          cee = true;
        }
      }
    }
    if (!isInner && !cee && res) {
      res = "{" + res + "}";
    }
    return res;
  },
  _goInner: function _goInner(input) {
    if (!input) {
      return input;
    }
    return texify.go(input, true);
  },
  _go2: function _go2(buf) {
    var res;
    switch (buf.type_) {
      case "chemfive":
        res = "";
        var b5 = {
          a: texify._goInner(buf.a),
          b: texify._goInner(buf.b),
          p: texify._goInner(buf.p),
          o: texify._goInner(buf.o),
          q: texify._goInner(buf.q),
          d: texify._goInner(buf.d)
        };
        if (b5.a) {
          if (b5.a.match(/^[+\-]/)) {
            b5.a = "{" + b5.a + "}";
          }
          res += b5.a + "\\,";
        }
        if (b5.b || b5.p) {
          res += "{\\vphantom{X}}";
          res += "^{\\hphantom{" + (b5.b || "") + "}}_{\\hphantom{" + (b5.p || "") + "}}";
          res += "{\\vphantom{X}}";
          res += "^{\\smash[t]{\\vphantom{2}}\\mathllap{" + (b5.b || "") + "}}";
          res += "_{\\vphantom{2}\\mathllap{\\smash[t]{" + (b5.p || "") + "}}}";
        }
        if (b5.o) {
          if (b5.o.match(/^[+\-]/)) {
            b5.o = "{" + b5.o + "}";
          }
          res += b5.o;
        }
        if (buf.dType === "kv") {
          if (b5.d || b5.q) {
            res += "{\\vphantom{X}}";
          }
          if (b5.d) {
            res += "^{" + b5.d + "}";
          }
          if (b5.q) {
            res += "_{\\smash[t]{" + b5.q + "}}";
          }
        } else if (buf.dType === "oxidation") {
          if (b5.d) {
            res += "{\\vphantom{X}}";
            res += "^{" + b5.d + "}";
          }
          if (b5.q) {
            res += "{\\vphantom{X}}";
            res += "_{\\smash[t]{" + b5.q + "}}";
          }
        } else {
          if (b5.q) {
            res += "{\\vphantom{X}}";
            res += "_{\\smash[t]{" + b5.q + "}}";
          }
          if (b5.d) {
            res += "{\\vphantom{X}}";
            res += "^{" + b5.d + "}";
          }
        }
        break;
      case "rm":
        res = "\\mathrm{" + buf.p1 + "}";
        break;
      case "text":
        if (buf.p1.match(/[\^_]/)) {
          buf.p1 = buf.p1.replace(" ", "~").replace("-", "\\text{-}");
          res = "\\mathrm{" + buf.p1 + "}";
        } else {
          res = "\\text{" + buf.p1 + "}";
        }
        break;
      case "roman numeral":
        res = "\\mathrm{" + buf.p1 + "}";
        break;
      case "state of aggregation":
        res = "\\mskip2mu " + texify._goInner(buf.p1);
        break;
      case "state of aggregation subscript":
        res = "\\mskip1mu " + texify._goInner(buf.p1);
        break;
      case "bond":
        res = texify._getBond(buf.kind_);
        if (!res) {
          throw ["MhchemErrorBond", "mhchem Error. Unknown bond type (" + buf.kind_ + ")"];
        }
        break;
      case "frac":
        var c = "\\frac{" + buf.p1 + "}{" + buf.p2 + "}";
        res = "\\mathchoice{\\textstyle" + c + "}{" + c + "}{" + c + "}{" + c + "}";
        break;
      case "pu-frac":
        var d2 = "\\frac{" + texify._goInner(buf.p1) + "}{" + texify._goInner(buf.p2) + "}";
        res = "\\mathchoice{\\textstyle" + d2 + "}{" + d2 + "}{" + d2 + "}{" + d2 + "}";
        break;
      case "tex-math":
        res = buf.p1 + " ";
        break;
      case "frac-ce":
        res = "\\frac{" + texify._goInner(buf.p1) + "}{" + texify._goInner(buf.p2) + "}";
        break;
      case "overset":
        res = "\\overset{" + texify._goInner(buf.p1) + "}{" + texify._goInner(buf.p2) + "}";
        break;
      case "underset":
        res = "\\underset{" + texify._goInner(buf.p1) + "}{" + texify._goInner(buf.p2) + "}";
        break;
      case "underbrace":
        res = "\\underbrace{" + texify._goInner(buf.p1) + "}_{" + texify._goInner(buf.p2) + "}";
        break;
      case "color":
        res = "{\\color{" + buf.color1 + "}{" + texify._goInner(buf.color2) + "}}";
        break;
      case "color0":
        res = "\\color{" + buf.color + "}";
        break;
      case "arrow":
        var b6 = {
          rd: texify._goInner(buf.rd),
          rq: texify._goInner(buf.rq)
        };
        var arrow2 = "\\x" + texify._getArrow(buf.r);
        if (b6.rq) {
          arrow2 += "[{" + b6.rq + "}]";
        }
        if (b6.rd) {
          arrow2 += "{" + b6.rd + "}";
        } else {
          arrow2 += "{}";
        }
        res = arrow2;
        break;
      case "operator":
        res = texify._getOperator(buf.kind_);
        break;
      case "1st-level escape":
        res = buf.p1 + " ";
        break;
      case "space":
        res = " ";
        break;
      case "entitySkip":
        res = "~";
        break;
      case "pu-space-1":
        res = "~";
        break;
      case "pu-space-2":
        res = "\\mkern3mu ";
        break;
      case "1000 separator":
        res = "\\mkern2mu ";
        break;
      case "commaDecimal":
        res = "{,}";
        break;
      case "comma enumeration L":
        res = "{" + buf.p1 + "}\\mkern6mu ";
        break;
      case "comma enumeration M":
        res = "{" + buf.p1 + "}\\mkern3mu ";
        break;
      case "comma enumeration S":
        res = "{" + buf.p1 + "}\\mkern1mu ";
        break;
      case "hyphen":
        res = "\\text{-}";
        break;
      case "addition compound":
        res = "\\,{\\cdot}\\,";
        break;
      case "electron dot":
        res = "\\mkern1mu \\bullet\\mkern1mu ";
        break;
      case "KV x":
        res = "{\\times}";
        break;
      case "prime":
        res = "\\prime ";
        break;
      case "cdot":
        res = "\\cdot ";
        break;
      case "tight cdot":
        res = "\\mkern1mu{\\cdot}\\mkern1mu ";
        break;
      case "times":
        res = "\\times ";
        break;
      case "circa":
        res = "{\\sim}";
        break;
      case "^":
        res = "uparrow";
        break;
      case "v":
        res = "downarrow";
        break;
      case "ellipsis":
        res = "\\ldots ";
        break;
      case "/":
        res = "/";
        break;
      case " / ":
        res = "\\,/\\,";
        break;
      default:
        throw ["MhchemBugT", "mhchem bug T. Please report."];
    }
    return res;
  },
  _getArrow: function _getArrow(a2) {
    switch (a2) {
      case "->":
        return "rightarrow";
      case "\u2192":
        return "rightarrow";
      case "\u27F6":
        return "rightarrow";
      case "<-":
        return "leftarrow";
      case "<->":
        return "leftrightarrow";
      case "<-->":
        return "rightleftarrows";
      case "<=>":
        return "rightleftharpoons";
      case "\u21CC":
        return "rightleftharpoons";
      case "<=>>":
        return "rightequilibrium";
      case "<<=>":
        return "leftequilibrium";
      default:
        throw ["MhchemBugT", "mhchem bug T. Please report."];
    }
  },
  _getBond: function _getBond(a2) {
    switch (a2) {
      case "-":
        return "{-}";
      case "1":
        return "{-}";
      case "=":
        return "{=}";
      case "2":
        return "{=}";
      case "#":
        return "{\\equiv}";
      case "3":
        return "{\\equiv}";
      case "~":
        return "{\\tripledash}";
      case "~-":
        return "{\\mathrlap{\\raisebox{-.1em}{$-$}}\\raisebox{.1em}{$\\tripledash$}}";
      case "~=":
        return "{\\mathrlap{\\raisebox{-.2em}{$-$}}\\mathrlap{\\raisebox{.2em}{$\\tripledash$}}-}";
      case "~--":
        return "{\\mathrlap{\\raisebox{-.2em}{$-$}}\\mathrlap{\\raisebox{.2em}{$\\tripledash$}}-}";
      case "-~-":
        return "{\\mathrlap{\\raisebox{-.2em}{$-$}}\\mathrlap{\\raisebox{.2em}{$-$}}\\tripledash}";
      case "...":
        return "{{\\cdot}{\\cdot}{\\cdot}}";
      case "....":
        return "{{\\cdot}{\\cdot}{\\cdot}{\\cdot}}";
      case "->":
        return "{\\rightarrow}";
      case "<-":
        return "{\\leftarrow}";
      case "<":
        return "{<}";
      case ">":
        return "{>}";
      default:
        throw ["MhchemBugT", "mhchem bug T. Please report."];
    }
  },
  _getOperator: function _getOperator(a2) {
    switch (a2) {
      case "+":
        return " {}+{} ";
      case "-":
        return " {}-{} ";
      case "=":
        return " {}={} ";
      case "<":
        return " {}<{} ";
      case ">":
        return " {}>{} ";
      case "<<":
        return " {}\\ll{} ";
      case ">>":
        return " {}\\gg{} ";
      case "\\pm":
        return " {}\\pm{} ";
      case "\\approx":
        return " {}\\approx{} ";
      case "$\\approx$":
        return " {}\\approx{} ";
      case "v":
        return " \\downarrow{} ";
      case "(v)":
        return " \\downarrow{} ";
      case "^":
        return " \\uparrow{} ";
      case "(^)":
        return " \\uparrow{} ";
      default:
        throw ["MhchemBugT", "mhchem bug T. Please report."];
    }
  }
};

// ../editor-tiptap/dist/formula.js
function renderKmindFormulaToHtml(args) {
  const latex = args.latex.trim();
  if (latex.length === 0)
    return "";
  try {
    return katex.renderToString(latex, {
      throwOnError: false,
      output: "htmlAndMathml",
      displayMode: Boolean(args.displayMode),
      strict: false
    });
  } catch {
    return `<span class="katex">${escapeHtml2(latex)}</span>`;
  }
}
function tryValidateKmindFormula(latex) {
  const value = latex.trim();
  if (value.length === 0)
    return { ok: false, error: "Empty formula" };
  try {
    katex.renderToString(value, { throwOnError: true, output: "htmlAndMathml", strict: false });
    return { ok: true };
  } catch (error) {
    return { ok: false, error: error instanceof Error ? error.message : "Invalid formula" };
  }
}
function escapeHtml2(text5) {
  return text5.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;").replaceAll("'", "&#039;");
}

// ../editor-tiptap/dist/formula-extension.js
function parseLatexAttr(element) {
  const raw = element.getAttribute("data-km-latex");
  if (typeof raw === "string")
    return raw;
  return element.textContent ?? "";
}
var KmFormula = Node3.create({
  name: "kmindFormula",
  group: "inline",
  inline: true,
  atom: true,
  selectable: true,
  addAttributes() {
    return {
      latex: {
        default: "",
        parseHTML: (element) => element instanceof HTMLElement ? parseLatexAttr(element) : "",
        renderHTML: (attrs) => {
          const latex = typeof attrs.latex === "string" ? attrs.latex : "";
          return { "data-km-latex": latex };
        }
      }
    };
  },
  parseHTML() {
    return [{ tag: 'span[data-km-formula="inline"]' }];
  },
  renderHTML({ node, HTMLAttributes }) {
    const latex = typeof node.attrs.latex === "string" ? node.attrs.latex : "";
    return [
      "span",
      mergeAttributes(HTMLAttributes, {
        "data-km-formula": "inline",
        "data-km-latex": latex
      }),
      latex || "\u220E"
    ];
  },
  addNodeView() {
    if (typeof document === "undefined")
      return null;
    return ({ node }) => {
      let lastLatex = String(node.attrs.latex ?? "");
      const dom = document.createElement("span");
      dom.setAttribute("data-km-formula-view", "inline");
      dom.style.display = "inline-flex";
      dom.style.alignItems = "center";
      dom.style.maxWidth = "100%";
      dom.style.overflow = "visible";
      dom.style.verticalAlign = "middle";
      dom.contentEditable = "false";
      const render3 = (latex) => {
        dom.innerHTML = renderKmindFormulaToHtml({ latex, displayMode: false }) || `<span style="opacity:.55">\u220E</span>`;
      };
      render3(lastLatex);
      return {
        dom,
        update: (updatedNode) => {
          if (updatedNode.type.name !== "kmindFormula")
            return false;
          const nextLatex = String(updatedNode.attrs?.latex ?? "");
          if (lastLatex !== nextLatex) {
            lastLatex = nextLatex;
            render3(nextLatex);
          }
          return true;
        }
      };
    };
  }
});
var KmFormulaBlock = Node3.create({
  name: "kmindFormulaBlock",
  group: "block",
  atom: true,
  selectable: true,
  addAttributes() {
    return {
      latex: {
        default: "",
        parseHTML: (element) => element instanceof HTMLElement ? parseLatexAttr(element) : "",
        renderHTML: (attrs) => {
          const latex = typeof attrs.latex === "string" ? attrs.latex : "";
          return { "data-km-latex": latex };
        }
      }
    };
  },
  parseHTML() {
    return [{ tag: 'div[data-km-formula="block"]' }];
  },
  renderHTML({ node, HTMLAttributes }) {
    const latex = typeof node.attrs.latex === "string" ? node.attrs.latex : "";
    return [
      "div",
      mergeAttributes(HTMLAttributes, {
        "data-km-formula": "block",
        "data-km-latex": latex
      }),
      latex || "\u220E"
    ];
  },
  addNodeView() {
    if (typeof document === "undefined")
      return null;
    return ({ node }) => {
      let lastLatex = String(node.attrs.latex ?? "");
      const dom = document.createElement("div");
      dom.setAttribute("data-km-formula-view", "block");
      dom.style.display = "flex";
      dom.style.justifyContent = "center";
      dom.style.alignItems = "center";
      dom.style.padding = "4px 0";
      dom.contentEditable = "false";
      const render3 = (latex) => {
        dom.innerHTML = renderKmindFormulaToHtml({ latex, displayMode: true }) || `<span style="opacity:.55">\u220E</span>`;
      };
      render3(lastLatex);
      return {
        dom,
        update: (updatedNode) => {
          if (updatedNode.type.name !== "kmindFormulaBlock")
            return false;
          const nextLatex = String(updatedNode.attrs?.latex ?? "");
          if (lastLatex !== nextLatex) {
            lastLatex = nextLatex;
            render3(nextLatex);
          }
          return true;
        }
      };
    };
  }
});

// ../editor-tiptap/dist/index.js
var clozeMarkName = "kmindCloze";
var textStyleMarkName = "kmindTextStyle";
var kmindCustomLinkProtocols = ["siyuan", "obsidian"];
var KmCloze = Mark2.create({
  name: clozeMarkName,
  inclusive: false,
  addAttributes() {
    return {
      id: {
        default: null
      },
      revealMode: {
        default: "click",
        parseHTML: (element) => element.getAttribute("data-km-reveal-mode") ?? "click",
        renderHTML: (attrs) => {
          const value = attrs.revealMode;
          return typeof value === "string" ? { "data-km-reveal-mode": value } : {};
        }
      },
      style: {
        default: "blur",
        parseHTML: (element) => element.getAttribute("data-km-cloze-style") ?? "blur",
        renderHTML: (attrs) => {
          const value = attrs.style;
          return typeof value === "string" ? { "data-km-cloze-style": value } : {};
        }
      },
      hint: {
        default: null,
        parseHTML: (element) => element.getAttribute("data-km-cloze-hint"),
        renderHTML: (attrs) => {
          const value = attrs.hint;
          return typeof value === "string" ? { "data-km-cloze-hint": value } : {};
        }
      }
    };
  },
  parseHTML() {
    return [{ tag: "span[data-km-cloze]" }];
  },
  renderHTML({ HTMLAttributes }) {
    return [
      "span",
      mergeAttributes(HTMLAttributes, {
        "data-km-cloze": "true",
        "data-km-cloze-id": String(HTMLAttributes.id ?? "")
      }),
      0
    ];
  },
  addCommands() {
    return {
      toggleKmindCloze: (attrs) => ({ commands }) => commands.toggleMark(this.name, attrs)
    };
  }
});
var KmTextStyle = Mark2.create({
  name: textStyleMarkName,
  addAttributes() {
    return {
      color: {
        default: null,
        parseHTML: (element) => {
          if (!(element instanceof HTMLElement))
            return null;
          return element.style.color || null;
        }
      },
      background: {
        default: null,
        parseHTML: (element) => {
          if (!(element instanceof HTMLElement))
            return null;
          return element.style.backgroundColor || null;
        }
      },
      fontSize: {
        default: null,
        parseHTML: (element) => {
          if (!(element instanceof HTMLElement))
            return null;
          const raw = element.style.fontSize;
          if (!raw)
            return null;
          const num = Number.parseFloat(raw);
          return Number.isFinite(num) ? num : null;
        }
      },
      fontFamily: {
        default: null,
        parseHTML: (element) => {
          if (!(element instanceof HTMLElement))
            return null;
          const explicit = normalizeFontFamilyAttrValue2(element.getAttribute("data-km-font") ?? "");
          if (explicit)
            return explicit;
          return normalizeFontFamilyAttrValue2(element.style.fontFamily);
        }
      }
    };
  },
  parseHTML() {
    return [{ tag: "span[data-km-text-style]" }];
  },
  renderHTML({ HTMLAttributes }) {
    const color = typeof HTMLAttributes.color === "string" ? HTMLAttributes.color.trim() : "";
    const background = typeof HTMLAttributes.background === "string" ? HTMLAttributes.background.trim() : "";
    const fontSizeRaw = HTMLAttributes.fontSize;
    const fontSizeNum = typeof fontSizeRaw === "number" ? fontSizeRaw : typeof fontSizeRaw === "string" ? Number.parseFloat(fontSizeRaw) : NaN;
    const fontKeyRaw = typeof HTMLAttributes.fontFamily === "string" ? HTMLAttributes.fontFamily.trim() : "";
    const fontFamily = resolveFontFamilyStyle(fontKeyRaw);
    const styles2 = [];
    if (color.length > 0)
      styles2.push(`color:${color}`);
    if (background.length > 0)
      styles2.push(`background-color:${background}`);
    if (Number.isFinite(fontSizeNum) && fontSizeNum > 0)
      styles2.push(`font-size:${fontSizeNum}px`);
    if (fontFamily)
      styles2.push(`font-family:${fontFamily}`);
    const attrs = {
      "data-km-text-style": "true"
    };
    if (fontFamily && isFontFamilyPresetKey(fontKeyRaw))
      attrs["data-km-font"] = fontKeyRaw;
    if (styles2.length > 0)
      attrs.style = styles2.join(";");
    return ["span", attrs, 0];
  }
});
function createKmindTiptapExtensions(options = {}) {
  return [
    index_default.configure({
      ...options.document === false ? { document: false } : {},
      ...options.dropcursor === false ? { dropcursor: false } : {},
      ...options.undoRedo === false ? { undoRedo: false } : {},
      heading: false,
      bulletList: false,
      orderedList: false,
      listItem: false,
      blockquote: false,
      horizontalRule: false,
      link: {
        openOnClick: false,
        autolink: false,
        linkOnPaste: true,
        protocols: [...kmindCustomLinkProtocols],
        HTMLAttributes: {
          rel: "noopener noreferrer"
        }
      }
    }),
    KmFormula,
    KmFormulaBlock,
    KmCloze,
    KmTextStyle,
    KmCodeHighlight
  ];
}
function fromKmind(args) {
  const content = args.content;
  if (!content || content.schemaVersion !== 1)
    return createDocFromText(args.fallbackText);
  if (content.kind === "richtext" && content.engine === "prosemirror") {
    return createEditableDocFromHtmlBackedContent2({
      doc: content.doc,
      html: content.html,
      fallbackText: args.fallbackText
    });
  }
  if (content.kind === "blocks") {
    const richtextBlock = content.blocks.find((block) => block.type === "richtext");
    if (richtextBlock && richtextBlock.engine === "prosemirror") {
      return createEditableDocFromHtmlBackedContent2({
        doc: richtextBlock.doc,
        html: richtextBlock.html,
        fallbackText: args.fallbackText
      });
    }
    return createDocFromText(args.fallbackText);
  }
  if (content.kind === "plain-text") {
    return createDocFromText(content.text);
  }
  return createDocFromText(args.fallbackText);
}
function toKmind(args) {
  return {
    schemaVersion: 1,
    kind: "richtext",
    engine: "prosemirror",
    doc: args.doc,
    html: args.html
  };
}
function createEditableDocFromHtmlBackedContent2(args) {
  return createEditableDocFromHtmlBackedContent({
    doc: args.doc,
    html: args.html,
    fallbackText: args.fallbackText
  });
}
function renderHtml(doc3) {
  return generateHTML(doc3, createKmindTiptapExtensions());
}
function sanitizeExternalHtml(html) {
  if (typeof DOMParser === "undefined")
    return stripHtml2(html);
  try {
    const parser = new DOMParser();
    const doc3 = parser.parseFromString(html, "text/html");
    const allowedTags = /* @__PURE__ */ new Set([
      "p",
      "br",
      "strong",
      "b",
      "em",
      "i",
      "s",
      "strike",
      "del",
      "code",
      "pre",
      "a",
      "span",
      // Formula block uses <div data-km-formula="block">...</div>
      "div"
    ]);
    const walk = (node) => {
      if (node.nodeType === Node.ELEMENT_NODE) {
        const el = node;
        const tag = el.nodeName.toLowerCase();
        if (!allowedTags.has(tag)) {
          const text5 = doc3.createTextNode(el.textContent ?? "");
          el.replaceWith(text5);
          return;
        }
        if (tag === "div") {
          const kind = (el.getAttribute("data-km-formula") ?? "").trim();
          if (kind !== "block") {
            const text5 = ensureParagraphSeparators(doc3, el.textContent ?? "");
            el.replaceWith(text5);
            return;
          }
        }
        for (const attr of Array.from(el.attributes)) {
          const name = attr.name.toLowerCase();
          if (tag === "a" && name === "href")
            continue;
          if (tag === "span" && (name === "style" || name.startsWith("data-km-") && name !== "data-km-action"))
            continue;
          if (tag === "div" && (name === "data-km-formula" || name === "data-km-latex"))
            continue;
          el.removeAttribute(attr.name);
        }
        if (tag === "a") {
          const href = el.getAttribute("href") ?? "";
          if (!href || href.startsWith("javascript:")) {
            const text5 = doc3.createTextNode(el.textContent ?? "");
            el.replaceWith(text5);
            return;
          }
        }
        if (tag === "span") {
          const rawStyle = el.getAttribute("style") ?? "";
          const safeStyle = sanitizeInlineStyle(rawStyle);
          if (safeStyle.length > 0) {
            el.setAttribute("style", safeStyle);
          } else {
            el.removeAttribute("style");
          }
        }
      }
      for (const child of Array.from(node.childNodes)) {
        walk(child);
      }
    };
    walk(doc3.body);
    return doc3.body.innerHTML;
  } catch {
    return stripHtml2(html);
  }
}
function ensureParagraphSeparators(doc3, text5) {
  const raw = String(text5 ?? "");
  if (!raw.includes("\n"))
    return doc3.createTextNode(raw);
  const parts = raw.split(/\r?\n/);
  const frag = doc3.createDocumentFragment();
  parts.forEach((part, idx) => {
    if (idx > 0)
      frag.appendChild(doc3.createElement("br"));
    frag.appendChild(doc3.createTextNode(part));
  });
  return frag;
}
function createDocFromText(text5) {
  return createProseMirrorDocFromText(text5);
}
function stripHtml2(input) {
  return input.replace(/<[^>]*>/g, "");
}
function sanitizeCssColor2(input) {
  const value = input.trim();
  if (value.length === 0)
    return null;
  if (value === "transparent")
    return value;
  if (/^#[0-9a-f]{3,4}$/i.test(value))
    return value;
  if (/^#[0-9a-f]{6}([0-9a-f]{2})?$/i.test(value))
    return value;
  if (/^rgba?\(\s*\d+\s*,\s*\d+\s*,\s*\d+\s*(,\s*(0|1|0?\.\d+)\s*)?\)$/i.test(value))
    return value;
  if (/^hsla?\(\s*\d+\s*,\s*\d+%\s*,\s*\d+%\s*(,\s*(0|1|0?\.\d+)\s*)?\)$/i.test(value))
    return value;
  return null;
}
function sanitizeCssFontSize2(input) {
  const match = input.trim().match(/^(\d+(\.\d+)?)(px)?$/i);
  if (!match)
    return null;
  const num = Number(match[1]);
  if (!Number.isFinite(num))
    return null;
  const clamped = Math.max(8, Math.min(72, num));
  return `${clamped}px`;
}
function sanitizeCssFontFamily2(input) {
  const value = input.trim().replace(/\s*!important\s*$/i, "");
  if (value.length === 0 || value.length > 160)
    return null;
  if (/[;{}<>]/.test(value) || /url\s*\(/i.test(value))
    return null;
  if (!/^[\p{L}\p{N}\s"',._-]+$/u.test(value))
    return null;
  return value;
}
function isFontFamilyPresetKey(value) {
  return value === "sans" || value === "serif" || value === "mono";
}
function normalizeFontFamilyAttrValue2(input) {
  const value = input.trim().replace(/\s*!important\s*$/i, "");
  if (value.length === 0)
    return null;
  const lowered = value.toLowerCase();
  if (lowered.includes("sans-serif") || lowered.includes("system-ui"))
    return "sans";
  if (lowered.includes("monospace"))
    return "mono";
  if (lowered.includes("serif"))
    return lowered.includes("sans-serif") ? "sans" : "serif";
  return sanitizeCssFontFamily2(value);
}
function resolveFontFamilyStyle(key) {
  switch (key) {
    case "sans":
      return "ui-sans-serif, system-ui, sans-serif";
    case "serif":
      return 'ui-serif, Georgia, Cambria, "Times New Roman", Times, serif';
    case "mono":
      return 'ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace';
    default:
      return sanitizeCssFontFamily2(key);
  }
}
function sanitizeInlineStyle(input) {
  if (input.trim().length === 0)
    return "";
  const out = [];
  const decls = input.split(";");
  for (const decl of decls) {
    const [rawProp, ...rawRest] = decl.split(":");
    if (!rawProp)
      continue;
    const prop = rawProp.trim().toLowerCase();
    const value = rawRest.join(":").trim();
    if (value.length === 0)
      continue;
    if (prop === "color") {
      const next = sanitizeCssColor2(value);
      if (next)
        out.push(`color:${next}`);
      continue;
    }
    if (prop === "background-color") {
      const next = sanitizeCssColor2(value);
      if (next)
        out.push(`background-color:${next}`);
      continue;
    }
    if (prop === "font-size") {
      const next = sanitizeCssFontSize2(value);
      if (next)
        out.push(`font-size:${next}`);
      continue;
    }
    if (prop === "font-family") {
      const family = resolveFontFamilyStyle(value.trim());
      if (family)
        out.push(`font-family:${family}`);
    }
  }
  return out.join(";");
}

// ../react/src/mindmap-editor/utils/code-highlight.ts
function highlightCodeToHtml(code, languageHint) {
  return highlightKmindCodeToHtml(code, languageHint);
}
function applyCodeHighlightingToHtml(html) {
  if (!html.includes("<pre") || !html.includes("<code")) return html;
  if (typeof DOMParser === "undefined") return html;
  try {
    const parser = new DOMParser();
    const doc3 = parser.parseFromString(`<div>${html}</div>`, "text/html");
    const container = doc3.body.firstElementChild;
    if (!container) return html;
    const codeBlocks = Array.from(container.querySelectorAll("pre > code"));
    for (const codeEl of codeBlocks) {
      const classAttr = codeEl.getAttribute("class") ?? "";
      const match = classAttr.match(/\blanguage-([a-z0-9_-]+)\b/i);
      const languageHint = match?.[1] ?? null;
      const code = codeEl.textContent ?? "";
      codeEl.innerHTML = highlightCodeToHtml(code, languageHint);
      codeEl.setAttribute("data-km-code-highlight", "true");
    }
    return container.innerHTML;
  } catch {
    return html;
  }
}

// ../react/src/mindmap-editor/utils/formula.ts
function applyFormulaRenderingToHtml(html) {
  if (!html.includes("data-km-formula")) return html;
  if (typeof DOMParser === "undefined") return html;
  try {
    const parser = new DOMParser();
    const doc3 = parser.parseFromString(`<div>${html}</div>`, "text/html");
    const container = doc3.body.firstElementChild;
    if (!container) return html;
    const nodes = Array.from(container.querySelectorAll("[data-km-formula][data-km-latex]"));
    if (nodes.length === 0) return html;
    nodes.forEach((el) => {
      const latex = (el.getAttribute("data-km-latex") ?? "").trim();
      const variant = (el.getAttribute("data-km-formula") ?? "").trim();
      const displayMode = variant === "block";
      const rendered = renderKmindFormulaToHtml({ latex, displayMode });
      if (!rendered) return;
      const host = doc3.createElement(displayMode ? "div" : "span");
      if (displayMode) host.className = "km-formula-block";
      host.innerHTML = rendered;
      el.replaceWith(host);
    });
    return container.innerHTML;
  } catch {
    return html;
  }
}

// ../react/src/mindmap-editor/node-html.ts
function escapeHtml3(text5) {
  return text5.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;").replaceAll("'", "&#039;");
}
function buildProseMirrorMeasureSignature(doc3) {
  try {
    return `doc:${JSON.stringify(doc3)}`;
  } catch {
    return "doc:unserializable";
  }
}
function sanitizeCssColor3(input) {
  const value = input.trim();
  if (value.length === 0) return null;
  if (value === "transparent") return value;
  if (/^#[0-9a-f]{3,4}$/i.test(value)) return value;
  if (/^#[0-9a-f]{6}([0-9a-f]{2})?$/i.test(value)) return value;
  if (/^rgba?\(\s*\d+\s*,\s*\d+\s*,\s*\d+\s*(,\s*(0|1|0?\.\d+)\s*)?\)$/i.test(value)) return value;
  if (/^hsla?\(\s*\d+\s*,\s*\d+%\s*,\s*\d+%\s*(,\s*(0|1|0?\.\d+)\s*)?\)$/i.test(value)) return value;
  return null;
}
function sanitizeCssFontSize3(input) {
  const match = input.trim().match(/^(\d+(\.\d+)?)(px)?$/i);
  if (!match) return null;
  const num = Number(match[1]);
  if (!Number.isFinite(num)) return null;
  const clamped = Math.max(8, Math.min(72, num));
  return `${clamped}px`;
}
function resolveFontFamilyPreset(key) {
  switch (key) {
    case "sans":
      return "ui-sans-serif, system-ui, sans-serif";
    case "serif":
      return 'ui-serif, Georgia, Cambria, "Times New Roman", Times, serif';
    case "mono":
      return 'ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace';
    default:
      return null;
  }
}
function resolveAssetBackedHtml(args) {
  if (!args.html.includes(KMIND_ASSET_URL_PREFIX2)) return args.html;
  const resolveAssetSrc = (assetId) => {
    const asset = args.doc.assets?.[assetId];
    if (!asset || asset.kind !== "image" && asset.kind !== "blob") {
      return { src: TRANSPARENT_PIXEL_DATA_URL, placeholder: true, asset };
    }
    const rawUrl = asset.dataUrl;
    if (!rawUrl.startsWith(KMIND_ASSET_URL_PREFIX2)) {
      return { src: rawUrl || TRANSPARENT_PIXEL_DATA_URL, placeholder: rawUrl.length === 0, asset };
    }
    const objectUrl = args.assetObjectUrlById?.get(assetId) ?? null;
    return { src: objectUrl ?? TRANSPARENT_PIXEL_DATA_URL, placeholder: !objectUrl, asset };
  };
  if (typeof DOMParser === "undefined") {
    return args.html.replace(/kmind-asset:\/\/([A-Za-z0-9._:-]+)/g, (full, rawId) => {
      const assetId = String(rawId ?? "").trim();
      if (!assetId) return full;
      return resolveAssetSrc(assetId).src;
    });
  }
  try {
    const parser = new DOMParser();
    const doc3 = parser.parseFromString(`<div>${args.html}</div>`, "text/html");
    const container = doc3.body.firstElementChild;
    if (!container) return args.html;
    const images = container.querySelectorAll("img");
    for (const image of Array.from(images)) {
      const src = (image.getAttribute("src") ?? "").trim();
      if (!src.startsWith(KMIND_ASSET_URL_PREFIX2)) continue;
      const assetId = src.slice(KMIND_ASSET_URL_PREFIX2.length).trim() || "";
      if (!assetId) continue;
      const resolved = resolveAssetSrc(assetId);
      image.setAttribute("src", resolved.src);
      const resolvedWidth = resolved.asset && resolved.asset.kind === "image" ? resolved.asset.width : void 0;
      const resolvedHeight = resolved.asset && resolved.asset.kind === "image" ? resolved.asset.height : void 0;
      if (!image.getAttribute("width") && typeof resolvedWidth === "number") {
        image.setAttribute("width", String(resolvedWidth));
      }
      if (!image.getAttribute("height") && typeof resolvedHeight === "number") {
        image.setAttribute("height", String(resolvedHeight));
      }
      const currentStyle = image.getAttribute("style") ?? "";
      const extras = ["max-width:100%", "height:auto"];
      if (resolved.placeholder) extras.push("background:rgba(226,232,240,0.55)", "border:1px dashed rgba(148,163,184,0.5)");
      const nextStyle = [currentStyle.trim(), ...extras].filter(Boolean).join(";");
      image.setAttribute("style", nextStyle);
    }
    return container.innerHTML;
  } catch {
    return args.html.replace(/kmind-asset:\/\/([A-Za-z0-9._:-]+)/g, (full, rawId) => {
      const assetId = String(rawId ?? "").trim();
      if (!assetId) return full;
      return resolveAssetSrc(assetId).src;
    });
  }
}
function renderProseMirrorDocHtml(doc3) {
  try {
    if (!doc3 || typeof doc3 !== "object") return null;
    if (doc3.type === "doc") {
      const html = (doc3.content ?? []).map(renderProseMirrorBlockNode).join("");
      return html.length > 0 ? html : "<p></p>";
    }
    return renderProseMirrorBlockNode(doc3);
  } catch {
    return null;
  }
}
function renderProseMirrorBlockNode(node) {
  if (node.type === "paragraph") {
    return `<p>${(node.content ?? []).map(renderProseMirrorInlineNode).join("")}</p>`;
  }
  if (node.type === "codeBlock") {
    return `<pre><code>${escapeHtml3(proseMirrorPlainText(node))}</code></pre>`;
  }
  if (node.type === "kmindFormulaBlock") {
    const latex = String(node.attrs?.latex ?? "").trim();
    const safe = escapeHtml3(latex);
    return `<div data-km-formula="block" data-km-latex="${safe}">${safe || "\u220E"}</div>`;
  }
  if (node.type === "text" || node.type === "hardBreak" || node.type === "kmindFormula") {
    return renderProseMirrorInlineNode(node);
  }
  const children = (node.content ?? []).map(renderProseMirrorInlineNode).join("");
  if (children.length > 0) return children;
  const text5 = proseMirrorPlainText(node);
  return text5.length > 0 ? `<p>${escapeHtml3(text5)}</p>` : "";
}
function renderProseMirrorInlineNode(node) {
  if (node.type === "text") {
    return applyProseMirrorMarks(escapeHtml3(node.text ?? ""), node.marks ?? []);
  }
  if (node.type === "hardBreak") return "<br>";
  if (node.type === "kmindFormula") {
    const latex = String(node.attrs?.latex ?? "").trim();
    const safe = escapeHtml3(latex);
    return `<span data-km-formula="inline" data-km-latex="${safe}">${safe || "\u220E"}</span>`;
  }
  const inner2 = (node.content ?? []).map(renderProseMirrorInlineNode).join("");
  return inner2.length > 0 ? applyProseMirrorMarks(inner2, node.marks ?? []) : escapeHtml3(proseMirrorPlainText(node));
}
function applyProseMirrorMarks(input, marks) {
  let html = input;
  for (const mark of marks) {
    const type = typeof mark?.type === "string" ? mark.type : "";
    const attrs = mark?.attrs && typeof mark.attrs === "object" && !Array.isArray(mark.attrs) ? mark.attrs : {};
    if (type === "bold") {
      html = `<strong>${html}</strong>`;
      continue;
    }
    if (type === "italic") {
      html = `<em>${html}</em>`;
      continue;
    }
    if (type === "strike") {
      html = `<s>${html}</s>`;
      continue;
    }
    if (type === "code") {
      html = `<code>${html}</code>`;
      continue;
    }
    if (type === "link") {
      const href = escapeHtml3(String(attrs.href ?? "").trim());
      html = `<a href="${href}" rel="noopener noreferrer">${html}</a>`;
      continue;
    }
    if (type === "kmindTextStyle") {
      const color = sanitizeCssColor3(String(attrs.color ?? ""));
      const background = sanitizeCssColor3(String(attrs.background ?? ""));
      const fontSize = typeof attrs.fontSize === "number" ? sanitizeCssFontSize3(String(attrs.fontSize)) : typeof attrs.fontSize === "string" ? sanitizeCssFontSize3(attrs.fontSize) : null;
      const fontKey = typeof attrs.fontFamily === "string" ? attrs.fontFamily.trim() : "";
      const fontFamily = resolveFontFamilyPreset(fontKey);
      const styles2 = [];
      if (color) styles2.push(`color:${color}`);
      if (background) styles2.push(`background-color:${background}`);
      if (fontSize) styles2.push(`font-size:${fontSize}`);
      if (fontFamily) styles2.push(`font-family:${fontFamily}`);
      const attrsText = [
        `data-km-text-style="true"`,
        fontFamily && fontKey.length > 0 ? `data-km-font="${escapeHtml3(fontKey)}"` : "",
        styles2.length > 0 ? `style="${escapeHtml3(styles2.join(";"))}"` : ""
      ].filter(Boolean).join(" ");
      html = `<span ${attrsText}>${html}</span>`;
      continue;
    }
    if (type === "kmindCloze") {
      const id = escapeHtml3(String(attrs.id ?? ""));
      const style2 = escapeHtml3(String(attrs.style ?? "blur"));
      const revealMode = escapeHtml3(String(attrs.revealMode ?? "click"));
      const hint = typeof attrs.hint === "string" ? attrs.hint.trim() : "";
      html = [
        `<span data-km-cloze="true"`,
        ` data-km-cloze-id="${id}"`,
        ` data-km-reveal-mode="${revealMode}"`,
        ` data-km-cloze-style="${style2}"`,
        hint.length > 0 ? ` data-km-cloze-hint="${escapeHtml3(hint)}"` : "",
        `>${html}</span>`
      ].join("");
    }
  }
  return html;
}
function proseMirrorPlainText(node) {
  if (node.type === "text") return node.text ?? "";
  if (node.type === "hardBreak") return "\n";
  if (node.type === "kmindFormula" || node.type === "kmindFormulaBlock") {
    return String(node.attrs?.latex ?? "");
  }
  const children = (node.content ?? []).map(proseMirrorPlainText).join("");
  if (node.type === "paragraph" || node.type === "codeBlock") return children;
  return children;
}
function normalizeSiyuanDocGhostText(value) {
  return typeof value === "string" ? value.trim() : "";
}
function codeToEmoji(value) {
  const trimmed = value.trim();
  if (!trimmed) return "";
  if (!/^[0-9a-fA-F-]+$/.test(trimmed)) return trimmed;
  const parts = trimmed.split("-").filter(Boolean);
  try {
    return parts.map((part) => String.fromCodePoint(Number.parseInt(part, 16))).join("");
  } catch {
    return trimmed;
  }
}
function formatSiyuanDocGhostUpdatedAt(value) {
  const raw = typeof value === "number" ? value : Number.parseInt(String(value ?? ""), 10);
  if (!Number.isFinite(raw) || raw <= 0) return "";
  const ts2 = raw < 1e12 ? raw * 1e3 : raw;
  const date = new Date(ts2);
  if (Number.isNaN(date.getTime())) return "";
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");
  const hours = String(date.getHours()).padStart(2, "0");
  const minutes = String(date.getMinutes()).padStart(2, "0");
  return `${year}-${month}-${day} ${hours}:${minutes}`;
}
function resolveSiyuanIconImageSrc(icon) {
  const normalized = icon.trim();
  if (!normalized) return null;
  if (normalized.startsWith("http://") || normalized.startsWith("https://") || normalized.startsWith("/")) {
    return normalized;
  }
  if (normalized.startsWith("api/icon/")) {
    return `/${normalized}`;
  }
  if (normalized.includes(".")) {
    return `/emojis/${normalized}`;
  }
  return null;
}
function renderSiyuanDocGhostIcon(icon, title) {
  const normalized = icon.trim();
  const src = resolveSiyuanIconImageSrc(normalized);
  if (src) {
    return `<span class="km-node-doc-ghost__icon"><img alt="${escapeHtml3(title)}" src="${escapeHtml3(src)}" /></span>`;
  }
  const emoji2 = codeToEmoji(normalized) || "\u{1F4C4}";
  return `<span class="km-node-doc-ghost__icon">${escapeHtml3(emoji2)}</span>`;
}
function renderSiyuanDocGhost(embedProps) {
  const props = embedProps && typeof embedProps === "object" && !Array.isArray(embedProps) ? embedProps : {};
  const docId = normalizeSiyuanDocGhostText(props.docId);
  const title = normalizeSiyuanDocGhostText(props.title) || docId || "Document";
  const hpath = normalizeSiyuanDocGhostText(props.hpath) || title || docId;
  const excerpt = normalizeSiyuanDocGhostText(props.excerpt) || "No preview excerpt yet.";
  const updatedAt = formatSiyuanDocGhostUpdatedAt(props.updatedAt);
  const meta = updatedAt ? `<div class="km-node-doc-ghost__meta"><span>${escapeHtml3(updatedAt)}</span></div>` : "";
  const icon = renderSiyuanDocGhostIcon(normalizeSiyuanDocGhostText(props.icon), title);
  return [
    `<div class="km-node-doc-ghost">`,
    `<div class="km-node-doc-ghost__toolbar">${escapeHtml3(hpath)}</div>`,
    `<div class="km-node-doc-ghost__body">`,
    `<div class="km-node-doc-ghost__header">`,
    icon,
    `<div class="km-node-doc-ghost__content">`,
    `<div class="km-node-doc-ghost__title">${escapeHtml3(title)}</div>`,
    meta,
    `</div>`,
    `</div>`,
    `<div class="km-node-doc-ghost__excerpt">${escapeHtml3(excerpt)}</div>`,
    `</div>`,
    `</div>`
  ].join("");
}
function resolveSequenceNumber(doc3, nodeId) {
  const node = doc3.nodes[nodeId];
  if (!node) return null;
  if (node.parentId) {
    const parent = doc3.nodes[node.parentId];
    if (!parent) return null;
    const index2 = parent.children.indexOf(nodeId);
    return index2 >= 0 ? index2 + 1 : null;
  }
  if (node.parentSummaryId) {
    const summary = doc3.summaries.find((item) => item.id === node.parentSummaryId);
    if (!summary) return null;
    const index2 = summary.children.indexOf(nodeId);
    return index2 >= 0 ? index2 + 1 : null;
  }
  const index = doc3.roots.indexOf(nodeId);
  return index >= 0 ? index + 1 : null;
}
function resolveSequenceNumberForMeasureKey(doc3, node) {
  const nodes = doc3.nodes;
  if (!nodes) return null;
  if (node.parentId) {
    const parent = nodes[node.parentId];
    if (!parent) return null;
    const index2 = parent.children.indexOf(node.id);
    return index2 >= 0 ? index2 + 1 : null;
  }
  if (node.parentSummaryId) {
    const summary = doc3.summaries?.find((item) => item.id === node.parentSummaryId);
    if (!summary) return null;
    const index2 = summary.children.indexOf(node.id);
    return index2 >= 0 ? index2 + 1 : null;
  }
  const index = doc3.roots?.indexOf(node.id) ?? -1;
  return index >= 0 ? index + 1 : null;
}
function buildLinksMeasureSignature(links) {
  return JSON.stringify(
    links.map((link) => link.kind === "internal" ? {
      id: link.id ?? "",
      kind: link.kind,
      nodeId: link.nodeId,
      docId: link.docId ?? "",
      label: link.label ?? ""
    } : {
      id: link.id ?? "",
      kind: link.kind,
      url: link.url,
      label: link.label ?? "",
      iconId: link.iconId ?? ""
    })
  );
}
function buildSummaryContentMeasureSignature(summary) {
  const content = summary.content;
  if (!content || content.schemaVersion !== 1) return `t:${summary.text}`;
  if (content.kind === "plain-text") return `pt:${content.text}`;
  if (content.kind === "richtext") return `rt:${content.html ?? buildProseMirrorMeasureSignature(content.doc)}`;
  try {
    return `blocks:${JSON.stringify(content.blocks)}`;
  } catch {
    return `blocks:unserializable:${summary.text}`;
  }
}
function buildSummaryMeasureKey(summary) {
  return buildSummaryContentMeasureSignature(summary);
}
function buildNodeMeasureKey(node, doc3) {
  const parts = [];
  const content = node.content;
  const contentWidthState = resolveNodeContentWidth(node);
  parts.push(`cw:${contentWidthState.mode}:${clampNodeMainWidth(contentWidthState.width)}`);
  if (!content || content.schemaVersion !== 1) {
    parts.push("t:" + node.text);
    return parts.join("|");
  }
  if (content.kind === "plain-text") {
    parts.push("pt:" + content.text);
    return parts.join("|");
  }
  if (content.kind === "richtext") {
    parts.push("rt:" + (content.html ?? buildProseMirrorMeasureSignature(content.doc)));
    return parts.join("|");
  }
  parts.push("t:" + node.text);
  for (const block of content.blocks) {
    if (block.type === "image") {
      const asset = doc3.assets?.[block.assetId];
      const assetWidth = asset && asset.kind === "image" ? asset.width ?? 0 : 0;
      const assetHeight = asset && asset.kind === "image" ? asset.height ?? 0 : 0;
      const fit = block.fit ?? "contain";
      parts.push(
        `img:${block.region}:${block.order}:${block.assetId}:${block.width ?? assetWidth}x${block.height ?? assetHeight}:${fit}`
      );
      continue;
    }
    if (block.type === "embed") {
      const width = Math.max(40, block.width ?? 180);
      const height = Math.max(40, block.height ?? 120);
      const props = block.embed.props && typeof block.embed.props === "object" && !Array.isArray(block.embed.props) ? JSON.stringify(block.embed.props) : "";
      parts.push(`emb:${block.region}:${block.order}:${block.embed.type}:${block.embed.assetId ?? ""}:${width}x${height}:${props}`);
      continue;
    }
    if (block.type === "richtext") {
      parts.push(`rtb:${block.region}:${block.order}:${block.html ?? buildProseMirrorMeasureSignature(block.doc)}`);
      continue;
    }
    if (block.type === "sequence") {
      parts.push(`seq:${block.region}:${block.order}:${block.mode ?? "siblings"}:${block.prefix ?? ""}:${block.suffix ?? ""}:${resolveSequenceNumberForMeasureKey(doc3, node) ?? ""}`);
      continue;
    }
    if (block.type === "tags") {
      parts.push(`tags:${block.region}:${block.order}:${block.tags.map((tag) => tag.text).join(",")}`);
      continue;
    }
    if (block.type === "icons") {
      parts.push(`icons:${block.region}:${block.order}:${block.icons.map((icon) => icon.value).join(",")}`);
      continue;
    }
    if (block.type === "tasks") {
      parts.push(
        `tasks:${block.region}:${block.order}:${block.items.map((item) => `${item.checked ? "1" : "0"}:${item.text}`).join(",")}`
      );
      continue;
    }
    if (block.type === "links") {
      parts.push(
        `links:${block.region}:${block.order}:${buildLinksMeasureSignature(block.links)}`
      );
      continue;
    }
    if (block.type === "notes") {
      const signature = (() => {
        const candidate = block;
        if (typeof candidate.html === "string") return `html:${candidate.html}`;
        if (typeof candidate.text === "string") return `text:${candidate.text}`;
        if (candidate.engine === "prosemirror" && candidate.doc && typeof candidate.doc === "object" && !Array.isArray(candidate.doc)) {
          try {
            return `doc:${JSON.stringify(candidate.doc)}`;
          } catch {
            return "doc:unserializable";
          }
        }
        return "";
      })();
      parts.push(`notes:${block.region}:${block.order}:${signature}`);
      continue;
    }
    if (block.type === "comments") {
      parts.push(`comments:${block.region}:${block.order}:${block.items.length}`);
      continue;
    }
    if (block.type === "progress") {
      parts.push(`progress:${block.region}:${block.order}:${block.variant ?? ""}`);
      continue;
    }
    const unknownBlock = block;
    parts.push(
      `${String(unknownBlock.type ?? "unknown")}:${String(unknownBlock.region ?? "")}:${String(unknownBlock.order ?? "")}`
    );
  }
  return parts.join("|");
}
function buildSummaryBodyHtml(doc3, summaryId, blurViewState, override) {
  const summary = doc3.summaries.find((item) => item.id === summaryId);
  if (!summary) return "";
  const text5 = override?.text ?? summary.text;
  const content = override?.content ?? summary.content;
  const renderRichtextHtml = (html) => {
    const withAssets = resolveAssetBackedHtml({ html, doc: doc3, assetObjectUrlById: null });
    const withCloze = blurViewState ? applyClozeViewState(withAssets, blurViewState) : withAssets;
    const withCode = applyCodeHighlightingToHtml(withCloze);
    const withFormula = applyFormulaRenderingToHtml(withCode);
    return `<div class="km-node-richtext">${withFormula}</div>`;
  };
  const renderPlainText = (plain) => {
    if (plain.length === 0) {
      return `<div class="km-node-richtext"><p></p></div>`;
    }
    return `<div class="km-node-richtext" style="white-space:pre-wrap;word-break:break-word;">${escapeHtml3(plain)}</div>`;
  };
  if (!content || content.schemaVersion !== 1) return renderPlainText(text5);
  if (content.kind === "plain-text") return renderPlainText(content.text);
  if (content.kind === "richtext") {
    const html = content.html ?? renderProseMirrorDocHtml(content.doc);
    return html ? renderRichtextHtml(html) : renderPlainText(text5);
  }
  if (content.kind === "blocks") {
    const richtext = content.blocks.find((block) => block.type === "richtext");
    const html = richtext?.html ?? (richtext && richtext.engine === "prosemirror" ? renderProseMirrorDocHtml(richtext.doc) : null);
    if (html) return renderRichtextHtml(html);
    return renderPlainText(text5);
  }
  return renderPlainText(text5);
}
function buildSummaryMeasureHtmlFromContent(doc3, summaryId, override) {
  return `<style>${nodeRichTextCssText}</style>${buildSummaryBodyHtml(doc3, summaryId, null, override)}`;
}
var KMIND_ICON_ASSET_PREFIX = "kmind-icon://asset/";
function renderNodeIconValue(value, args) {
  const trimmed = value.trim();
  if (trimmed.startsWith(KMIND_ICON_ASSET_PREFIX)) {
    const assetId = trimmed.slice(KMIND_ICON_ASSET_PREFIX.length).trim() || "";
    const asset = assetId ? args.doc.assets?.[assetId] : null;
    const resolved = (() => {
      if (!asset || asset.kind !== "image" && asset.kind !== "blob") return { src: TRANSPARENT_PIXEL_DATA_URL, placeholder: true };
      const url = asset.dataUrl;
      if (url.startsWith(KMIND_ASSET_URL_PREFIX2)) {
        const storedId = url.slice(KMIND_ASSET_URL_PREFIX2.length).trim() || assetId;
        const objectUrl = args.assetObjectUrlById?.get(storedId) ?? null;
        return objectUrl ? { src: objectUrl, placeholder: false } : { src: TRANSPARENT_PIXEL_DATA_URL, placeholder: true };
      }
      return url.length > 0 ? { src: url, placeholder: false } : { src: TRANSPARENT_PIXEL_DATA_URL, placeholder: true };
    })();
    const placeholderStyle = resolved.placeholder ? "background:rgba(226,232,240,0.55);border:1px dashed rgba(148,163,184,0.5);" : "";
    return `<span class="km-node-icon km-node-icon--asset" data-km-action="icons.open"><img alt="" src="${escapeHtml3(resolved.src)}" style="object-fit:contain;${placeholderStyle}" /></span>`;
  }
  if (trimmed.startsWith("kmind-icon://")) {
    const svg = getBuiltinIconSvg(trimmed);
    if (svg) {
      const normalized = normalizeBuiltinIconId(trimmed);
      return `<span class="km-node-icon km-node-icon--builtin" data-km-action="icons.open" data-km-icon-id="${escapeHtml3(normalized)}">${svg}</span>`;
    }
  }
  return `<span class="km-node-icon km-node-icon--text" data-km-action="icons.open">${escapeHtml3(value)}</span>`;
}
function buildNodeMeasureHtml(doc3, nodeId, override, options) {
  return `<style>${nodeRichTextCssText}</style>${buildNodeBodyHtml(doc3, nodeId, null, null, override, options)}`;
}
function buildNodeBodyHtml(doc3, nodeId, blurViewState, assetObjectUrlById, override, options) {
  const baseNode = doc3.nodes[nodeId];
  if (!baseNode) return "";
  const text5 = override?.text ?? baseNode.text;
  const content = override?.content ?? baseNode.content;
  const nodeBodyLayout = options?.nodeBodyLayout ?? "classic";
  const contentWidthState = override && "contentWidth" in override ? resolveNodeContentWidth(
    {
      contentWidth: override.contentWidth ?? void 0,
      maxWidth: void 0,
      contentWidthMode: void 0
    }
  ) : resolveNodeContentWidth(baseNode);
  const contentWidthMode = contentWidthState.mode;
  const isCardV1 = nodeBodyLayout === "card-v1";
  const resolveEmbedAsset = (block) => {
    const assetId = (block.embed.assetId ?? "").trim();
    return assetId ? doc3.assets?.[assetId] : void 0;
  };
  const renderEmbedFallbackHtml = (block) => {
    const embedProps = block.embed.props;
    const definition = options?.embedRegistry?.[block.embed.type];
    const customHtml = definition?.renderFallbackHtml?.({
      asset: resolveEmbedAsset(block),
      props: embedProps && typeof embedProps === "object" && !Array.isArray(embedProps) ? embedProps : void 0
    });
    if (typeof customHtml === "string" && customHtml.length > 0) return customHtml;
    if (block.embed.type === "kmind:siyuan-doc") {
      return renderSiyuanDocGhost(embedProps);
    }
    return escapeHtml3(`Embed: ${block.embed.type}`);
  };
  const blocks = content?.schemaVersion === 1 && content.kind === "blocks" ? content.blocks : [];
  const byRegion = {
    top: [],
    left: [],
    main: [],
    right: [],
    bottom: []
  };
  for (const block of blocks) {
    byRegion[block.region].push(block);
  }
  for (const list of Object.values(byRegion)) {
    list.sort((a2, b2) => a2.order - b2.order);
  }
  const renderRichtextHtml = (html) => {
    const withAssets = resolveAssetBackedHtml({ html, doc: doc3, assetObjectUrlById });
    const withCloze = blurViewState ? applyClozeViewState(withAssets, blurViewState) : withAssets;
    const withCode = applyCodeHighlightingToHtml(withCloze);
    const withFormula = applyFormulaRenderingToHtml(withCode);
    return `<div class="km-node-richtext">${withFormula}</div>`;
  };
  const renderPlainText = (text6) => {
    if (text6.length === 0) {
      return `<div class="km-node-richtext"><p></p></div>`;
    }
    return `<div class="km-node-richtext" style="white-space:pre-wrap;word-break:break-word;">${escapeHtml3(text6)}</div>`;
  };
  const noteIconSvg = getBuiltinIconSvg("kmind-icon://builtin/ui/notes") ?? `
      <svg viewBox="0 0 24 24" fill="none" aria-hidden="true">
        <path d="M7 3h10a2 2 0 0 1 2 2v10l-6 6H7a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z" stroke="currentColor" stroke-width="2" stroke-linejoin="round"/>
        <path d="M13 21v-4a2 2 0 0 1 2-2h4" stroke="currentColor" stroke-width="2" stroke-linejoin="round"/>
      </svg>
    `.trim();
  const commentIconSvg = getBuiltinIconSvg("kmind-icon://builtin/ui/comments") ?? `
      <svg viewBox="0 0 24 24" fill="none" aria-hidden="true">
        <path d="M4 5h16a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2H9l-5 4v-4H4a2 2 0 0 1-2-2V7a2 2 0 0 1 2-2z" stroke="currentColor" stroke-width="2" stroke-linejoin="round"/>
        <path d="M7.5 10h9" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
        <path d="M7.5 13.5h6" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
      </svg>
    `.trim();
  const renderMetaButton = (args) => {
    return `<button class="km-node-meta-btn" data-km-action="${escapeHtml3(args.action)}" type="button" tabindex="-1" aria-label="${escapeHtml3(args.title)}">${args.icon}</button>`;
  };
  const renderLeadingExternalLink = (mainHtml) => {
    const link = isCardV1 ? options?.leadingExternalLink : null;
    if (!link?.url) return mainHtml;
    const icon = link.iconHtml && link.iconHtml.trim() ? link.iconHtml : '<svg viewBox="0 0 24 24" fill="none" aria-hidden="true"><path d="M6 12h12" stroke="currentColor" stroke-linecap="round" stroke-width="2"/></svg>';
    return [
      `<div class="km-node-leading-link">`,
      `<button class="km-node-leading-link__icon" data-km-action="external.open" data-km-external-url="${escapeHtml3(link.url)}" type="button" tabindex="-1" aria-label="${escapeHtml3(link.label)}">${icon}</button>`,
      `<div class="km-node-leading-link__title">${mainHtml}</div>`,
      `</div>`
    ].join("");
  };
  const isCardMainMediaBlock = (block) => {
    if (!isCardV1) return false;
    if (block.type !== "image" && block.type !== "embed") return false;
    return block.region === "top" || block.region === "bottom";
  };
  const hasRichtextBlock = blocks.some((block) => block.type === "richtext");
  const isExclusiveEmbedNode = !hasRichtextBlock && byRegion.main.some((block) => {
    if (block.type !== "embed") return false;
    const props = block.embed.props;
    if (!props || typeof props !== "object" || Array.isArray(props)) return false;
    return props.exclusive === true;
  });
  const isBlocks = content?.schemaVersion === 1 && content.kind === "blocks";
  const implicitMain = (() => {
    if (content?.schemaVersion !== 1) return renderPlainText(text5);
    if (content.kind === "plain-text") return renderPlainText(content.text);
    if (content.kind === "richtext") {
      const html = content.html ?? renderProseMirrorDocHtml(content.doc);
      return html ? renderRichtextHtml(html) : renderPlainText(text5);
    }
    if (content.kind === "blocks") {
      const richtext = content.blocks.find((block) => block.type === "richtext");
      const html = richtext?.html ?? (richtext && richtext.engine === "prosemirror" ? renderProseMirrorDocHtml(richtext.doc) : null);
      if (html) return renderRichtextHtml(html);
      return renderPlainText(text5);
    }
    return renderPlainText(text5);
  })();
  const renderBlock = (block) => {
    if (block.type === "richtext") {
      const html = block.html ?? (block.engine === "prosemirror" ? renderProseMirrorDocHtml(block.doc) : null);
      return html ? renderRichtextHtml(html) : renderPlainText(text5);
    }
    if (block.type === "sequence") {
      const number2 = resolveSequenceNumber(doc3, nodeId);
      if (number2 === null) return "";
      return `<div class="km-node-seq">${escapeHtml3(`${block.prefix ?? ""}${number2}${block.suffix ?? ""}`)}</div>`;
    }
    if (block.type === "icons") {
      return `<div class="km-node-icons">${block.icons.map((icon) => renderNodeIconValue(icon.value, { doc: doc3, assetObjectUrlById })).join("")}</div>`;
    }
    if (block.type === "tags") {
      return `<div class="km-node-tags">${block.tags.map((tag) => `<span class="km-node-tag"${tag.color ? ` style="background:${escapeHtml3(tag.color)}"` : ""}>${escapeHtml3(tag.text)}</span>`).join("")}</div>`;
    }
    if (block.type === "image") {
      const asset = doc3.assets?.[block.assetId];
      const assetWidth = asset && asset.kind === "image" ? asset.width : void 0;
      const assetHeight = asset && asset.kind === "image" ? asset.height : void 0;
      const width = Math.max(20, block.width ?? assetWidth ?? 160);
      const height = Math.max(20, block.height ?? assetHeight ?? 120);
      const resolved = (() => {
        if (!asset || asset.kind !== "image" && asset.kind !== "blob") return { src: TRANSPARENT_PIXEL_DATA_URL, placeholder: true };
        const url = asset.dataUrl;
        if (url.startsWith(KMIND_ASSET_URL_PREFIX2)) {
          const id = url.slice(KMIND_ASSET_URL_PREFIX2.length) || block.assetId;
          const objectUrl = assetObjectUrlById?.get(id) ?? null;
          return objectUrl ? { src: objectUrl, placeholder: false } : { src: TRANSPARENT_PIXEL_DATA_URL, placeholder: true };
        }
        return { src: url, placeholder: false };
      })();
      const fit = block.fit ?? "contain";
      const placeholderStyle = resolved.placeholder ? "background:rgba(226,232,240,0.55);border:1px dashed rgba(148,163,184,0.5);" : "";
      return `<img class="km-node-image" alt="${escapeHtml3(block.alt ?? "")}" src="${escapeHtml3(resolved.src)}" style="width:${width}px;height:${height}px;object-fit:${fit};${placeholderStyle}" />`;
    }
    if (block.type === "tasks") {
      const first2 = block.items[0];
      const isNodeTask = block.items.length === 1 && Boolean(first2) && String(first2?.text ?? "").trim().length === 0;
      if (isNodeTask) {
        const checked = Boolean(first2?.checked);
        const mark = checked ? "\u2713" : "";
        return `<button class="km-node-task-toggle" data-km-action="task.toggle" type="button" tabindex="-1" role="checkbox" aria-checked="${checked ? "true" : "false"}">${mark}</button>`;
      }
      return `<div class="km-node-tasks">${block.items.map((item) => {
        const mark = item.checked ? "\u2713" : "";
        return `<div class="km-node-task"><span class="km-node-task-box">${mark}</span><span>${escapeHtml3(item.text)}</span></div>`;
      }).join("")}</div>`;
    }
    if (block.type === "links") {
      if (nodeBodyLayout === "card-v1") return "";
      return `<div class="km-node-links">${block.links.map((link) => {
        if (link.kind === "internal") {
          const docId = typeof link.docId === "string" ? link.docId.trim() : "";
          const code = docId ? `${docId}#${link.nodeId}` : `#${link.nodeId}`;
          const label2 = link.label ?? (docId ? link.nodeId : doc3.nodes[link.nodeId]?.text ?? link.nodeId);
          return `<div class="km-node-link"><span class="km-node-link-code">${escapeHtml3(code)}</span><span>${escapeHtml3(label2)}</span></div>`;
        }
        const label = link.label ?? link.url;
        return `<div class="km-node-link"><span class="km-node-link-code">${escapeHtml3(link.url)}</span><span>${escapeHtml3(label)}</span></div>`;
      }).join("")}</div>`;
    }
    if (block.type === "notes") {
      if (nodeBodyLayout === "card-v1") {
        return renderMetaButton({ action: "notes.open", title: "Notes", icon: noteIconSvg });
      }
      const candidate = block;
      const html = typeof candidate.html === "string" ? candidate.html : candidate.engine === "prosemirror" && candidate.doc && typeof candidate.doc === "object" && !Array.isArray(candidate.doc) ? renderProseMirrorDocHtml(candidate.doc) : null;
      if (html) return renderRichtextHtml(html);
      const text6 = typeof candidate.text === "string" ? candidate.text : "";
      return `<div class="km-node-notes">${escapeHtml3(text6)}</div>`;
    }
    if (block.type === "comments") {
      if (nodeBodyLayout === "card-v1") {
        return renderMetaButton({ action: "comments.open", title: "Comments", icon: commentIconSvg });
      }
      const count = block.items.length;
      return count > 0 ? `<div class="km-node-notes">${escapeHtml3(`Comments: ${count}`)}</div>` : "";
    }
    if (block.type === "embed") {
      const width = Math.max(40, block.width ?? 180);
      const height = Math.max(40, block.height ?? 120);
      const embedProps = block.embed.props;
      const props = embedProps && typeof embedProps === "object" && !Array.isArray(embedProps) ? JSON.stringify(block.embed.props) : "";
      const propsAttr = props ? ` data-km-embed-props="${escapeHtml3(props)}"` : "";
      const isResizable = Boolean(
        embedProps && typeof embedProps === "object" && !Array.isArray(embedProps) && embedProps.resizable === true
      );
      const isExclusive = Boolean(
        embedProps && typeof embedProps === "object" && !Array.isArray(embedProps) && embedProps.exclusive === true
      );
      const resizeHandle = isResizable && !isExclusive ? `<div class="km-node-embed__resize-handle" data-km-action="embed.resize" data-km-embed-block-id="${escapeHtml3(block.id)}"></div>` : "";
      const fallbackHtml = renderEmbedFallbackHtml(block);
      return [
        `<div class="km-node-embed-wrap" data-km-embed-block-id="${escapeHtml3(block.id)}" style="width:${width}px;height:${height}px;">`,
        `<div class="km-node-embed" data-km-embed-host="true" data-km-embed-type="${escapeHtml3(block.embed.type)}" data-km-embed-asset-id="${escapeHtml3(block.embed.assetId ?? "")}"${propsAttr} style="width:100%;height:100%;">${fallbackHtml}</div>`,
        resizeHandle,
        `</div>`
      ].join("");
    }
    return "";
  };
  const cardMainMedia = isCardV1 ? {
    top: byRegion.top.filter(isCardMainMediaBlock),
    left: byRegion.left.filter(isCardMainMediaBlock),
    right: byRegion.right.filter(isCardMainMediaBlock),
    bottom: byRegion.bottom.filter(isCardMainMediaBlock)
  } : null;
  const hasCardMainMedia = Boolean(
    isCardV1 && cardMainMedia && (cardMainMedia.top.length > 0 || cardMainMedia.left.length > 0 || cardMainMedia.right.length > 0 || cardMainMedia.bottom.length > 0)
  );
  const renderMainContent = () => {
    if (!isBlocks) return implicitMain;
    const renderedBlocks = byRegion.main.filter((block) => {
      if (block.type === "progress") return false;
      if (!isExclusiveEmbedNode) return true;
      return block.type === "embed";
    }).map(renderBlock);
    if (hasRichtextBlock || isExclusiveEmbedNode) return renderedBlocks.join("");
    return `${implicitMain}${renderedBlocks.join("")}`;
  };
  const renderCardMainLayout = () => {
    const topHtml = (cardMainMedia?.top ?? []).map(renderBlock).join("");
    const leftHtml = (cardMainMedia?.left ?? []).map(renderBlock).join("");
    const rightHtml = (cardMainMedia?.right ?? []).map(renderBlock).join("");
    const bottomHtml = (cardMainMedia?.bottom ?? []).map(renderBlock).join("");
    const mainHtml = renderLeadingExternalLink(renderMainContent());
    return [
      `<div class="km-node-main-layout">`,
      topHtml ? `<div class="km-node-main-layout__top">${topHtml}</div>` : "",
      leftHtml ? `<div class="km-node-main-layout__left">${leftHtml}</div>` : "",
      `<div class="km-node-main-layout__main">${mainHtml}</div>`,
      rightHtml ? `<div class="km-node-main-layout__right">${rightHtml}</div>` : "",
      bottomHtml ? `<div class="km-node-main-layout__bottom">${bottomHtml}</div>` : "",
      `</div>`
    ].join("");
  };
  const renderRegion = (region) => {
    const isMetaBlock = (block) => block.type === "notes" || block.type === "comments";
    const regionBlocks = (() => {
      if (!isCardV1) return byRegion[region];
      if (region === "right") {
        const seen = /* @__PURE__ */ new Set();
        const rightBlocks = [];
        for (const candidate of [...byRegion.right, ...byRegion.top, ...byRegion.left, ...byRegion.main, ...byRegion.bottom]) {
          if (!candidate) continue;
          if (seen.has(candidate.id)) continue;
          if (candidate.region === "right" || isMetaBlock(candidate)) {
            seen.add(candidate.id);
            rightBlocks.push(candidate);
          }
        }
        return rightBlocks;
      }
      return byRegion[region].filter((block) => !isMetaBlock(block));
    })();
    if (isExclusiveEmbedNode) {
      return regionBlocks.filter((block) => block.type === "embed").map(renderBlock).join("");
    }
    if (region === "main") {
      if (isCardV1) return hasCardMainMedia ? renderCardMainLayout() : renderLeadingExternalLink(renderMainContent());
      return renderMainContent();
    }
    const filtered = regionBlocks.filter((block) => block.type !== "progress" && !isCardMainMediaBlock(block));
    if (filtered.length === 0) return "";
    if (isCardV1) {
      const isMediaBlock = (block) => block.type === "image" || block.type === "embed";
      if (region === "left") {
        const tasks = filtered.filter((block) => block.type === "tasks");
        const media = filtered.filter(isMediaBlock);
        const rest = filtered.filter((block) => block.type !== "tasks" && !isMediaBlock(block));
        if (tasks.length > 0 || media.length > 0) {
          return [...tasks, ...rest, ...media].map(renderBlock).join("");
        }
      }
      if (region === "right") {
        const meta = filtered.filter(isMetaBlock);
        const nonMeta = filtered.filter((block) => !isMetaBlock(block));
        const media = nonMeta.filter(isMediaBlock);
        const rest = nonMeta.filter((block) => !isMediaBlock(block));
        if (meta.length > 0 || media.length > 0) {
          return [...media, ...rest, ...meta].map(renderBlock).join("");
        }
      }
    }
    return filtered.map(renderBlock).join("");
  };
  const layoutClass = nodeBodyLayout === "card-v1" ? `km-node-body km-node-body--card-v1${contentWidthMode === "fixed" ? " km-node-body--card-v1-fixed" : ""}${options?.hasChromeTop ? " km-node-body--card-v1-has-chrome-top" : ""}${isExclusiveEmbedNode ? " km-node-body--exclusive-embed" : ""}` : nodeBodyLayout === "baseline-v1" ? `km-node-body km-node-body--baseline-v1${isExclusiveEmbedNode ? " km-node-body--exclusive-embed" : ""}` : "km-node-body";
  let mainMaxWidth = clampNodeMainWidth(contentWidthState.width);
  if (isExclusiveEmbedNode) {
    const embedMaxWidth = byRegion.main.reduce((acc, block) => {
      if (block.type !== "embed") return acc;
      const width = Math.max(40, block.width ?? 180);
      return Math.max(acc, width);
    }, 0);
    if (embedMaxWidth > 0) {
      mainMaxWidth = clampNodeMainWidth(Math.max(mainMaxWidth, embedMaxWidth));
    }
  }
  return [
    `<div class="${layoutClass}" style="--km-node-main-max-width:${mainMaxWidth}px;">`,
    `<div class="km-node-region-top">${renderRegion("top")}</div>`,
    `<div class="km-node-region-left">${renderRegion("left")}</div>`,
    `<div class="km-node-region-main">${renderRegion("main")}</div>`,
    `<div class="km-node-region-right">${renderRegion("right")}</div>`,
    `<div class="km-node-region-bottom">${renderRegion("bottom")}</div>`,
    `</div>`
  ].join("");
}
function applyClozeViewState(html, blurViewState) {
  if (typeof DOMParser === "undefined") return html;
  try {
    const parser = new DOMParser();
    const doc3 = parser.parseFromString(`<div>${html}</div>`, "text/html");
    const container = doc3.body.firstElementChild;
    if (!container) return html;
    const nodes = container.querySelectorAll("[data-km-cloze][data-km-cloze-id]");
    for (const el of Array.from(nodes)) {
      const id = el.getAttribute("data-km-cloze-id") ?? "";
      const override = blurViewState.segmentOverrides?.[id];
      const visibility = override ?? blurViewState.defaultVisibility;
      if (visibility === "revealed") {
        el.setAttribute("data-km-revealed", "true");
      } else {
        el.removeAttribute("data-km-revealed");
      }
    }
    return container.innerHTML;
  } catch {
    return html;
  }
}
function collectReferencedAssetIdsFromContent2(content) {
  return collectReferencedAssetIdsFromContent(content);
}
function collectReferencedAssets(doc3, nodeIds) {
  const assets = {};
  for (const nodeId of nodeIds) {
    const node = doc3.nodes[nodeId];
    if (!node) continue;
    for (const assetId of collectReferencedAssetIdsFromContent2(node.content)) {
      const asset = doc3.assets?.[assetId];
      if (!asset) continue;
      assets[assetId] = asset;
    }
  }
  return assets;
}
function mountEmbeds(root, args) {
  const cleanups = [];
  const embeds = Array.from(root.querySelectorAll("[data-km-embed-host][data-km-embed-type]"));
  for (const host of embeds) {
    const type = (host.getAttribute("data-km-embed-type") ?? "").trim();
    if (!type) continue;
    const definition = args.embedRegistry[type];
    if (!definition) {
      if (type.startsWith("kmind:")) {
        console.warn(`[kmind] Missing embed definition for "${type}".`);
      }
      continue;
    }
    if (definition.trust === "untrusted") {
      host.textContent = "Untrusted embed";
      continue;
    }
    const assetId = (host.getAttribute("data-km-embed-asset-id") ?? "").trim();
    const asset = assetId ? args.doc.assets?.[assetId] : void 0;
    const rawProps = host.getAttribute("data-km-embed-props") ?? "";
    const props = (() => {
      if (!rawProps) return void 0;
      try {
        const parsed = JSON.parse(rawProps);
        if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return void 0;
        return parsed;
      } catch {
        return void 0;
      }
    })();
    const result = definition.mount?.(host, { asset, props });
    if (typeof result === "function") cleanups.push(result);
  }
  return () => {
    for (const cleanup of cleanups) cleanup();
  };
}
function remapIncomingAssets(args) {
  const referenced = collectReferencedAssetIdsFromContent2(args.content);
  if (referenced.size === 0) return { content: args.content, assets: {} };
  const existing = args.doc.assets ?? {};
  const nextAssets = {};
  for (const assetId of referenced) {
    if (existing[assetId]) continue;
    const asset = args.assets[assetId];
    if (!asset) continue;
    nextAssets[assetId] = { ...asset, id: assetId };
  }
  return { content: args.content, assets: nextAssets };
}
async function blobToDataUrl(blob) {
  return await new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = () => resolve(String(reader.result));
    reader.onerror = () => reject(new Error("Failed to read file"));
    reader.readAsDataURL(blob);
  });
}
async function getImageDimensions(dataUrl) {
  return await new Promise((resolve, reject) => {
    const img = new Image();
    img.onload = () => resolve({ width: img.naturalWidth || img.width, height: img.naturalHeight || img.height });
    img.onerror = () => reject(new Error("Failed to load image"));
    img.src = dataUrl;
  });
}

// ../react/src/mindmap-editor/styles.ts
var buttonStyle = {
  borderRadius: 8,
  border: "1px solid var(--km-border)",
  background: "var(--km-panel)",
  padding: "6px 10px",
  fontSize: 13,
  lineHeight: "18px",
  cursor: "pointer"
};

// ../react/src/i18n.tsx
var React = __toESM(require_react(), 1);

// ../i18n/src/utils.ts
function toTitleCase(value) {
  if (value.length === 0) return value;
  return value.slice(0, 1).toUpperCase() + value.slice(1).toLowerCase();
}
function normalizeLocale(locale) {
  const raw = String(locale ?? "").trim();
  if (!raw) return "";
  const parts = raw.replaceAll("_", "-").split("-").filter(Boolean);
  if (parts.length === 0) return "";
  const language = parts[0].toLowerCase();
  const rest = parts.slice(1);
  const normalized = [language];
  for (const part of rest) {
    if (/^[A-Za-z]{4}$/.test(part)) {
      normalized.push(toTitleCase(part));
      continue;
    }
    if (/^[A-Za-z]{2}$/.test(part) || /^\d{3}$/.test(part)) {
      normalized.push(part.toUpperCase());
      continue;
    }
    normalized.push(part.toLowerCase());
  }
  return normalized.filter(Boolean).join("-");
}
function resolveBestLocale(args) {
  const desired = normalizeLocale(args.desired);
  const fallback = normalizeLocale(args.fallbackLocale);
  const available = args.availableLocales.map(normalizeLocale).filter(Boolean);
  if (desired && available.includes(desired)) return desired;
  const desiredLang = desired.split("-")[0] ?? "";
  if (desiredLang) {
    const exactLang = available.find((item) => item === desiredLang);
    if (exactLang) return exactLang;
    const byPrefix = available.find((item) => item.startsWith(`${desiredLang}-`));
    if (byPrefix) return byPrefix;
  }
  if (fallback && available.includes(fallback)) return fallback;
  return fallback || available[0] || "en-US";
}
function mergeMessagesByLocale(...sources) {
  const merged = {};
  for (const source of sources) {
    if (!source) continue;
    for (const [locale, messages] of Object.entries(source)) {
      const normalizedLocale = normalizeLocale(locale);
      if (!normalizedLocale) continue;
      const existing = merged[normalizedLocale];
      merged[normalizedLocale] = existing ? { ...existing, ...messages } : { ...messages };
    }
  }
  return merged;
}

// ../i18n/src/runtime.ts
function formatMessage(template, params) {
  if (!params) return template;
  return template.replace(/\{(\w+)\}/g, (_match, key) => {
    const value = params[key];
    if (value === null || typeof value === "undefined") return "";
    return String(value);
  });
}
function resolveTemplate(args) {
  const messages = args.messagesByLocale[args.locale] ?? null;
  if (messages && typeof messages[args.key] === "string") return messages[args.key];
  const fallback = args.messagesByLocale[args.fallbackLocale] ?? null;
  if (fallback && typeof fallback[args.key] === "string") return fallback[args.key];
  return null;
}
function resolveMissing(key, strategy) {
  if (strategy === "bracket") return `[${key}]`;
  if (strategy === "debug") return `__MISSING__:${key}`;
  return key;
}
function createI18n(init2) {
  const messagesByLocale = mergeMessagesByLocale(init2.messagesByLocale);
  const availableLocales = Object.keys(messagesByLocale).map(normalizeLocale);
  const fallbackLocale = normalizeLocale(init2.fallbackLocale);
  const isProd = typeof process !== "undefined" && false;
  const missingKeyStrategy = init2.missingKeyStrategy ?? (isProd ? "key" : "debug");
  let locale = resolveBestLocale({ desired: init2.locale, availableLocales, fallbackLocale });
  let version2 = 0;
  const listeners2 = /* @__PURE__ */ new Set();
  const emit = () => {
    version2 += 1;
    for (const listener of listeners2) listener();
  };
  const i18n = {
    getLocale() {
      return locale;
    },
    setLocale(next) {
      const resolved = resolveBestLocale({ desired: next, availableLocales, fallbackLocale });
      if (resolved === locale) return;
      locale = resolved;
      emit();
    },
    has(key) {
      const template = resolveTemplate({ locale, fallbackLocale, messagesByLocale, key });
      return typeof template === "string";
    },
    t(key, params) {
      const template = resolveTemplate({ locale, fallbackLocale, messagesByLocale, key });
      if (!template) return resolveMissing(key, missingKeyStrategy);
      return formatMessage(template, params);
    },
    subscribe(listener) {
      listeners2.add(listener);
      return () => listeners2.delete(listener);
    },
    getVersion() {
      return version2;
    }
  };
  return i18n;
}

// ../app/src/i18n/messages.ts
var KMIND_APP_MESSAGES = {
  "en-US": {
    "kmind.common.untitled": "Untitled",
    "app.command.document.exportSvg": "Export SVG",
    "app.command.document.exportPng": "Export PNG",
    "app.command.document.exportSvgPackage": "Export KMindz SVG package",
    "app.command.document.exportKmindzPackage": "Export KMindz package",
    "app.command.document.exportPngPackage": "Export KMindz PNG package",
    "app.command.document.exportZip": "Export KMindz zip",
    "app.command.document.import": "Import",
    "app.command.document.importZip": "Import zip",
    "app.toolbar.document.import": "Import",
    "app.toolbar.document.export": "Export",
    "app.command.document.new": "New document",
    "app.command.document.switch": "Switch document",
    "app.command.document.rename": "Rename document",
    "app.command.document.renameTo": "Rename document (inline)",
    "app.command.document.delete": "Delete document",
    "app.command.document.saveNow": "Save document",
    "app.command.document.refreshFromStore": "Reload from storage",
    "app.toolbar.document.new": "New",
    "app.toolbar.document.switcher": "Documents",
    "app.toolbar.document.rename": "Rename",
    "app.toolbar.document.delete": "Delete",
    "app.dialog.document.rename.title": "Rename",
    "app.dialog.document.rename.message": "Document title",
    "app.dialog.document.delete.confirm.moveToTrash": "Move current document to Trash?",
    "app.dialog.document.delete.confirm.cascadeToTrash": "This document has {count} sub map(s). Move them to Trash too?",
    "app.dialog.document.delete.confirm.delete": "Delete current document?",
    "app.selectionToolbar.changeTheme": "Change Theme",
    "app.selectionToolbar.nodeStyle": "Node Style",
    "editor.changeTheme.section.layout": "Layout",
    "editor.changeTheme.option.inherit": "Inherit",
    "app.command.view.zen.toggle": "Toggle zen mode",
    "app.command.view.readOnly.toggle": "Toggle read-only mode",
    "app.command.projectSearch.open": "Search in project",
    "app.command.projectSearch.close": "Close search",
    "app.command.projectSearch.toggle": "Toggle search",
    "app.toolbar.about": "About",
    "app.command.mindmap.summary.reveal": "Reveal summary",
    "appPage.popover.projectSearch.title": "Search",
    "appPage.popover.projectSearch.query.placeholder": "Search in nodes, notes, comments\u2026",
    "appPage.popover.projectSearch.section.mode": "Mode",
    "appPage.popover.projectSearch.mode.plain": "Plain",
    "appPage.popover.projectSearch.mode.regex": "Regex",
    "appPage.popover.projectSearch.mode.fuzzy": "Fuzzy",
    "appPage.popover.projectSearch.section.fields": "Fields",
    "appPage.popover.projectSearch.field.nodes": "Nodes",
    "appPage.popover.projectSearch.field.notes": "Notes",
    "appPage.popover.projectSearch.field.comments": "Comments",
    "appPage.popover.projectSearch.entity.summary": "Summary",
    "appPage.popover.projectSearch.option.caseSensitive": "Case sensitive",
    "appPage.popover.projectSearch.option.wholeWord": "Whole word",
    "appPage.popover.projectSearch.section.replace": "Replace",
    "appPage.popover.projectSearch.replace.placeholder": "Replacement\u2026",
    "appPage.popover.projectSearch.action.replaceSelected": "Replace selected",
    "appPage.popover.projectSearch.action.replaceAll": "Replace all",
    "appPage.popover.projectSearch.hint.fuzzyNoReplace": "Fuzzy mode does not support replace.",
    "appPage.popover.projectSearch.hint.readOnlyNoReplace": "Read-only mode: replace is disabled.",
    "appPage.popover.projectSearch.status.typeToSearch": "Type to search.",
    "appPage.popover.projectSearch.status.searching": "Searching\u2026",
    "appPage.popover.projectSearch.status.noResults": "No results",
    "appPage.popover.projectSearch.error.invalidRegex": "Invalid regex: {message}",
    "appPage.popover.projectSearch.confirm.replaceAll": "Replace {matches} matches across {maps} map(s)?",
    "appPage.popover.about.title": "About KMind Zen",
    "appPage.popover.about.appVersion": "App Version",
    "appPage.popover.about.coreVersion": "Core Version",
    "appPage.popover.about.website": "Website",
    "appPage.popover.about.action.openWebsite": "Open Website",
    "appPage.popover.import.subtitle": "Import a KMind Zen package, XMind file, legacy .kmind file, or paste Markdown headings.",
    "appPage.popover.import.file.label": "Import file",
    "appPage.popover.import.file.desc": "Auto-detects *.kmindz / *.svg / *.png / *.zip, *.xmind, and legacy *.kmind / *.json.",
    "appPage.popover.import.file.action": "Choose file\u2026",
    "appPage.popover.import.markdown.label": "Paste markdown headings",
    "appPage.popover.import.markdown.placeholder": "# Title\n## Section\n### Item",
    "appPage.popover.import.markdown.clear": "Clear",
    "appPage.popover.import.markdown.action": "Replace current map",
    "appPage.popover.import.status.noActiveEditor": "Import is unavailable: no active editor core.",
    "appPage.popover.import.status.filePickerUnavailable": "File picker is unavailable in this host.",
    "appPage.floatingToolbar.shortcuts.section.commands": "Map commands",
    "appPage.floatingToolbar.shortcuts.section.richText": "Rich text editing",
    "appPage.floatingToolbar.shortcuts.richText.bold": "Bold",
    "appPage.floatingToolbar.shortcuts.richText.italic": "Italic",
    "appPage.floatingToolbar.shortcuts.richText.strike": "Strikethrough",
    "appPage.floatingToolbar.shortcuts.richText.inlineCode": "Inline code",
    "appPage.floatingToolbar.shortcuts.richText.codeBlock": "Code block",
    "appPage.floatingToolbar.shortcuts.richText.formula": "Formula",
    "appPage.floatingToolbar.shortcuts.richText.slashMenu": "Slash menu",
    "appPage.floatingToolbar.shortcuts.richText.slashMenu.desc": "At line start or after whitespace",
    "appPage.floatingToolbar.shortcuts.richText.hardBreak": "Line break",
    "appPage.floatingToolbar.shortcuts.richText.paragraph": "New paragraph",
    "appPage.floatingToolbar.shortcuts.richText.commit": "Finish editing",
    "appPage.floatingToolbar.shortcuts.richText.commit.desc": "Enter may also create the next sibling depending on editing mode",
    "appPage.floatingToolbar.shortcuts.richText.cancel": "Cancel editing",
    "app.toolbar.node.icons": "Icons",
    "app.toolbar.node.panel": "Node",
    "app.command.node.width.set": "Set node content width",
    "app.command.node.width.setMode": "Set node content width mode",
    "app.command.node.width.reset": "Reset node content width",
    "app.command.node.task.toggleMode": "Toggle task mode",
    "app.command.node.task.toggleDone": "Toggle task done",
    "app.command.node.todo.add": "Add todo",
    "app.command.node.todo.remove": "Remove todo",
    "app.command.node.icon.add": "Add icon",
    "app.command.node.icon.remove": "Remove icon",
    "app.command.node.icon.move": "Move icon",
    "app.command.node.icon.set": "Set icons",
    "app.command.node.tag.add": "Add tag",
    "app.command.node.tag.remove": "Remove tag",
    "app.command.node.link.addExternal": "Add external link",
    "app.command.node.link.updateExternal": "Update external link",
    "app.command.node.link.moveExternal": "Move external link",
    "app.command.node.link.addInternal": "Add internal link",
    "app.command.node.link.connect": "Connect nodes (internal link)",
    "app.command.node.link.updateInternal": "Update internal link",
    "app.command.node.link.remove": "Remove link",
    "app.command.node.link.removeMany": "Remove links",
    "app.command.node.image.add": "Add image",
    "app.command.node.image.paste": "Paste image",
    "app.command.node.image.remove": "Remove image",
    "app.command.node.image.setRegion": "Set image region",
    "app.command.node.image.setSize": "Set image size",
    "app.command.node.image.setFit": "Set image fit",
    "app.command.node.notes.setText": "Set notes",
    "app.command.node.notes.open": "Edit notes",
    "app.command.node.notes.clear": "Clear notes",
    "app.command.node.comments.add": "Add comment",
    "app.command.node.comments.open": "Add comment",
    "app.command.node.comments.remove": "Remove comment",
    "app.command.node.comments.update": "Update comment",
    "app.command.node.comments.clear": "Clear comments",
    "app.command.clipboard.refresh": "Refresh clipboard hints",
    "app.command.node.clipboard.copyPlainText": "Copy plain text",
    "app.command.node.clipboard.copyNodeId": "Copy node id",
    "app.command.node.clipboard.copySubtree": "Copy node subtree",
    "app.command.node.clipboard.pasteSubtree": "Paste node subtree",
    "app.command.node.clipboard.copyMarkdown": "Copy subtree as markdown",
    "app.command.mindmap.clipboard.copyMarkdown": "Copy document as markdown",
    "app.command.node.clipboard.copyPng": "Copy node subtree as PNG",
    "app.command.mindmap.clipboard.copyPng": "Copy current view as PNG",
    "app.command.project.background.setColor": "Set project background color",
    "app.command.layout.project.clearThemeDefaults": "Clear theme defaults from project settings",
    "app.command.layout.project.setDefaultRootLayout": "Set project default root layout",
    "app.command.layout.project.setOptions": "Set project layout spacing",
    "app.command.layout.project.applyDensityPreset": "Apply project density preset",
    "app.command.layout.root.setOptions": "Set root layout spacing",
    "app.command.layout.node.setLayout": "Set node layout",
    "app.command.layout.node.clearActiveRootSubtreeLayouts": "Clear active root subtree node layouts",
    "app.toolbar.layout.project": "Layout",
    "app.toolbar.layout.node": "Node layout",
    "app.command.editor.setNodeBodyLayout": "Set node body layout",
    "app.toolbar.editor.layout": "Layout",
    "app.command.mindmap.flushDocsToStore": "Flush cached docs to store",
    "app.command.mindmap.reloadDocsFromStore": "Reload cached docs from store",
    "app.command.mindmap.undo": "Undo",
    "app.command.mindmap.redo": "Redo",
    "app.command.mindmap.addChild": "Add child",
    "app.command.mindmap.addRoot": "Add root",
    "app.command.mindmap.deleteSelection": "Delete selection",
    "app.command.mindmap.deleteSelectionOnly": "Delete only node (keep children)",
    "app.command.mindmap.expandAllDescendants": "Expand all descendants",
    "app.command.mindmap.collapseAllDescendants": "Collapse all descendants",
    "app.command.mindmap.zoomIn": "Zoom in",
    "app.command.mindmap.zoomOut": "Zoom out",
    "app.command.mindmap.zoomTo": "Zoom to",
    "app.command.mindmap.resetZoom": "Reset zoom",
    "app.command.mindmap.panTo": "Pan to",
    "app.command.mindmap.panToFirstRoot": "Pan to first root",
    "app.command.mindmap.fitView": "Fit view",
    "app.command.mindmap.summary.create": "Summary",
    "app.command.mindmap.relation.start": "Relation",
    "app.command.mindmap.relation.setLabel": "Set relation label",
    "app.command.mindmap.relation.setStyle": "Set relation style",
    "app.command.mindmap.relation.setDirection": "Set relation direction",
    "app.command.mindmap.relation.resetStyle": "Reset relation style",
    "app.command.mindmap.relation.resetCurve": "Reset relation curve",
    "app.command.mindmap.relation.setPorts": "Set relation ports",
    "app.toolbar.mindmap.relation.panel": "Relation edit",
    "app.command.nodeLink.open": "Open node link",
    "app.command.nodeLink.copy": "Copy node link",
    "app.command.nodeLink.refreshBacklinks": "Refresh backlinks",
    "app.command.trash.restore": "Restore from trash",
    "app.command.trash.empty": "Empty trash",
    "app.trash.empty.confirm": "Empty trash? This cannot be undone.",
    "app.toolbar.trash.title": "Trash",
    "app.toolbar.trash.empty": "Empty Trash",
    "app.toolbar.trash.restore": "Restore: {title}",
    "app.import.error.pngMissingPayload": "This PNG does not contain a KMind package; export *.kmindz.png or *.kmindz.zip instead.",
    "app.import.error.svgMissingPayload": "This SVG does not contain a KMind package; export *.kmindz / *.kmindz.svg / *.kmindz.zip instead.",
    "app.import.error.unsupportedFileType": "Unsupported file type. Import *.kmindz / *.kmindz.zip / *.kmindz.png / *.kmindz.svg / *.xmind / *.kmind / *.json.",
    "app.import.error.generic": "Import failed.",
    "app.import.error.xmindEncrypted": "This XMind file is encrypted and cannot be imported.",
    "app.import.error.xmindInvalidFile": "This XMind file is invalid or corrupted.",
    "app.import.error.xmindMissingContentJson": "This XMind file does not contain content.json.",
    "app.import.error.xmindUnsupportedXml": "This XMind file uses the older content.xml format, which is not supported in this phase.",
    "app.import.error.xmindUnsupportedZipCompression": "This XMind file uses a zip compression method that is not supported.",
    "app.dialog.import.confirm.replaceProject": "Import into current mindmap? This will overwrite the project (submaps & assets will be replaced).",
    "app.dialog.import.confirm.replaceCurrentMap": "This will replace the current map. Continue?",
    "app.dialog.import.markdown.empty": "Paste markdown headings first.",
    "app.import.preflight.title": "Compatibility check",
    "app.import.preflight.summary": "This external import will discard or rewrite {count} incompatible item(s) across {categories} category(ies):",
    "app.import.preflight.confirmContinue": "Continue importing anyway?",
    "app.import.preflight.issue.dropUnderline": "Drop underline style: {count}",
    "app.import.preflight.issue.dropTextAlign": "Drop text alignment style: {count}",
    "app.import.preflight.issue.dropInlineImage": "Convert inline image to text placeholder: {count}",
    "app.import.preflight.issue.dropUnsupportedTag": "Drop unsupported HTML tag: {count}",
    "app.import.preflight.issue.dropUnsupportedStyle": "Drop unsupported rich-text style: {count}",
    "app.import.preflight.issue.sanitizeUnsafeLink": "Drop unsafe or invalid link: {count}",
    "app.import.preflight.issue.dropXmindMarker": "Drop unsupported XMind marker: {count}",
    "app.import.preflight.issue.dropXmindBoundary": "Drop unsupported XMind boundary: {count}",
    "app.import.preflight.issue.dropXmindAttachment": "Drop unsupported XMind attachment: {count}",
    "app.import.preflight.issue.dropXmindCallout": "Drop unsupported XMind callout: {count}",
    "app.import.preflight.issue.dropXmindRemoteImage": "Drop remote or unsupported XMind image: {count}",
    "app.import.preflight.issue.dropXmindRelationship": "Drop relationship with unresolved endpoint: {count}",
    "app.import.preflight.issue.dropXmindSummary": "Drop summary with unresolved range: {count}",
    "app.documentZip.importFail.missingManifest": "Import failed: zip missing manifest.json.",
    "app.documentZip.importFail.unsupportedVersion": "Import failed: unsupported package version.",
    "app.documentZip.importFail.missingDocFile": "Import failed: missing document file {path}.",
    "app.documentZip.importFail.missingRootDoc": "Import failed: package missing the document referenced by rootDocId.",
    "app.documentZip.importFail.missingLegacyDocJson": "Import failed: zip missing doc.json (legacy format).",
    "app.documentZip.importFail.unresolvedRootDocId": "Import failed: cannot resolve rootDocId.",
    "app.documentZip.importFail.missingAssetFile": "Import failed: missing asset file {path}.",
    "app.documentZip.importFail.missingSubmapDoc": 'Import failed: package missing submap document "{subId}".',
    "app.host.clipboardUnavailableCopy": "Clipboard is not available in current host; cannot copy.",
    "app.host.clipboardUnavailablePaste": "Clipboard is not available in current host; cannot paste.",
    "app.host.clipboardReadFailed": "Failed to read clipboard (requires user permission).",
    "app.host.clipboardWriteFailed": "Copy failed (clipboard may be blocked by permissions).",
    "app.host.clipboardWritePngFailed": "Copy PNG failed (clipboard may be blocked by permissions).",
    "app.host.filesDownloadUnsupported": "Current host does not support exporting files.",
    "app.host.filesOpenUnsupported": "Current host does not support selecting files for import.",
    "app.host.assetsUnsupportedForImport": "Current host does not support asset storage; cannot import packages with images.",
    "app.export.pngFallbackFast": "PNG export has fallen back to fast (may omit rich text/images).",
    "app.export.error.generic": "Export failed.",
    "app.clipboard.subtree.invalidPayload": "Clipboard content is not KMind subtree data.",
    "app.clipboard.subtree.invalidJson": "Failed to parse clipboard (content is not JSON).",
    "app.trash.restoreFailed.idConflict": "Restore failed: document ID conflict. Please retry later.",
    "app.submap.missingOrDeleted": "Submap does not exist or has been deleted.",
    "app.submap.targetNotReachable": "Target map is not reachable from current project.",
    "app.submap.targetMissingOrDeleted": "Target map does not exist or has been deleted.",
    "app.submap.defaultTitle": "SubMap",
    "app.command.submap.open": "Open submap",
    "app.command.submap.createAndEnter": "Create and enter submap",
    "app.command.submap.enter": "Enter submap",
    "app.command.submap.back": "Back to parent map",
    "app.command.submap.resetToRoot": "Go to main map",
    "app.command.submap.popTo": "Pop to map",
    "app.command.submap.navigateTo": "Navigate to map",
    "app.command.submap.rename": "Rename map",
    "app.command.submap.delete": "Delete map",
    "app.toolbar.submap.open": "SubMap",
    "app.toolbar.submap.back": "Back",
    "app.dialog.submap.delete.confirm": 'Delete map "{title}"? This action cannot be undone.',
    "app.theme.unknownPreset": "Unknown theme preset.",
    "app.theme.invalidPackage": "Invalid theme package.",
    "app.themeDesigner.title": "Theme Designer",
    "app.themeDesigner.aria.preset": "Built-in theme template",
    "app.themeDesigner.aria.previewCanvas": "Theme preview canvas",
    "app.themeDesigner.preview.root": "KMind Zen\nTheme Designer",
    "app.themeDesigner.preview.design": "Design",
    "app.themeDesigner.preview.colors": "Colors",
    "app.themeDesigner.preview.typography": "Typography",
    "app.themeDesigner.preview.shapes": "Shape",
    "app.themeDesigner.preview.layout": "Layout",
    "app.themeDesigner.preview.edges": "Edges",
    "app.themeDesigner.preview.cubic": "Bezier",
    "app.themeDesigner.preview.orthogonal": "Orthogonal",
    "app.themeDesigner.preview.tapered": "Tapered",
    "app.themeDesigner.preview.baseline": "Baseline fork",
    "app.themeDesigner.preview.rules": "Rules",
    "app.themeDesigner.preview.depth": "By depth",
    "app.themeDesigner.preview.range": "By range",
    "app.themeDesigner.preview.conditions": "Conditions",
    "app.themeDesigner.preview.overrides": "Overrides",
    "app.themeDesigner.preview.export": "Export",
    "app.themeDesigner.preview.image": "Image",
    "app.themeDesigner.preview.themeFile": "Theme file",
    "app.themeDesigner.preview.import": "Import",
    "app.themeDesigner.preview.plugin": "Plugin",
    "app.themeDesigner.preview.level3Plus": "Level 3+",
    "app.themeDesigner.preview.summaryEdges": "Edge route set",
    "app.themeDesigner.preview.summaryEdgeExamples": "Edge examples",
    "app.themeDesigner.preview.relationDefaults": "Shared defaults",
    "app.themeDesigner.variant.light": "Light",
    "app.themeDesigner.variant.dark": "Dark",
    "app.themeDesigner.action.saveTheme": "Save theme",
    "app.themeDesigner.action.saveDraft": "Save draft",
    "app.themeDesigner.action.shareTheme": "Share theme",
    "app.themeDesigner.action.submitReview": "Submit review",
    "app.themeDesigner.action.applyToMap": "Apply to map",
    "app.themeDesigner.action.importThemePackage": "Import theme package",
    "app.themeDesigner.action.exportThemePackage": "Export theme package",
    "app.themeDesigner.action.import": "Import",
    "app.themeDesigner.status.fixBeforeSave": "Fix validation issues before saving the theme.",
    "app.themeDesigner.status.fixBeforeApply": "Fix validation issues before applying to the map.",
    "app.themeDesigner.status.fixBeforeShare": "Fix validation issues before sharing the theme.",
    "app.themeDesigner.status.saved": "Theme saved.",
    "app.themeDesigner.status.saveFailed": "Failed to save theme.",
    "app.themeDesigner.status.loadDraftFailed": "Failed to load theme draft.",
    "app.themeDesigner.status.applied": "Applied to the map.",
    "app.themeDesigner.status.applyFailed": "Failed to apply theme.",
    "app.themeDesigner.status.shareSubmitted": "Submitted for Share Center review.",
    "app.themeDesigner.status.shareNamedSubmitted": 'Submitted "{name}" for Share Center review.',
    "app.themeDesigner.status.shareFailed": "Failed to share theme.",
    "app.themeDesigner.status.exported": "Theme exported.",
    "app.themeDesigner.status.exportFailed": "Failed to export theme.",
    "app.themeDesigner.status.presetSwitched": 'Switched to "{name}" template.',
    "app.themeDesigner.status.localLoaded": 'Loaded "{name}".',
    "app.themeDesigner.status.renamed": "Theme renamed.",
    "app.themeDesigner.status.renameFailed": "Failed to rename theme.",
    "app.themeDesigner.status.duplicated": 'Duplicated as "{name}".',
    "app.themeDesigner.status.duplicateFailed": "Failed to duplicate theme.",
    "app.themeDesigner.status.deleted": "Local theme deleted.",
    "app.themeDesigner.status.deleteFailed": "Failed to delete local theme.",
    "app.themeDesigner.status.imported": 'Imported "{name}".',
    "app.themeDesigner.status.importFailed": "Failed to import theme.",
    "app.themeDesigner.status.draftImported": 'Imported "{name}" into the current draft.',
    "app.themeDesigner.error.invalidSharePackage": "Invalid theme share package.",
    "app.themeDesigner.confirm.dirtyPreset": "The current theme has unsaved changes. Switching the built-in template will discard them. Continue?",
    "app.themeDesigner.confirm.dirtyLocal": "The current theme has unsaved changes. Loading a local theme will discard them. Continue?",
    "app.themeDesigner.confirm.deleteLocal": 'Delete local theme "{name}"? Inline themes already applied to maps will not be changed.',
    "app.themeDesigner.confirm.dirtyImportDraft": "The current theme has unsaved changes. Importing a theme package will replace the current draft. Continue?",
    "app.themeDesigner.web.shareConfirm": "Submit the current theme draft to Share Center review? If this theme was shared before, an unpublished submission updates the same review item; a published theme creates a new version and replaces the public version after approval.",
    "app.themeDesigner.info.title": "Theme info",
    "app.themeDesigner.info.status.filled": "Filled",
    "app.themeDesigner.info.status.nameRequired": "Name required",
    "app.themeDesigner.info.name": "Name",
    "app.themeDesigner.info.description": "Description",
    "app.themeDesigner.info.tags": "Tags",
    "app.themeDesigner.info.tags.placeholder": "minimal, dark, business",
    "app.themeDesigner.info.tags.hint": "Press Enter or comma to confirm. Up to 12 tags.",
    "app.themeDesigner.info.tags.remove": "Remove tag {tag}",
    "app.themeDesigner.library.title": "Local theme library",
    "app.themeDesigner.library.subtitle": "Plugin-level theme assets reusable across maps.",
    "app.themeDesigner.library.storageUnavailable": "This host has not provided a theme library storage port.",
    "app.themeDesigner.library.empty": "No local themes yet. Save the current theme and it will appear here.",
    "app.themeDesigner.library.renameAria": "Theme name",
    "app.themeDesigner.library.action.saveName": "Save name",
    "app.themeDesigner.library.action.cancel": "Cancel",
    "app.themeDesigner.library.action.load": "Load",
    "app.themeDesigner.library.action.apply": "Apply",
    "app.themeDesigner.library.action.shareOnline": "Share online",
    "app.themeDesigner.library.action.rename": "Rename",
    "app.themeDesigner.library.action.duplicate": "Duplicate",
    "app.themeDesigner.library.action.export": "Export",
    "app.themeDesigner.library.action.delete": "Delete",
    "app.themeDesigner.library.source.imported": "Imported",
    "app.themeDesigner.library.source.installed": "Installed",
    "app.themeDesigner.library.source.official": "Official",
    "app.themeDesigner.library.source.local": "Local",
    "app.themeDesigner.library.updatedAt.missing": "Not recorded",
    "app.themeDesigner.library.updatedAt.fallback": "Updated",
    "app.themeDesigner.validation.title": "Theme validation",
    "app.themeDesigner.validation.ready": "Ready to save",
    "app.themeDesigner.validation.issueCount": "{count} issue(s)",
    "app.themeDesigner.validation.invalidColor": "{path}: Unsupported color format",
    "app.themeDesigner.validation.invalidRoute": "{path}: Unsupported edge route",
    "app.themeDesigner.validation.invalidNumber": "{path}: Number is out of supported range",
    "app.themeDesigner.validation.invalidSelector": "{path}: Unsupported node matching rule",
    "app.themeDesigner.validation.invalidTheme": "{path}: Theme structure is incomplete",
    "app.themeDesigner.validation.invalidPackage": "{path}: Invalid theme package",
    "app.themeDesigner.level.root": "Root",
    "app.themeDesigner.level.level1": "Level 1",
    "app.themeDesigner.level.level2": "Level 2",
    "app.themeDesigner.level.level3Plus": "Level 3+",
    "app.themeDesigner.inspector.sectionTitle": "{level} style",
    "app.themeDesigner.inspector.nodeFallback": "Node",
    "app.themeDesigner.field.nodeFill": "Fill",
    "app.themeDesigner.field.nodeFill.tooltip": "Fill color for nodes at the current level",
    "app.themeDesigner.field.text": "Text color",
    "app.themeDesigner.field.text.tooltip": "Text color for nodes at the current level",
    "app.themeDesigner.field.nodeStroke": "Stroke",
    "app.themeDesigner.field.nodeStroke.tooltip": "Border color for nodes at the current level",
    "app.themeDesigner.field.strokeWidth": "Stroke width",
    "app.themeDesigner.field.strokeWidth.tooltip": "Border width for nodes at the current level. Set to 0 to hide the border.",
    "app.themeDesigner.field.radius": "Corner radius",
    "app.themeDesigner.field.radius.tooltip": "The formal theme designer is fixed to rounded rectangles. This adjusts the corner radius.",
    "app.themeDesigner.field.fontFamily": "Font",
    "app.themeDesigner.field.fontFamily.tooltip": "Font family used by nodes at the current level",
    "app.themeDesigner.field.fontSize": "Font size",
    "app.themeDesigner.field.fontSize.tooltip": "Text size for nodes at the current level",
    "app.themeDesigner.field.fontWeight": "Font weight",
    "app.themeDesigner.field.fontWeight.tooltip": "Text weight for nodes at the current level",
    "app.themeDesigner.field.textAlign": "Align",
    "app.themeDesigner.field.textAlign.tooltip": "Text alignment for nodes at the current level",
    "app.themeDesigner.option.align.left": "Left",
    "app.themeDesigner.option.align.center": "Center",
    "app.themeDesigner.option.align.right": "Right",
    "app.themeDesigner.edge.title": "Incoming edge",
    "app.themeDesigner.field.edgeRoute": "Route",
    "app.themeDesigner.field.edgeRoute.tooltip": "Connection style from the parent node to the current level",
    "app.themeDesigner.field.edgeColor": "Color",
    "app.themeDesigner.field.edgeColor.tooltip": "Incoming edge stroke color",
    "app.themeDesigner.field.edgeWidth": "Width",
    "app.themeDesigner.field.edgeWidth.tooltip": "Incoming edge stroke width",
    "app.themeDesigner.field.edgeDash": "Dash",
    "app.themeDesigner.field.edgeDash.tooltip": "Incoming edge dash pattern",
    "app.themeDesigner.global.title": "Global style",
    "app.themeDesigner.field.relationColor": "Relation color",
    "app.themeDesigner.field.relationColor.tooltip": "Global relation line color",
    "app.themeDesigner.field.relationWidth": "Relation width",
    "app.themeDesigner.field.relationWidth.tooltip": "Global relation line width",
    "app.themeDesigner.field.relationDash": "Relation dash",
    "app.themeDesigner.field.relationDash.tooltip": "Global relation line dash pattern",
    "app.themeDesigner.field.summaryColor": "Summary color",
    "app.themeDesigner.field.summaryColor.tooltip": "Summary bracket line color",
    "app.themeDesigner.field.canvasBackground": "Canvas background",
    "app.themeDesigner.field.canvasBackground.tooltip": "Canvas background color for the current light / dark mode",
    "app.themeDesigner.field.rainbow": "Rainbow edges",
    "app.themeDesigner.field.rainbow.tooltip": "Use theme palette colors for child branch edges",
    "app.themeDesigner.spacing.title": "Node spacing",
    "app.themeDesigner.field.horizontalGap": "Horizontal gap",
    "app.themeDesigner.field.horizontalGap.tooltip": "Horizontal distance between levels",
    "app.themeDesigner.field.verticalGap": "Vertical gap",
    "app.themeDesigner.field.verticalGap.tooltip": "Vertical distance between sibling nodes",
    "app.themeDesigner.dash.solid": "Solid",
    "app.themeDesigner.dash.dashed": "Dashed",
    "app.themeDesigner.dash.dotted": "Dotted",
    "app.themeDesigner.color.transparent": "Transparent",
    "app.themeDesigner.color.swatchAria": "{label} color swatch",
    "app.themeDesigner.edgeRoute.cubic": "Bezier curve",
    "app.themeDesigner.edgeRoute.quadratic": "Quadratic curve",
    "app.themeDesigner.edgeRoute.center-quadratic": "Center arc",
    "app.themeDesigner.edgeRoute.center-quadratic-tapered": "Tapered center arc",
    "app.themeDesigner.edgeRoute.edge-lead-quadratic": "Edge-lead curve",
    "app.themeDesigner.edgeRoute.edge-lead-quadratic-tapered": "Tapered edge-lead curve",
    "app.themeDesigner.edgeRoute.straight": "Straight",
    "app.themeDesigner.edgeRoute.orthogonal": "Orthogonal",
    "app.themeDesigner.edgeRoute.orthogonal-rounded": "Rounded orthogonal",
    "app.themeDesigner.edgeRoute.tapered": "Tapered curve",
    "app.toolbar.theme.title": "Theme",
    "app.command.theme.applyPreset": "Apply theme preset",
    "app.command.theme.applyPackage": "Apply theme package",
    "app.command.theme.rainbow.toggle": "Toggle rainbow edges",
    "app.command.theme.rainbow.toggleForRoot": "Toggle rainbow edges for root",
    "app.command.theme.rainbow.setEnabled": "Set rainbow edges enabled",
    "app.command.theme.relation.setProjectStyle": "Set project relation line style",
    "app.command.theme.relation.setRootStyle": "Set root relation line style",
    "app.command.theme.edgeRoute.applyToRootSubtree": "Apply edge route type to root subtree",
    "app.command.theme.edgeDasharray.applyToSubtree": "Apply edge dasharray to subtree",
    "app.command.theme.edgeStrokeWidth.applyToSubtree": "Apply edge stroke width to subtree",
    "app.command.theme.nodeOverride.merge": "Merge node theme override",
    "app.command.theme.nodeStyle.applyToSiblings": "Apply node style to siblings",
    "app.nodeLink.targetDocMissingOrDeleted": "Target document does not exist or has been deleted.",
    "app.nodeLink.addFailed.targetDocMissing": "Add failed: target document does not exist: {docId}",
    "app.nodeLink.addFailed.targetNodeMissing": "Add failed: target node does not exist: {ref}",
    "app.contextMenu.canvas.panToRoot": "Pan to root",
    "app.contextMenu.canvas.backToMainMap": "Back to main map",
    "app.contextMenu.canvas.resetZoom": "Reset zoom (100%)",
    "app.contextMenu.canvas.newRoot": "New root node",
    "app.contextMenu.canvas.zen.enter": "Enter zen mode",
    "app.contextMenu.canvas.zen.exit": "Exit zen mode",
    "app.contextMenu.canvas.readOnly.enter": "Enter read-only mode",
    "app.contextMenu.canvas.readOnly.exit": "Exit read-only mode",
    "app.contextMenu.common.copyAs": "Copy as",
    "app.contextMenu.common.copyAs.png": "Image (PNG)",
    "app.contextMenu.common.copyAs.markdown": "Markdown",
    "app.contextMenu.common.copyAs.id": "ID",
    "app.contextMenu.common.copyImage": "Copy as image",
    "app.contextMenu.common.copyImage.original": "Original",
    "app.contextMenu.common.copyImage.original.description": "Copy as-is with the current map style.",
    "app.contextMenu.common.copyImage.window": "Window",
    "app.contextMenu.common.copyImage.window.description": "Add a clean window frame and soft shadow.",
    "app.contextMenu.node.todo.add": "Add Todo",
    "app.contextMenu.node.todo.remove": "Delete Todo",
    "app.contextMenu.node.notes.open": "Notes",
    "app.contextMenu.node.comments.open": "Comment",
    "app.contextMenu.node.copy.plainText": "Copy plain text",
    "app.contextMenu.node.copy.subtree": "Copy node subtree",
    "app.contextMenu.node.paste.subtree": "Paste node subtree",
    "app.contextMenu.node.copy.link": "Copy Link",
    "app.contextMenu.node.submap.open": "Down drill (SubMap)",
    "app.contextMenu.node.delete": "Delete",
    "app.contextMenu.node.deleteOnly": "Delete only node",
    "app.contextMenu.node.expandAll": "Expand all descendants",
    "app.contextMenu.node.collapseAll": "Collapse all descendants"
  },
  "zh-CN": {
    "kmind.common.untitled": "\u672A\u547D\u540D",
    "app.command.document.exportSvg": "\u5BFC\u51FA SVG",
    "app.command.document.exportPng": "\u5BFC\u51FA PNG",
    "app.command.document.exportSvgPackage": "\u5BFC\u51FA KMindz SVG \u5305",
    "app.command.document.exportKmindzPackage": "\u5BFC\u51FA KMindz \u5305",
    "app.command.document.exportPngPackage": "\u5BFC\u51FA KMindz PNG \u5305",
    "app.command.document.exportZip": "\u5BFC\u51FA KMindz Zip",
    "app.command.document.import": "\u5BFC\u5165",
    "app.command.document.importZip": "\u5BFC\u5165 Zip",
    "app.toolbar.document.import": "\u5BFC\u5165",
    "app.toolbar.document.export": "\u5BFC\u51FA",
    "app.command.document.new": "\u65B0\u5EFA\u5BFC\u56FE",
    "app.command.document.switch": "\u5207\u6362\u5BFC\u56FE",
    "app.command.document.rename": "\u91CD\u547D\u540D\u5BFC\u56FE",
    "app.command.document.renameTo": "\u91CD\u547D\u540D\u5BFC\u56FE\uFF08\u5185\u8054\uFF09",
    "app.command.document.delete": "\u5220\u9664\u5BFC\u56FE",
    "app.command.document.saveNow": "\u4FDD\u5B58\u5BFC\u56FE",
    "app.command.document.refreshFromStore": "\u4ECE\u5B58\u50A8\u91CD\u65B0\u52A0\u8F7D",
    "app.toolbar.document.new": "\u65B0\u5EFA",
    "app.toolbar.document.switcher": "\u5BFC\u56FE",
    "app.toolbar.document.rename": "\u91CD\u547D\u540D",
    "app.toolbar.document.delete": "\u5220\u9664",
    "app.dialog.document.rename.title": "\u91CD\u547D\u540D",
    "app.dialog.document.rename.message": "\u5BFC\u56FE\u6807\u9898",
    "app.dialog.document.delete.confirm.moveToTrash": "\u5C06\u5F53\u524D\u5BFC\u56FE\u79FB\u5165\u56DE\u6536\u7AD9\u5417\uFF1F",
    "app.dialog.document.delete.confirm.cascadeToTrash": "\u8BE5\u5BFC\u56FE\u5305\u542B {count} \u4E2A\u5B50\u5BFC\u56FE\uFF0C\u662F\u5426\u4E00\u5E76\u79FB\u5165\u56DE\u6536\u7AD9\uFF1F",
    "app.dialog.document.delete.confirm.delete": "\u5220\u9664\u5F53\u524D\u5BFC\u56FE\u5417\uFF1F",
    "app.selectionToolbar.changeTheme": "\u5207\u6362\u4E3B\u9898",
    "app.selectionToolbar.nodeStyle": "\u8282\u70B9\u6837\u5F0F",
    "editor.changeTheme.section.layout": "\u5E03\u5C40",
    "editor.changeTheme.option.inherit": "\u7EE7\u627F",
    "app.command.view.zen.toggle": "\u5207\u6362\u7985\u6A21\u5F0F",
    "app.command.view.readOnly.toggle": "\u5207\u6362\u53EA\u8BFB\u6A21\u5F0F",
    "app.command.projectSearch.open": "\u9879\u76EE\u5185\u641C\u7D22",
    "app.command.projectSearch.close": "\u5173\u95ED\u641C\u7D22",
    "app.command.projectSearch.toggle": "\u5207\u6362\u641C\u7D22",
    "app.toolbar.about": "\u5173\u4E8E",
    "app.command.mindmap.summary.reveal": "\u5B9A\u4F4D\u6982\u8981",
    "appPage.popover.projectSearch.title": "\u641C\u7D22",
    "appPage.popover.projectSearch.query.placeholder": "\u5728\u8282\u70B9 / \u5907\u6CE8 / \u6279\u6CE8\u4E2D\u641C\u7D22\u2026",
    "appPage.popover.projectSearch.section.mode": "\u6A21\u5F0F",
    "appPage.popover.projectSearch.mode.plain": "\u666E\u901A",
    "appPage.popover.projectSearch.mode.regex": "\u6B63\u5219",
    "appPage.popover.projectSearch.mode.fuzzy": "\u6A21\u7CCA",
    "appPage.popover.projectSearch.section.fields": "\u8303\u56F4",
    "appPage.popover.projectSearch.field.nodes": "\u8282\u70B9",
    "appPage.popover.projectSearch.field.notes": "\u5907\u6CE8",
    "appPage.popover.projectSearch.field.comments": "\u6279\u6CE8",
    "appPage.popover.projectSearch.entity.summary": "\u6982\u8981",
    "appPage.popover.projectSearch.option.caseSensitive": "\u5927\u5C0F\u5199\u654F\u611F",
    "appPage.popover.projectSearch.option.wholeWord": "\u5168\u8BCD\u5339\u914D",
    "appPage.popover.projectSearch.section.replace": "\u66FF\u6362",
    "appPage.popover.projectSearch.replace.placeholder": "\u66FF\u6362\u4E3A\u2026",
    "appPage.popover.projectSearch.action.replaceSelected": "\u66FF\u6362\u5F53\u524D\u9879",
    "appPage.popover.projectSearch.action.replaceAll": "\u5168\u90E8\u66FF\u6362",
    "appPage.popover.projectSearch.hint.fuzzyNoReplace": "\u6A21\u7CCA\u6A21\u5F0F\u4E0D\u652F\u6301\u66FF\u6362\u3002",
    "appPage.popover.projectSearch.hint.readOnlyNoReplace": "\u53EA\u8BFB\u6A21\u5F0F\uFF1A\u66FF\u6362\u5DF2\u7981\u7528\u3002",
    "appPage.popover.projectSearch.status.typeToSearch": "\u8F93\u5165\u5173\u952E\u8BCD\u5F00\u59CB\u641C\u7D22\u3002",
    "appPage.popover.projectSearch.status.searching": "\u641C\u7D22\u4E2D\u2026",
    "appPage.popover.projectSearch.status.noResults": "\u65E0\u7ED3\u679C",
    "appPage.popover.projectSearch.error.invalidRegex": "\u6B63\u5219\u65E0\u6548\uFF1A{message}",
    "appPage.popover.projectSearch.confirm.replaceAll": "\u786E\u8BA4\u66FF\u6362 {maps} \u5F20\u5BFC\u56FE\u4E2D\u7684 {matches} \u5904\u547D\u4E2D\uFF1F",
    "appPage.popover.about.title": "\u5173\u4E8E KMind Zen",
    "appPage.popover.about.appVersion": "\u5E94\u7528\u7248\u672C",
    "appPage.popover.about.coreVersion": "\u5185\u6838\u7248\u672C",
    "appPage.popover.about.website": "\u5B98\u7F51",
    "appPage.popover.about.action.openWebsite": "\u6253\u5F00\u5B98\u7F51",
    "appPage.popover.import.subtitle": "\u5BFC\u5165 KMind Zen \u6570\u636E\u5305\u3001XMind \u6587\u4EF6\u3001\u8001 `.kmind` \u6587\u4EF6\uFF0C\u6216\u76F4\u63A5\u7C98\u8D34 Markdown \u6807\u9898\u3002",
    "appPage.popover.import.file.label": "\u5BFC\u5165\u6587\u4EF6",
    "appPage.popover.import.file.desc": "\u81EA\u52A8\u8BC6\u522B *.kmindz / *.svg / *.png / *.zip\u3001*.xmind\uFF0C\u4EE5\u53CA\u8001 *.kmind / *.json\u3002",
    "appPage.popover.import.file.action": "\u9009\u62E9\u6587\u4EF6\u2026",
    "appPage.popover.import.markdown.label": "\u7C98\u8D34 Markdown \u6807\u9898",
    "appPage.popover.import.markdown.placeholder": "# \u6807\u9898\n## \u5C0F\u8282\n### \u6761\u76EE",
    "appPage.popover.import.markdown.clear": "\u6E05\u7A7A",
    "appPage.popover.import.markdown.action": "\u66FF\u6362\u5F53\u524D\u5BFC\u56FE",
    "appPage.popover.import.status.noActiveEditor": "\u5F53\u524D\u6CA1\u6709\u53EF\u7528\u7684\u7F16\u8F91\u5668\u5B9E\u4F8B\uFF0C\u6682\u65F6\u65E0\u6CD5\u5BFC\u5165\u3002",
    "appPage.popover.import.status.filePickerUnavailable": "\u5F53\u524D\u5BBF\u4E3B\u4E0D\u652F\u6301\u6253\u5F00\u6587\u4EF6\u9009\u62E9\u5668\u3002",
    "appPage.floatingToolbar.shortcuts.section.commands": "\u5BFC\u56FE\u547D\u4EE4",
    "appPage.floatingToolbar.shortcuts.section.richText": "\u5BCC\u6587\u672C\u7F16\u8F91",
    "appPage.floatingToolbar.shortcuts.richText.bold": "\u52A0\u7C97",
    "appPage.floatingToolbar.shortcuts.richText.italic": "\u659C\u4F53",
    "appPage.floatingToolbar.shortcuts.richText.strike": "\u5220\u9664\u7EBF",
    "appPage.floatingToolbar.shortcuts.richText.inlineCode": "\u884C\u5185\u4EE3\u7801",
    "appPage.floatingToolbar.shortcuts.richText.codeBlock": "\u4EE3\u7801\u5757",
    "appPage.floatingToolbar.shortcuts.richText.formula": "\u516C\u5F0F",
    "appPage.floatingToolbar.shortcuts.richText.slashMenu": "\u659C\u6760\u83DC\u5355",
    "appPage.floatingToolbar.shortcuts.richText.slashMenu.desc": "\u5728\u884C\u9996\u6216\u7A7A\u767D\u540E\u89E6\u53D1",
    "appPage.floatingToolbar.shortcuts.richText.hardBreak": "\u6362\u884C",
    "appPage.floatingToolbar.shortcuts.richText.paragraph": "\u65B0\u6BB5\u843D",
    "appPage.floatingToolbar.shortcuts.richText.commit": "\u5B8C\u6210\u7F16\u8F91",
    "appPage.floatingToolbar.shortcuts.richText.commit.desc": "Enter \u662F\u5426\u7EE7\u7EED\u521B\u5EFA\u540C\u7EA7\u8282\u70B9\u53D6\u51B3\u4E8E\u5F53\u524D\u7F16\u8F91\u6A21\u5F0F",
    "appPage.floatingToolbar.shortcuts.richText.cancel": "\u53D6\u6D88\u7F16\u8F91",
    "app.toolbar.node.icons": "\u56FE\u6807",
    "app.toolbar.node.panel": "\u8282\u70B9",
    "app.command.node.width.set": "\u8BBE\u7F6E\u8282\u70B9\u6B63\u6587\u5BBD\u5EA6",
    "app.command.node.width.setMode": "\u8BBE\u7F6E\u8282\u70B9\u6B63\u6587\u5BBD\u5EA6\u6A21\u5F0F",
    "app.command.node.width.reset": "\u91CD\u7F6E\u8282\u70B9\u6B63\u6587\u5BBD\u5EA6",
    "app.command.node.task.toggleMode": "\u5207\u6362\u5F85\u529E\u6A21\u5F0F",
    "app.command.node.task.toggleDone": "\u5207\u6362\u5F85\u529E\u5B8C\u6210",
    "app.command.node.todo.add": "\u6DFB\u52A0\u5F85\u529E",
    "app.command.node.todo.remove": "\u5220\u9664\u5F85\u529E",
    "app.command.node.icon.add": "\u6DFB\u52A0\u56FE\u6807",
    "app.command.node.icon.remove": "\u5220\u9664\u56FE\u6807",
    "app.command.node.icon.move": "\u79FB\u52A8\u56FE\u6807",
    "app.command.node.icon.set": "\u8BBE\u7F6E\u56FE\u6807",
    "app.command.node.tag.add": "\u6DFB\u52A0\u6807\u7B7E",
    "app.command.node.tag.remove": "\u5220\u9664\u6807\u7B7E",
    "app.command.node.link.addExternal": "\u6DFB\u52A0\u5916\u94FE",
    "app.command.node.link.updateExternal": "\u66F4\u65B0\u5916\u94FE",
    "app.command.node.link.moveExternal": "\u79FB\u52A8\u5916\u94FE",
    "app.command.node.link.addInternal": "\u6DFB\u52A0\u5185\u94FE",
    "app.command.node.link.connect": "\u8FDE\u63A5\u8282\u70B9\uFF08\u5185\u94FE\uFF09",
    "app.command.node.link.updateInternal": "\u66F4\u65B0\u5185\u94FE",
    "app.command.node.link.remove": "\u5220\u9664\u94FE\u63A5",
    "app.command.node.link.removeMany": "\u5220\u9664\u591A\u4E2A\u94FE\u63A5",
    "app.command.node.image.add": "\u6DFB\u52A0\u56FE\u7247",
    "app.command.node.image.paste": "\u7C98\u8D34\u56FE\u7247",
    "app.command.node.image.remove": "\u5220\u9664\u56FE\u7247",
    "app.command.node.image.setRegion": "\u8BBE\u7F6E\u56FE\u7247\u4F4D\u7F6E",
    "app.command.node.image.setSize": "\u8BBE\u7F6E\u56FE\u7247\u5C3A\u5BF8",
    "app.command.node.image.setFit": "\u8BBE\u7F6E\u56FE\u7247\u9002\u5E94",
    "app.command.node.notes.setText": "\u8BBE\u7F6E\u5907\u6CE8",
    "app.command.node.notes.open": "\u7F16\u8F91\u5907\u6CE8",
    "app.command.node.notes.clear": "\u6E05\u9664\u5907\u6CE8",
    "app.command.node.comments.add": "\u6DFB\u52A0\u6279\u6CE8",
    "app.command.node.comments.open": "\u6DFB\u52A0\u6279\u6CE8",
    "app.command.node.comments.remove": "\u5220\u9664\u6279\u6CE8",
    "app.command.node.comments.update": "\u66F4\u65B0\u6279\u6CE8",
    "app.command.node.comments.clear": "\u6E05\u7A7A\u6279\u6CE8",
    "app.command.clipboard.refresh": "\u5237\u65B0\u526A\u8D34\u677F\u63D0\u793A",
    "app.command.node.clipboard.copyPlainText": "\u590D\u5236\u7EAF\u6587\u672C",
    "app.command.node.clipboard.copyNodeId": "\u590D\u5236\u8282\u70B9 ID",
    "app.command.node.clipboard.copySubtree": "\u590D\u5236\u8282\u70B9\u5B50\u6811",
    "app.command.node.clipboard.pasteSubtree": "\u7C98\u8D34\u8282\u70B9\u5B50\u6811",
    "app.command.node.clipboard.copyMarkdown": "\u590D\u5236\u8282\u70B9\u5B50\u6811\u4E3A Markdown",
    "app.command.mindmap.clipboard.copyMarkdown": "\u590D\u5236\u5BFC\u56FE\u4E3A Markdown",
    "app.command.node.clipboard.copyPng": "\u590D\u5236\u8282\u70B9\u5B50\u6811\u4E3A PNG",
    "app.command.mindmap.clipboard.copyPng": "\u590D\u5236\u5F53\u524D\u89C6\u56FE\u4E3A PNG",
    "app.command.project.background.setColor": "\u8BBE\u7F6E\u9879\u76EE\u80CC\u666F\u8272",
    "app.command.layout.project.clearThemeDefaults": "\u6E05\u7406\u4E3B\u9898\u9ED8\u8BA4\u9879\u76EE\u8BBE\u7F6E",
    "app.command.layout.project.setDefaultRootLayout": "\u8BBE\u7F6E\u9879\u76EE\u9ED8\u8BA4\u6839\u5E03\u5C40",
    "app.command.layout.project.setOptions": "\u8BBE\u7F6E\u9879\u76EE\u5E03\u5C40\u95F4\u8DDD",
    "app.command.layout.project.applyDensityPreset": "\u5E94\u7528\u9879\u76EE\u5BC6\u5EA6\u9884\u8BBE",
    "app.command.layout.root.setOptions": "\u8BBE\u7F6E Root \u5E03\u5C40\u95F4\u8DDD",
    "app.command.layout.node.setLayout": "\u8BBE\u7F6E\u8282\u70B9\u5E03\u5C40",
    "app.command.layout.node.clearActiveRootSubtreeLayouts": "\u6E05\u9664\u5F53\u524D Root \u5B50\u6811\u8282\u70B9\u5E03\u5C40",
    "app.toolbar.layout.project": "\u5E03\u5C40",
    "app.toolbar.layout.node": "\u8282\u70B9\u5E03\u5C40",
    "app.command.editor.setNodeBodyLayout": "\u8BBE\u7F6E\u8282\u70B9\u4E3B\u4F53\u5E03\u5C40",
    "app.toolbar.editor.layout": "\u5E03\u5C40",
    "app.command.mindmap.flushDocsToStore": "\u5199\u56DE\u7F13\u5B58\u5BFC\u56FE\u5230\u5B58\u50A8",
    "app.command.mindmap.reloadDocsFromStore": "\u4ECE\u5B58\u50A8\u91CD\u65B0\u52A0\u8F7D\u7F13\u5B58\u5BFC\u56FE",
    "app.command.mindmap.undo": "\u64A4\u9500",
    "app.command.mindmap.redo": "\u91CD\u505A",
    "app.command.mindmap.addChild": "\u6DFB\u52A0\u5B50\u8282\u70B9",
    "app.command.mindmap.addRoot": "\u6DFB\u52A0\u6839\u8282\u70B9",
    "app.command.mindmap.deleteSelection": "\u5220\u9664\u9009\u4E2D",
    "app.command.mindmap.deleteSelectionOnly": "\u4EC5\u5220\u9664\u8282\u70B9\uFF08\u4FDD\u7559\u5B50\u8282\u70B9\uFF09",
    "app.command.mindmap.expandAllDescendants": "\u5C55\u5F00\u6240\u6709\u540E\u4EE3",
    "app.command.mindmap.collapseAllDescendants": "\u6298\u53E0\u6240\u6709\u540E\u4EE3",
    "app.command.mindmap.zoomIn": "\u653E\u5927",
    "app.command.mindmap.zoomOut": "\u7F29\u5C0F",
    "app.command.mindmap.zoomTo": "\u7F29\u653E\u5230",
    "app.command.mindmap.resetZoom": "\u91CD\u7F6E\u7F29\u653E",
    "app.command.mindmap.panTo": "\u5E73\u79FB\u5230",
    "app.command.mindmap.panToFirstRoot": "\u56DE\u5230\u7B2C\u4E00\u4E2A\u6839\u8282\u70B9",
    "app.command.mindmap.fitView": "\u9002\u914D\u89C6\u56FE",
    "app.command.mindmap.summary.create": "\u6982\u8981",
    "app.command.mindmap.relation.start": "\u5173\u8054\u7EBF",
    "app.command.mindmap.relation.setLabel": "\u8BBE\u7F6E\u5173\u8054\u7EBF\u6807\u7B7E",
    "app.command.mindmap.relation.setStyle": "\u8BBE\u7F6E\u5173\u8054\u7EBF\u6837\u5F0F",
    "app.command.mindmap.relation.setDirection": "\u8BBE\u7F6E\u5173\u8054\u7EBF\u65B9\u5411",
    "app.command.mindmap.relation.resetStyle": "\u91CD\u7F6E\u5173\u8054\u7EBF\u6837\u5F0F",
    "app.command.mindmap.relation.resetCurve": "\u91CD\u7F6E\u5173\u8054\u7EBF\u66F2\u7EBF",
    "app.command.mindmap.relation.setPorts": "\u8BBE\u7F6E\u5173\u8054\u7EBF\u8FDE\u63A5\u70B9",
    "app.toolbar.mindmap.relation.panel": "\u5173\u8054\u7EBF\u7F16\u8F91",
    "app.command.nodeLink.open": "\u6253\u5F00\u8282\u70B9\u94FE\u63A5",
    "app.command.nodeLink.copy": "\u590D\u5236\u8282\u70B9\u94FE\u63A5",
    "app.command.nodeLink.refreshBacklinks": "\u5237\u65B0\u53CD\u94FE",
    "app.command.trash.restore": "\u4ECE\u56DE\u6536\u7AD9\u6062\u590D",
    "app.command.trash.empty": "\u6E05\u7A7A\u56DE\u6536\u7AD9",
    "app.trash.empty.confirm": "\u786E\u5B9A\u6E05\u7A7A\u56DE\u6536\u7AD9\u5417\uFF1F\u8BE5\u64CD\u4F5C\u65E0\u6CD5\u64A4\u9500\u3002",
    "app.toolbar.trash.title": "\u56DE\u6536\u7AD9",
    "app.toolbar.trash.empty": "\u6E05\u7A7A\u56DE\u6536\u7AD9",
    "app.toolbar.trash.restore": "\u6062\u590D\uFF1A{title}",
    "app.import.error.pngMissingPayload": "\u8BE5 PNG \u4E0D\u5305\u542B KMind \u6570\u636E\u5305\uFF1B\u8BF7\u5BFC\u51FA *.kmindz.png \u6216 *.kmindz.zip\u3002",
    "app.import.error.svgMissingPayload": "\u8BE5 SVG \u4E0D\u5305\u542B KMind \u6570\u636E\u5305\uFF1B\u8BF7\u5BFC\u51FA *.kmindz / *.kmindz.svg / *.kmindz.zip\u3002",
    "app.import.error.unsupportedFileType": "\u4E0D\u652F\u6301\u7684\u6587\u4EF6\u7C7B\u578B\u3002\u8BF7\u5BFC\u5165 *.kmindz / *.kmindz.zip / *.kmindz.png / *.kmindz.svg / *.xmind / *.kmind / *.json\u3002",
    "app.import.error.generic": "\u5BFC\u5165\u5931\u8D25\u3002",
    "app.import.error.xmindEncrypted": "\u8BE5 XMind \u6587\u4EF6\u5DF2\u52A0\u5BC6\uFF0C\u6682\u65F6\u65E0\u6CD5\u5BFC\u5165\u3002",
    "app.import.error.xmindInvalidFile": "\u8BE5 XMind \u6587\u4EF6\u65E0\u6548\u6216\u5DF2\u635F\u574F\u3002",
    "app.import.error.xmindMissingContentJson": "\u8BE5 XMind \u6587\u4EF6\u4E0D\u5305\u542B content.json\u3002",
    "app.import.error.xmindUnsupportedXml": "\u8BE5 XMind \u6587\u4EF6\u4F7F\u7528\u65E7\u7248 content.xml \u683C\u5F0F\uFF0C\u672C\u9636\u6BB5\u6682\u4E0D\u652F\u6301\u3002",
    "app.import.error.xmindUnsupportedZipCompression": "\u8BE5 XMind \u6587\u4EF6\u4F7F\u7528\u4E86\u6682\u4E0D\u652F\u6301\u7684 zip \u538B\u7F29\u65B9\u5F0F\u3002",
    "app.dialog.import.confirm.replaceProject": "\u5BFC\u5165\u5230\u5F53\u524D\u5BFC\u56FE\u5DE5\u7A0B\uFF1F\u8FD9\u4F1A\u8986\u76D6\u5F53\u524D\u5DE5\u7A0B\u4E2D\u7684\u5BFC\u56FE\u3001\u5B50\u56FE\u4E0E\u8D44\u6E90\u3002",
    "app.dialog.import.confirm.replaceCurrentMap": "\u8FD9\u4F1A\u66FF\u6362\u5F53\u524D\u5BFC\u56FE\uFF0C\u662F\u5426\u7EE7\u7EED\uFF1F",
    "app.dialog.import.markdown.empty": "\u8BF7\u5148\u7C98\u8D34 Markdown \u6807\u9898\u5185\u5BB9\u3002",
    "app.import.preflight.title": "\u517C\u5BB9\u6027\u68C0\u67E5",
    "app.import.preflight.summary": "\u8BE5\u5916\u90E8\u5BFC\u5165\u4F1A\u4E22\u5F03\u6216\u6539\u5199 {count} \u5904\u4E0D\u517C\u5BB9\u5185\u5BB9\uFF0C\u6D89\u53CA {categories} \u7C7B\u95EE\u9898\uFF1A",
    "app.import.preflight.confirmContinue": "\u4ECD\u8981\u7EE7\u7EED\u5BFC\u5165\u5417\uFF1F",
    "app.import.preflight.issue.dropUnderline": "\u4E0B\u5212\u7EBF\u6837\u5F0F\u5C06\u88AB\u4E22\u5F03\uFF1A{count} \u5904",
    "app.import.preflight.issue.dropTextAlign": "\u6587\u672C\u5BF9\u9F50\u6837\u5F0F\u5C06\u88AB\u4E22\u5F03\uFF1A{count} \u5904",
    "app.import.preflight.issue.dropInlineImage": "\u5185\u8054\u56FE\u7247\u5C06\u88AB\u6539\u5199\u4E3A\u6587\u672C\u5360\u4F4D\uFF1A{count} \u5904",
    "app.import.preflight.issue.dropUnsupportedTag": "\u4E0D\u652F\u6301\u7684 HTML \u6807\u7B7E\u5C06\u88AB\u4E22\u5F03\uFF1A{count} \u5904",
    "app.import.preflight.issue.dropUnsupportedStyle": "\u4E0D\u652F\u6301\u7684\u5BCC\u6587\u672C\u6837\u5F0F\u5C06\u88AB\u4E22\u5F03\uFF1A{count} \u5904",
    "app.import.preflight.issue.sanitizeUnsafeLink": "\u4E0D\u5B89\u5168\u6216\u65E0\u6548\u7684\u94FE\u63A5\u5C06\u88AB\u4E22\u5F03\uFF1A{count} \u5904",
    "app.import.preflight.issue.dropXmindMarker": "\u6682\u4E0D\u652F\u6301\u7684 XMind marker \u5C06\u88AB\u4E22\u5F03\uFF1A{count} \u5904",
    "app.import.preflight.issue.dropXmindBoundary": "\u6682\u4E0D\u652F\u6301\u7684 XMind boundary \u5C06\u88AB\u4E22\u5F03\uFF1A{count} \u5904",
    "app.import.preflight.issue.dropXmindAttachment": "\u6682\u4E0D\u652F\u6301\u7684 XMind attachment \u5C06\u88AB\u4E22\u5F03\uFF1A{count} \u5904",
    "app.import.preflight.issue.dropXmindCallout": "\u6682\u4E0D\u652F\u6301\u7684 XMind callout \u5C06\u88AB\u4E22\u5F03\uFF1A{count} \u5904",
    "app.import.preflight.issue.dropXmindRemoteImage": "\u8FDC\u7A0B\u6216\u4E0D\u652F\u6301\u7684 XMind \u56FE\u7247\u5C06\u88AB\u4E22\u5F03\uFF1A{count} \u5904",
    "app.import.preflight.issue.dropXmindRelationship": "\u7AEF\u70B9\u65E0\u6CD5\u89E3\u6790\u7684 XMind relationship \u5C06\u88AB\u4E22\u5F03\uFF1A{count} \u5904",
    "app.import.preflight.issue.dropXmindSummary": "\u8303\u56F4\u65E0\u6CD5\u89E3\u6790\u7684 XMind summary \u5C06\u88AB\u4E22\u5F03\uFF1A{count} \u5904",
    "app.documentZip.importFail.missingManifest": "\u5BFC\u5165\u5931\u8D25\uFF1Azip \u7F3A\u5C11 manifest.json\u3002",
    "app.documentZip.importFail.unsupportedVersion": "\u5BFC\u5165\u5931\u8D25\uFF1A\u4E0D\u652F\u6301\u7684\u6587\u6863\u5305\u7248\u672C\u3002",
    "app.documentZip.importFail.missingDocFile": "\u5BFC\u5165\u5931\u8D25\uFF1A\u7F3A\u5C11\u6587\u6863\u6587\u4EF6 {path}",
    "app.documentZip.importFail.missingRootDoc": "\u5BFC\u5165\u5931\u8D25\uFF1A\u6587\u6863\u5305\u7F3A\u5C11 rootDocId \u5BF9\u5E94\u7684\u6587\u6863\u3002",
    "app.documentZip.importFail.missingLegacyDocJson": "\u5BFC\u5165\u5931\u8D25\uFF1Azip \u7F3A\u5C11 doc.json\uFF08\u65E7\u683C\u5F0F\uFF09\u3002",
    "app.documentZip.importFail.unresolvedRootDocId": "\u5BFC\u5165\u5931\u8D25\uFF1A\u65E0\u6CD5\u89E3\u6790 rootDocId\u3002",
    "app.documentZip.importFail.missingAssetFile": "\u5BFC\u5165\u5931\u8D25\uFF1A\u7F3A\u5C11\u8D44\u4EA7\u6587\u4EF6 {path}",
    "app.documentZip.importFail.missingSubmapDoc": '\u5BFC\u5165\u5931\u8D25\uFF1A\u6587\u6863\u5305\u7F3A\u5C11\u5B50\u5BFC\u56FE\u6587\u6863 "{subId}"\u3002',
    "app.host.clipboardUnavailableCopy": "\u5F53\u524D\u5BBF\u4E3B\u672A\u63D0\u4F9B clipboard port\uFF0C\u65E0\u6CD5\u590D\u5236\u3002",
    "app.host.clipboardUnavailablePaste": "\u5F53\u524D\u5BBF\u4E3B\u672A\u63D0\u4F9B clipboard port\uFF0C\u65E0\u6CD5\u7C98\u8D34\u3002",
    "app.host.clipboardReadFailed": "\u8BFB\u53D6\u526A\u8D34\u677F\u5931\u8D25\uFF08\u9700\u8981\u7528\u6237\u6388\u6743\uFF09\u3002",
    "app.host.clipboardWriteFailed": "\u590D\u5236\u5931\u8D25\uFF08\u526A\u8D34\u677F\u53EF\u80FD\u88AB\u6743\u9650\u62E6\u622A\uFF09\u3002",
    "app.host.clipboardWritePngFailed": "\u590D\u5236 PNG \u5931\u8D25\uFF08\u526A\u8D34\u677F\u53EF\u80FD\u88AB\u6743\u9650\u62E6\u622A\uFF09\u3002",
    "app.host.filesDownloadUnsupported": "\u5F53\u524D\u5BBF\u4E3B\u4E0D\u652F\u6301\u5BFC\u51FA\u6587\u4EF6\u3002",
    "app.host.filesOpenUnsupported": "\u5F53\u524D\u5BBF\u4E3B\u4E0D\u652F\u6301\u9009\u62E9\u5BFC\u5165\u6587\u4EF6\u3002",
    "app.host.assetsUnsupportedForImport": "\u5F53\u524D\u5BBF\u4E3B\u4E0D\u652F\u6301\u8D44\u4EA7\u5B58\u50A8\uFF0C\u65E0\u6CD5\u5BFC\u5165\u5305\u542B\u56FE\u7247\u7684\u6587\u6863\u5305\u3002",
    "app.export.pngFallbackFast": "PNG \u5BFC\u51FA\u5DF2\u56DE\u9000\u5230 fast\uFF08\u53EF\u80FD\u4E0D\u5305\u542B\u5BCC\u6587\u672C/\u56FE\u7247\u7B49\uFF09\u3002",
    "app.export.error.generic": "\u5BFC\u51FA\u5931\u8D25\u3002",
    "app.clipboard.subtree.invalidPayload": "\u526A\u8D34\u677F\u5185\u5BB9\u4E0D\u662F KMind \u5B50\u6811\u6570\u636E\u3002",
    "app.clipboard.subtree.invalidJson": "\u89E3\u6790\u526A\u8D34\u677F\u5931\u8D25\uFF08\u5185\u5BB9\u4E0D\u662F JSON\uFF09\u3002",
    "app.trash.restoreFailed.idConflict": "\u6062\u590D\u5931\u8D25\uFF1A\u6587\u6863 ID \u51B2\u7A81\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002",
    "app.submap.missingOrDeleted": "\u5B50\u5BFC\u56FE\u4E0D\u5B58\u5728\u6216\u5DF2\u88AB\u5220\u9664\u3002",
    "app.submap.targetNotReachable": "\u76EE\u6807\u5BFC\u56FE\u4E0D\u5728\u5F53\u524D project \u7684\u53EF\u8FBE\u8303\u56F4\u5185\u3002",
    "app.submap.targetMissingOrDeleted": "\u76EE\u6807\u5BFC\u56FE\u4E0D\u5B58\u5728\u6216\u5DF2\u88AB\u5220\u9664\u3002",
    "app.submap.defaultTitle": "\u5B50\u5BFC\u56FE",
    "app.command.submap.open": "\u6253\u5F00\u5B50\u5BFC\u56FE",
    "app.command.submap.createAndEnter": "\u521B\u5EFA\u5E76\u8FDB\u5165\u5B50\u5BFC\u56FE",
    "app.command.submap.enter": "\u8FDB\u5165\u5B50\u5BFC\u56FE",
    "app.command.submap.back": "\u8FD4\u56DE\u4E0A\u5C42\u5BFC\u56FE",
    "app.command.submap.resetToRoot": "\u56DE\u5230\u4E3B\u5BFC\u56FE",
    "app.command.submap.popTo": "\u8FD4\u56DE\u5230\u6307\u5B9A\u5BFC\u56FE",
    "app.command.submap.navigateTo": "\u8DF3\u8F6C\u5230\u5BFC\u56FE",
    "app.command.submap.rename": "\u91CD\u547D\u540D\u5BFC\u56FE",
    "app.command.submap.delete": "\u5220\u9664\u5BFC\u56FE",
    "app.toolbar.submap.open": "\u5B50\u5BFC\u56FE",
    "app.toolbar.submap.back": "\u8FD4\u56DE",
    "app.dialog.submap.delete.confirm": "\u786E\u5B9A\u5220\u9664\u5BFC\u56FE\u300C{title}\u300D\u5417\uFF1F\u8BE5\u64CD\u4F5C\u4E0D\u53EF\u64A4\u9500\u3002",
    "app.theme.unknownPreset": "\u672A\u77E5\u4E3B\u9898 preset\u3002",
    "app.theme.invalidPackage": "\u4E3B\u9898\u5305\u65E0\u6548\u3002",
    "app.themeDesigner.title": "\u4E3B\u9898\u8BBE\u8BA1\u5668",
    "app.themeDesigner.aria.preset": "\u5185\u7F6E\u4E3B\u9898\u6A21\u677F",
    "app.themeDesigner.aria.previewCanvas": "\u4E3B\u9898\u9884\u89C8\u753B\u5E03",
    "app.themeDesigner.preview.root": "KMind Zen\n\u4E3B\u9898\u8BBE\u8BA1\u5668",
    "app.themeDesigner.preview.design": "\u8BBE\u8BA1",
    "app.themeDesigner.preview.colors": "\u989C\u8272",
    "app.themeDesigner.preview.typography": "\u5B57\u4F53",
    "app.themeDesigner.preview.shapes": "\u5F62\u72B6",
    "app.themeDesigner.preview.layout": "\u5E03\u5C40",
    "app.themeDesigner.preview.edges": "\u8FDE\u7EBF",
    "app.themeDesigner.preview.cubic": "\u8D1D\u585E\u5C14",
    "app.themeDesigner.preview.orthogonal": "\u6B63\u4EA4",
    "app.themeDesigner.preview.tapered": "\u9525\u5F62",
    "app.themeDesigner.preview.baseline": "\u57FA\u7EBF\u5206\u53C9",
    "app.themeDesigner.preview.rules": "\u89C4\u5219",
    "app.themeDesigner.preview.depth": "\u6309\u5C42\u7EA7",
    "app.themeDesigner.preview.range": "\u6309\u8303\u56F4",
    "app.themeDesigner.preview.conditions": "\u6761\u4EF6",
    "app.themeDesigner.preview.overrides": "\u8986\u76D6",
    "app.themeDesigner.preview.export": "\u5BFC\u51FA",
    "app.themeDesigner.preview.image": "\u56FE\u7247",
    "app.themeDesigner.preview.themeFile": "\u4E3B\u9898\u6587\u4EF6",
    "app.themeDesigner.preview.import": "\u5BFC\u5165",
    "app.themeDesigner.preview.plugin": "\u63D2\u4EF6",
    "app.themeDesigner.preview.level3Plus": "\u4E09\u7EA7\u53CA\u4EE5\u540E",
    "app.themeDesigner.preview.summaryEdges": "\u7EBF\u578B\u96C6\u5408",
    "app.themeDesigner.preview.summaryEdgeExamples": "\u8FDE\u7EBF\u793A\u4F8B",
    "app.themeDesigner.preview.relationDefaults": "\u5171\u4EAB\u9ED8\u8BA4\u914D\u7F6E",
    "app.themeDesigner.variant.light": "\u6D45\u8272",
    "app.themeDesigner.variant.dark": "\u6DF1\u8272",
    "app.themeDesigner.action.saveTheme": "\u4FDD\u5B58\u4E3B\u9898",
    "app.themeDesigner.action.saveDraft": "\u4FDD\u5B58\u8349\u7A3F",
    "app.themeDesigner.action.shareTheme": "\u5206\u4EAB\u4E3B\u9898",
    "app.themeDesigner.action.submitReview": "\u63D0\u4EA4\u5BA1\u6838",
    "app.themeDesigner.action.applyToMap": "\u5E94\u7528\u5230\u5BFC\u56FE",
    "app.themeDesigner.action.importThemePackage": "\u5BFC\u5165\u4E3B\u9898\u5305",
    "app.themeDesigner.action.exportThemePackage": "\u5BFC\u51FA\u4E3B\u9898\u5305",
    "app.themeDesigner.action.import": "\u5BFC\u5165",
    "app.themeDesigner.status.fixBeforeSave": "\u8BF7\u5148\u4FEE\u590D\u6821\u9A8C\u95EE\u9898\uFF0C\u518D\u4FDD\u5B58\u4E3B\u9898\u3002",
    "app.themeDesigner.status.fixBeforeApply": "\u8BF7\u5148\u4FEE\u590D\u6821\u9A8C\u95EE\u9898\uFF0C\u518D\u5E94\u7528\u5230\u5BFC\u56FE\u3002",
    "app.themeDesigner.status.fixBeforeShare": "\u8BF7\u5148\u4FEE\u590D\u6821\u9A8C\u95EE\u9898\uFF0C\u518D\u5206\u4EAB\u4E3B\u9898\u3002",
    "app.themeDesigner.status.saved": "\u4E3B\u9898\u5DF2\u4FDD\u5B58\u3002",
    "app.themeDesigner.status.saveFailed": "\u4E3B\u9898\u4FDD\u5B58\u5931\u8D25\u3002",
    "app.themeDesigner.status.loadDraftFailed": "\u4E3B\u9898\u8349\u7A3F\u52A0\u8F7D\u5931\u8D25\u3002",
    "app.themeDesigner.status.applied": "\u5DF2\u5E94\u7528\u5230\u5BFC\u56FE\u3002",
    "app.themeDesigner.status.applyFailed": "\u4E3B\u9898\u5E94\u7528\u5931\u8D25\u3002",
    "app.themeDesigner.status.shareSubmitted": "\u5DF2\u63D0\u4EA4\u5206\u4EAB\u4E2D\u5FC3\u5BA1\u6838\u3002",
    "app.themeDesigner.status.shareNamedSubmitted": "\u5DF2\u63D0\u4EA4\u300C{name}\u300D\u5230\u5206\u4EAB\u4E2D\u5FC3\u5BA1\u6838\u3002",
    "app.themeDesigner.status.shareFailed": "\u4E3B\u9898\u5206\u4EAB\u5931\u8D25\u3002",
    "app.themeDesigner.status.exported": "\u4E3B\u9898\u5DF2\u5BFC\u51FA\u3002",
    "app.themeDesigner.status.exportFailed": "\u4E3B\u9898\u5BFC\u51FA\u5931\u8D25\u3002",
    "app.themeDesigner.status.presetSwitched": "\u5DF2\u5207\u6362\u5230\u300C{name}\u300D\u6A21\u677F\u3002",
    "app.themeDesigner.status.localLoaded": "\u5DF2\u52A0\u8F7D\u300C{name}\u300D\u3002",
    "app.themeDesigner.status.renamed": "\u4E3B\u9898\u5DF2\u91CD\u547D\u540D\u3002",
    "app.themeDesigner.status.renameFailed": "\u4E3B\u9898\u91CD\u547D\u540D\u5931\u8D25\u3002",
    "app.themeDesigner.status.duplicated": "\u5DF2\u590D\u5236\u4E3A\u300C{name}\u300D\u3002",
    "app.themeDesigner.status.duplicateFailed": "\u4E3B\u9898\u590D\u5236\u5931\u8D25\u3002",
    "app.themeDesigner.status.deleted": "\u672C\u5730\u4E3B\u9898\u5DF2\u5220\u9664\u3002",
    "app.themeDesigner.status.deleteFailed": "\u672C\u5730\u4E3B\u9898\u5220\u9664\u5931\u8D25\u3002",
    "app.themeDesigner.status.imported": "\u5DF2\u5BFC\u5165\u300C{name}\u300D\u3002",
    "app.themeDesigner.status.importFailed": "\u4E3B\u9898\u5BFC\u5165\u5931\u8D25\u3002",
    "app.themeDesigner.status.draftImported": "\u5DF2\u5BFC\u5165\u300C{name}\u300D\u5230\u5F53\u524D\u7F16\u8F91\u8349\u7A3F\u3002",
    "app.themeDesigner.error.invalidSharePackage": "\u4E3B\u9898\u5206\u4EAB\u5305\u683C\u5F0F\u4E0D\u6B63\u786E\u3002",
    "app.themeDesigner.confirm.dirtyPreset": "\u5F53\u524D\u4E3B\u9898\u5DF2\u6709\u672A\u4FDD\u5B58\u4FEE\u6539\uFF0C\u5207\u6362\u5185\u7F6E\u4E3B\u9898\u4F1A\u4E22\u5931\u8FD9\u4E9B\u4FEE\u6539\u3002\u662F\u5426\u7EE7\u7EED\uFF1F",
    "app.themeDesigner.confirm.dirtyLocal": "\u5F53\u524D\u4E3B\u9898\u5DF2\u6709\u672A\u4FDD\u5B58\u4FEE\u6539\uFF0C\u52A0\u8F7D\u672C\u5730\u4E3B\u9898\u4F1A\u4E22\u5931\u8FD9\u4E9B\u4FEE\u6539\u3002\u662F\u5426\u7EE7\u7EED\uFF1F",
    "app.themeDesigner.confirm.deleteLocal": "\u5220\u9664\u672C\u5730\u4E3B\u9898\u300C{name}\u300D\uFF1F\u5DF2\u5E94\u7528\u5230\u5BFC\u56FE\u91CC\u7684 inline theme \u4E0D\u4F1A\u88AB\u4FEE\u6539\u3002",
    "app.themeDesigner.confirm.dirtyImportDraft": "\u5F53\u524D\u4E3B\u9898\u5DF2\u6709\u672A\u4FDD\u5B58\u4FEE\u6539\uFF0C\u5BFC\u5165\u4E3B\u9898\u5305\u4F1A\u66FF\u6362\u5F53\u524D\u7F16\u8F91\u8349\u7A3F\u3002\u662F\u5426\u7EE7\u7EED\uFF1F",
    "app.themeDesigner.web.shareConfirm": "\u786E\u8BA4\u5C06\u5F53\u524D\u4E3B\u9898\u8349\u7A3F\u63D0\u4EA4\u5230\u5206\u4EAB\u4E2D\u5FC3\u5BA1\u6838\uFF1F\u5982\u679C\u8BE5\u4E3B\u9898\u5DF2\u7ECF\u5206\u4EAB\u8FC7\uFF0C\u672A\u53D1\u5E03\u524D\u4F1A\u66F4\u65B0\u540C\u4E00\u6761\u5BA1\u6838\u5185\u5BB9\uFF1B\u5DF2\u53D1\u5E03\u540E\u4F1A\u63D0\u4EA4\u4E00\u4E2A\u65B0\u7248\u672C\uFF0C\u5BA1\u6838\u901A\u8FC7\u540E\u518D\u66FF\u6362\u516C\u5F00\u7248\u672C\u3002",
    "app.themeDesigner.info.title": "\u4E3B\u9898\u4FE1\u606F",
    "app.themeDesigner.info.status.filled": "\u5DF2\u586B\u5199",
    "app.themeDesigner.info.status.nameRequired": "\u540D\u79F0\u5FC5\u586B",
    "app.themeDesigner.info.name": "\u540D\u79F0",
    "app.themeDesigner.info.description": "\u63CF\u8FF0",
    "app.themeDesigner.info.tags": "\u6807\u7B7E",
    "app.themeDesigner.info.tags.placeholder": "\u6781\u7B80\uFF0C\u6DF1\u8272\uFF0C\u5546\u52A1",
    "app.themeDesigner.info.tags.hint": "Enter \u6216\u9017\u53F7\u786E\u8BA4\uFF0C\u6700\u591A 12 \u4E2A\u6807\u7B7E\u3002",
    "app.themeDesigner.info.tags.remove": "\u79FB\u9664\u6807\u7B7E {tag}",
    "app.themeDesigner.library.title": "\u672C\u5730\u4E3B\u9898\u5E93",
    "app.themeDesigner.library.subtitle": "\u63D2\u4EF6\u7EA7\u4E3B\u9898\u8D44\u4EA7\uFF0C\u53EF\u8DE8\u5BFC\u56FE\u590D\u7528\u3002",
    "app.themeDesigner.library.storageUnavailable": "\u5F53\u524D\u5BBF\u4E3B\u672A\u63D0\u4F9B\u4E3B\u9898\u5E93\u50A8\u5B58\u7AEF\u53E3\u3002",
    "app.themeDesigner.library.empty": "\u6682\u65E0\u672C\u5730\u4E3B\u9898\u3002\u4FDD\u5B58\u5F53\u524D\u4E3B\u9898\u540E\u4F1A\u51FA\u73B0\u5728\u8FD9\u91CC\u3002",
    "app.themeDesigner.library.renameAria": "\u4E3B\u9898\u540D\u79F0",
    "app.themeDesigner.library.action.saveName": "\u4FDD\u5B58\u540D\u79F0",
    "app.themeDesigner.library.action.cancel": "\u53D6\u6D88",
    "app.themeDesigner.library.action.load": "\u52A0\u8F7D",
    "app.themeDesigner.library.action.apply": "\u5E94\u7528",
    "app.themeDesigner.library.action.shareOnline": "\u5728\u7EBF\u5206\u4EAB",
    "app.themeDesigner.library.action.rename": "\u91CD\u547D\u540D",
    "app.themeDesigner.library.action.duplicate": "\u590D\u5236",
    "app.themeDesigner.library.action.export": "\u5BFC\u51FA",
    "app.themeDesigner.library.action.delete": "\u5220\u9664",
    "app.themeDesigner.library.source.imported": "\u5BFC\u5165",
    "app.themeDesigner.library.source.installed": "\u5B89\u88C5",
    "app.themeDesigner.library.source.official": "\u5B98\u65B9",
    "app.themeDesigner.library.source.local": "\u672C\u5730",
    "app.themeDesigner.library.updatedAt.missing": "\u672A\u8BB0\u5F55",
    "app.themeDesigner.library.updatedAt.fallback": "\u5DF2\u66F4\u65B0",
    "app.themeDesigner.validation.title": "\u4E3B\u9898\u6821\u9A8C",
    "app.themeDesigner.validation.ready": "\u53EF\u4FDD\u5B58",
    "app.themeDesigner.validation.issueCount": "{count} \u4E2A\u95EE\u9898",
    "app.themeDesigner.validation.invalidColor": "{path}: \u989C\u8272\u683C\u5F0F\u4E0D\u53D7\u652F\u6301",
    "app.themeDesigner.validation.invalidRoute": "{path}: \u8FDE\u7EBF\u7C7B\u578B\u4E0D\u53D7\u652F\u6301",
    "app.themeDesigner.validation.invalidNumber": "{path}: \u6570\u503C\u8D85\u51FA\u652F\u6301\u8303\u56F4",
    "app.themeDesigner.validation.invalidSelector": "{path}: \u8282\u70B9\u5339\u914D\u89C4\u5219\u4E0D\u53D7\u652F\u6301",
    "app.themeDesigner.validation.invalidTheme": "{path}: \u4E3B\u9898\u7ED3\u6784\u4E0D\u5B8C\u6574",
    "app.themeDesigner.validation.invalidPackage": "{path}: \u4E3B\u9898\u5305\u683C\u5F0F\u4E0D\u6B63\u786E",
    "app.themeDesigner.level.root": "\u6839\u8282\u70B9",
    "app.themeDesigner.level.level1": "\u4E00\u7EA7\u8282\u70B9",
    "app.themeDesigner.level.level2": "\u4E8C\u7EA7\u8282\u70B9",
    "app.themeDesigner.level.level3Plus": "\u4E09\u7EA7\u53CA\u4EE5\u540E",
    "app.themeDesigner.inspector.sectionTitle": "{level}\u6837\u5F0F",
    "app.themeDesigner.inspector.nodeFallback": "\u8282\u70B9",
    "app.themeDesigner.field.nodeFill": "\u586B\u5145\u8272",
    "app.themeDesigner.field.nodeFill.tooltip": "\u5F53\u524D\u5C42\u7EA7\u8282\u70B9\u7684\u586B\u5145\u989C\u8272",
    "app.themeDesigner.field.text": "\u6587\u5B57\u8272",
    "app.themeDesigner.field.text.tooltip": "\u5F53\u524D\u5C42\u7EA7\u8282\u70B9\u7684\u6587\u5B57\u989C\u8272",
    "app.themeDesigner.field.nodeStroke": "\u63CF\u8FB9\u8272",
    "app.themeDesigner.field.nodeStroke.tooltip": "\u5F53\u524D\u5C42\u7EA7\u8282\u70B9\u7684\u8FB9\u6846\u989C\u8272",
    "app.themeDesigner.field.strokeWidth": "\u63CF\u8FB9\u5BBD\u5EA6",
    "app.themeDesigner.field.strokeWidth.tooltip": "\u5F53\u524D\u5C42\u7EA7\u8282\u70B9\u7684\u8FB9\u6846\u5BBD\u5EA6\uFF1B\u8BBE\u7F6E\u4E3A 0 \u8868\u793A\u4E0D\u663E\u793A\u8282\u70B9\u63CF\u8FB9",
    "app.themeDesigner.field.radius": "\u5706\u89D2",
    "app.themeDesigner.field.radius.tooltip": "\u4E3B\u9898\u8BBE\u8BA1\u5668\u5F53\u524D\u56FA\u5B9A\u4F7F\u7528\u5706\u89D2\u77E9\u5F62\uFF1B\u8FD9\u91CC\u8C03\u6574\u5706\u89D2\u534A\u5F84",
    "app.themeDesigner.field.fontFamily": "\u5B57\u4F53",
    "app.themeDesigner.field.fontFamily.tooltip": "\u5F53\u524D\u5C42\u7EA7\u8282\u70B9\u4F7F\u7528\u7684\u5B57\u4F53\u65CF",
    "app.themeDesigner.field.fontSize": "\u5B57\u53F7",
    "app.themeDesigner.field.fontSize.tooltip": "\u5F53\u524D\u5C42\u7EA7\u8282\u70B9\u7684\u6587\u5B57\u5927\u5C0F",
    "app.themeDesigner.field.fontWeight": "\u5B57\u91CD",
    "app.themeDesigner.field.fontWeight.tooltip": "\u5F53\u524D\u5C42\u7EA7\u8282\u70B9\u7684\u6587\u5B57\u7C97\u7EC6",
    "app.themeDesigner.field.textAlign": "\u5BF9\u9F50",
    "app.themeDesigner.field.textAlign.tooltip": "\u5F53\u524D\u5C42\u7EA7\u8282\u70B9\u7684\u6587\u5B57\u5BF9\u9F50\u65B9\u5F0F",
    "app.themeDesigner.option.align.left": "\u5DE6\u5BF9\u9F50",
    "app.themeDesigner.option.align.center": "\u5C45\u4E2D",
    "app.themeDesigner.option.align.right": "\u53F3\u5BF9\u9F50",
    "app.themeDesigner.edge.title": "\u5165\u8FB9\u6837\u5F0F",
    "app.themeDesigner.field.edgeRoute": "\u7EBF\u578B",
    "app.themeDesigner.field.edgeRoute.tooltip": "\u7236\u8282\u70B9\u8FDE\u63A5\u5230\u5F53\u524D\u5C42\u7EA7\u8282\u70B9\u7684\u8FDE\u7EBF\u65B9\u5F0F",
    "app.themeDesigner.field.edgeColor": "\u989C\u8272",
    "app.themeDesigner.field.edgeColor.tooltip": "\u5165\u8FB9\u7684\u7EBF\u6761\u989C\u8272",
    "app.themeDesigner.field.edgeWidth": "\u7EBF\u5BBD",
    "app.themeDesigner.field.edgeWidth.tooltip": "\u5165\u8FB9\u7684\u7EBF\u6761\u5BBD\u5EA6",
    "app.themeDesigner.field.edgeDash": "\u865A\u7EBF",
    "app.themeDesigner.field.edgeDash.tooltip": "\u5165\u8FB9\u7684\u865A\u7EBF\u6837\u5F0F",
    "app.themeDesigner.global.title": "\u5168\u5C40\u6837\u5F0F",
    "app.themeDesigner.field.relationColor": "\u5173\u8054\u7EBF\u989C\u8272",
    "app.themeDesigner.field.relationColor.tooltip": "\u5168\u5C40\u5173\u8054\u7EBF\u7684\u7EBF\u6761\u989C\u8272",
    "app.themeDesigner.field.relationWidth": "\u5173\u8054\u7EBF\u5BBD",
    "app.themeDesigner.field.relationWidth.tooltip": "\u5168\u5C40\u5173\u8054\u7EBF\u7684\u7EBF\u6761\u5BBD\u5EA6",
    "app.themeDesigner.field.relationDash": "\u5173\u8054\u7EBF\u865A\u7EBF",
    "app.themeDesigner.field.relationDash.tooltip": "\u5168\u5C40\u5173\u8054\u7EBF\u7684\u865A\u7EBF\u6837\u5F0F",
    "app.themeDesigner.field.summaryColor": "\u6982\u8981\u7EBF\u989C\u8272",
    "app.themeDesigner.field.summaryColor.tooltip": "\u6982\u8981\u62EC\u53F7\u7EBF\u7684\u7EBF\u6761\u989C\u8272",
    "app.themeDesigner.field.canvasBackground": "\u753B\u5E03\u80CC\u666F",
    "app.themeDesigner.field.canvasBackground.tooltip": "\u5F53\u524D\u660E\u6697\u6A21\u5F0F\u4E0B\u7684\u753B\u5E03\u80CC\u666F\u989C\u8272",
    "app.themeDesigner.field.rainbow": "\u5F69\u8679\u7EBF\u6761",
    "app.themeDesigner.field.rainbow.tooltip": "\u6309\u5206\u652F\u4F7F\u7528\u4E3B\u9898\u8272\u677F\u4E3A\u5B50\u7EA7\u8FDE\u7EBF\u7740\u8272",
    "app.themeDesigner.spacing.title": "\u8282\u70B9\u95F4\u8DDD",
    "app.themeDesigner.field.horizontalGap": "\u6A2A\u5411\u95F4\u8DDD",
    "app.themeDesigner.field.horizontalGap.tooltip": "\u4E0D\u540C\u5C42\u7EA7\u4E4B\u95F4\u7684\u6C34\u5E73\u8DDD\u79BB",
    "app.themeDesigner.field.verticalGap": "\u7EB5\u5411\u95F4\u8DDD",
    "app.themeDesigner.field.verticalGap.tooltip": "\u540C\u7EA7\u5144\u5F1F\u8282\u70B9\u4E4B\u95F4\u7684\u5782\u76F4\u8DDD\u79BB",
    "app.themeDesigner.dash.solid": "\u5B9E\u7EBF",
    "app.themeDesigner.dash.dashed": "\u865A\u7EBF",
    "app.themeDesigner.dash.dotted": "\u70B9\u7EBF",
    "app.themeDesigner.color.transparent": "\u900F\u660E",
    "app.themeDesigner.color.swatchAria": "{label} \u8272\u677F",
    "app.themeDesigner.edgeRoute.cubic": "\u8D1D\u585E\u5C14\u66F2\u7EBF",
    "app.themeDesigner.edgeRoute.quadratic": "\u4E8C\u6B21\u66F2\u7EBF",
    "app.themeDesigner.edgeRoute.center-quadratic": "\u4E2D\u5FC3\u5F27\u7EBF",
    "app.themeDesigner.edgeRoute.center-quadratic-tapered": "\u4E2D\u5FC3\u6E10\u7EC6\u5F27\u7EBF",
    "app.themeDesigner.edgeRoute.edge-lead-quadratic": "\u8FB9\u7F18\u5F15\u5BFC\u66F2\u7EBF",
    "app.themeDesigner.edgeRoute.edge-lead-quadratic-tapered": "\u8FB9\u7F18\u6E10\u7EC6\u66F2\u7EBF",
    "app.themeDesigner.edgeRoute.straight": "\u76F4\u7EBF",
    "app.themeDesigner.edgeRoute.orthogonal": "\u6B63\u4EA4\u6298\u7EBF",
    "app.themeDesigner.edgeRoute.orthogonal-rounded": "\u5706\u89D2\u6B63\u4EA4",
    "app.themeDesigner.edgeRoute.tapered": "\u9525\u5F62\u66F2\u7EBF",
    "app.toolbar.theme.title": "\u4E3B\u9898",
    "app.command.theme.applyPreset": "\u5E94\u7528\u4E3B\u9898\u9884\u8BBE",
    "app.command.theme.applyPackage": "\u5E94\u7528\u4E3B\u9898\u5305",
    "app.command.theme.rainbow.toggle": "\u5207\u6362\u5F69\u8679\u7EBF\u6761",
    "app.command.theme.rainbow.toggleForRoot": "\u5207\u6362 Root \u5F69\u8679\u7EBF\u6761",
    "app.command.theme.rainbow.setEnabled": "\u8BBE\u7F6E\u5F69\u8679\u7EBF\u6761\u5F00\u5173",
    "app.command.theme.relation.setProjectStyle": "\u8BBE\u7F6E\u9879\u76EE\u5173\u8054\u7EBF\u6837\u5F0F",
    "app.command.theme.relation.setRootStyle": "\u8BBE\u7F6E Root \u5173\u8054\u7EBF\u6837\u5F0F",
    "app.command.theme.edgeRoute.applyToRootSubtree": "\u5C06\u8FDE\u7EBF\u98CE\u683C\u5E94\u7528\u5230 Root \u5B50\u6811",
    "app.command.theme.edgeDasharray.applyToSubtree": "\u5C06\u865A\u7EBF\u6837\u5F0F\u5E94\u7528\u5230\u5B50\u6811",
    "app.command.theme.edgeStrokeWidth.applyToSubtree": "\u5C06\u7EBF\u5BBD\u5E94\u7528\u5230\u5B50\u6811",
    "app.command.theme.nodeOverride.merge": "\u5408\u5E76\u8282\u70B9\u4E3B\u9898\u8986\u76D6",
    "app.command.theme.nodeStyle.applyToSiblings": "\u5C06\u8282\u70B9\u6837\u5F0F\u5E94\u7528\u5230\u540C\u7EA7\u8282\u70B9",
    "app.nodeLink.targetDocMissingOrDeleted": "\u76EE\u6807\u6587\u6863\u4E0D\u5B58\u5728\u6216\u5DF2\u88AB\u5220\u9664\u3002",
    "app.nodeLink.addFailed.targetDocMissing": "\u6DFB\u52A0\u5931\u8D25\uFF1A\u76EE\u6807\u6587\u6863\u4E0D\u5B58\u5728\uFF1A{docId}",
    "app.nodeLink.addFailed.targetNodeMissing": "\u6DFB\u52A0\u5931\u8D25\uFF1A\u76EE\u6807\u8282\u70B9\u4E0D\u5B58\u5728\uFF1A{ref}",
    "app.contextMenu.canvas.panToRoot": "\u56DE\u5230\u6839\u8282\u70B9",
    "app.contextMenu.canvas.backToMainMap": "\u8FD4\u56DE\u4E3B\u5BFC\u56FE",
    "app.contextMenu.canvas.resetZoom": "\u91CD\u7F6E\u7F29\u653E\uFF08100%\uFF09",
    "app.contextMenu.canvas.newRoot": "\u65B0\u5EFA\u6839\u8282\u70B9",
    "app.contextMenu.canvas.zen.enter": "\u8FDB\u5165\u7985\u6A21\u5F0F",
    "app.contextMenu.canvas.zen.exit": "\u9000\u51FA\u7985\u6A21\u5F0F",
    "app.contextMenu.canvas.readOnly.enter": "\u8FDB\u5165\u53EA\u8BFB\u6A21\u5F0F",
    "app.contextMenu.canvas.readOnly.exit": "\u9000\u51FA\u53EA\u8BFB\u6A21\u5F0F",
    "app.contextMenu.common.copyAs": "\u590D\u5236\u4E3A",
    "app.contextMenu.common.copyAs.png": "\u56FE\u7247\uFF08PNG\uFF09",
    "app.contextMenu.common.copyAs.markdown": "Markdown",
    "app.contextMenu.common.copyAs.id": "ID",
    "app.contextMenu.common.copyImage": "\u590D\u5236\u4E3A\u56FE\u7247",
    "app.contextMenu.common.copyImage.original": "\u539F\u56FE",
    "app.contextMenu.common.copyImage.original.description": "\u6309\u5F53\u524D\u5BFC\u56FE\u6837\u5F0F\u590D\u5236\uFF0C\u4E0D\u6DFB\u52A0\u5916\u6846\u3002",
    "app.contextMenu.common.copyImage.window": "\u7A97\u53E3",
    "app.contextMenu.common.copyImage.window.description": "\u6DFB\u52A0\u7A97\u53E3\u5916\u6846\u548C\u67D4\u548C\u9634\u5F71\uFF0C\u9002\u5408\u76F4\u63A5\u5206\u4EAB\u3002",
    "app.contextMenu.node.todo.add": "\u6DFB\u52A0\u5F85\u529E",
    "app.contextMenu.node.todo.remove": "\u5220\u9664\u5F85\u529E",
    "app.contextMenu.node.notes.open": "\u5907\u6CE8",
    "app.contextMenu.node.comments.open": "\u6279\u6CE8",
    "app.contextMenu.node.copy.plainText": "\u590D\u5236\u7EAF\u6587\u672C",
    "app.contextMenu.node.copy.subtree": "\u590D\u5236\u8282\u70B9\u5B50\u6811",
    "app.contextMenu.node.paste.subtree": "\u7C98\u8D34\u8282\u70B9\u5B50\u6811",
    "app.contextMenu.node.copy.link": "\u590D\u5236\u94FE\u63A5",
    "app.contextMenu.node.submap.open": "\u4E0B\u94BB\uFF08\u5B50\u5BFC\u56FE\uFF09",
    "app.contextMenu.node.delete": "\u5220\u9664",
    "app.contextMenu.node.deleteOnly": "\u4EC5\u5220\u9664\u8282\u70B9\uFF08\u4FDD\u7559\u5B50\u8282\u70B9\uFF09",
    "app.contextMenu.node.expandAll": "\u5C55\u5F00\u6240\u6709\u540E\u4EE3",
    "app.contextMenu.node.collapseAll": "\u6298\u53E0\u6240\u6709\u540E\u4EE3"
  }
};

// ../app/src/features/document-feature.ts
init_dist();
init_src();

// ../themes/src/presets.ts
init_src();

// ../themes/src/themes/baseline-fork-ink.ts
var baselineForkInkTheme = {
  schemaVersion: 1,
  id: "kmind-baseline-fork-ink",
  name: "Baseline Fork Ink",
  description: "Heavy ink baseline branches inspired by classic skeleton mind maps.",
  variants: {
    light: {
      tokens: {
        layout: {
          fontFamily: "ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif",
          fontSize: 15,
          fontWeight: 700,
          lineHeight: 1.24,
          textAlign: "left",
          paddingX: 9,
          paddingY: 8,
          nodeMinWidth: 76,
          nodeMinHeight: 34
        },
        paint: {
          bg: "#ffffff",
          panel: "#ffffff",
          text: "#111111",
          muted: "#525252",
          border: "#d4d4d4",
          nodeFill: "transparent",
          nodeFillSelected: "rgba(37, 99, 235, 0.08)",
          nodeStroke: "transparent",
          nodeStrokeSelected: "#3749b5",
          edgeStroke: "#151515",
          relationStroke: "#737373",
          relationStrokeSelected: "#3749b5",
          summaryStroke: "#151515"
        }
      },
      background: { color: "#ffffff" },
      edges: {
        routeType: "baseline-fork",
        strokeWidth: 4,
        cap: "butt",
        join: "miter",
        routeOptions: {
          "baseline-fork": {
            lead: 16,
            baselineOffset: 7,
            diagonalAngle: 64
          }
        }
      },
      relations: {
        strokeWidth: 2,
        cap: "round",
        join: "round"
      },
      nodeShape: {
        type: "rect",
        strokeWidth: 0
      },
      rainbow: {
        enabled: false,
        palette: ["#151515", "#3749b5", "#525252", "#737373"]
      },
      rules: {
        nodeRules: [
          {
            id: "baseline-root",
            priority: 10,
            when: { kind: "depth", depth: 0 },
            apply: {
              layout: {
                fontFamily: "ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, 'Liberation Mono', monospace",
                fontSize: 26,
                fontWeight: 800,
                textAlign: "center",
                paddingX: 12,
                paddingY: 8
              },
              paint: {
                text: "#3749b5",
                nodeFill: "transparent",
                nodeStroke: "transparent"
              },
              nodeShape: {
                type: "rect",
                strokeWidth: 0
              }
            }
          },
          {
            id: "baseline-depth-1",
            priority: 10,
            when: { kind: "depth", depth: 1 },
            apply: {
              layout: { fontSize: 18, fontWeight: 760, paddingX: 10, paddingY: 8 },
              incomingEdge: { strokeColor: "#151515", strokeWidth: 4, routeType: "baseline-fork" }
            }
          },
          {
            id: "baseline-depth-2",
            priority: 10,
            when: { kind: "depth", depth: 2 },
            apply: {
              layout: { fontSize: 15, fontWeight: 700, paddingX: 9, paddingY: 7 },
              incomingEdge: { strokeColor: "#151515", strokeWidth: 4, routeType: "baseline-fork" }
            }
          },
          {
            id: "baseline-depth-3plus",
            priority: 10,
            when: { kind: "depthRange", minDepth: 3 },
            apply: {
              layout: { fontSize: 14, fontWeight: 680, paddingX: 8, paddingY: 7 },
              incomingEdge: { strokeColor: "#151515", strokeWidth: 3.5, routeType: "baseline-fork" }
            }
          }
        ]
      }
    },
    dark: {
      tokens: {
        layout: {
          fontFamily: "ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif",
          fontSize: 15,
          fontWeight: 700,
          lineHeight: 1.24,
          textAlign: "left",
          paddingX: 9,
          paddingY: 8,
          nodeMinWidth: 76,
          nodeMinHeight: 34
        },
        paint: {
          bg: "#0a0a0a",
          panel: "#111111",
          text: "#f5f5f5",
          muted: "#a3a3a3",
          border: "#404040",
          nodeFill: "transparent",
          nodeFillSelected: "rgba(147, 197, 253, 0.12)",
          nodeStroke: "transparent",
          nodeStrokeSelected: "#93a4ff",
          edgeStroke: "#f5f5f5",
          relationStroke: "#a3a3a3",
          relationStrokeSelected: "#93a4ff",
          summaryStroke: "#f5f5f5"
        }
      },
      background: { color: "#0a0a0a" },
      edges: {
        routeType: "baseline-fork",
        strokeWidth: 4,
        cap: "butt",
        join: "miter",
        routeOptions: {
          "baseline-fork": {
            lead: 16,
            baselineOffset: 7,
            diagonalAngle: 64
          }
        }
      },
      relations: {
        strokeWidth: 2,
        cap: "round",
        join: "round"
      },
      nodeShape: {
        type: "rect",
        strokeWidth: 0
      },
      rainbow: {
        enabled: false,
        palette: ["#f5f5f5", "#93a4ff", "#d4d4d4", "#a3a3a3"]
      },
      rules: {
        nodeRules: [
          {
            id: "baseline-root",
            priority: 10,
            when: { kind: "depth", depth: 0 },
            apply: {
              layout: {
                fontFamily: "ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, 'Liberation Mono', monospace",
                fontSize: 26,
                fontWeight: 800,
                textAlign: "center",
                paddingX: 12,
                paddingY: 8
              },
              paint: {
                text: "#93a4ff",
                nodeFill: "transparent",
                nodeStroke: "transparent"
              },
              nodeShape: {
                type: "rect",
                strokeWidth: 0
              }
            }
          },
          {
            id: "baseline-depth-1",
            priority: 10,
            when: { kind: "depth", depth: 1 },
            apply: {
              layout: { fontSize: 18, fontWeight: 760, paddingX: 10, paddingY: 8 },
              incomingEdge: { strokeColor: "#f5f5f5", strokeWidth: 4, routeType: "baseline-fork" }
            }
          },
          {
            id: "baseline-depth-2",
            priority: 10,
            when: { kind: "depth", depth: 2 },
            apply: {
              layout: { fontSize: 15, fontWeight: 700, paddingX: 9, paddingY: 7 },
              incomingEdge: { strokeColor: "#f5f5f5", strokeWidth: 4, routeType: "baseline-fork" }
            }
          },
          {
            id: "baseline-depth-3plus",
            priority: 10,
            when: { kind: "depthRange", minDepth: 3 },
            apply: {
              layout: { fontSize: 14, fontWeight: 680, paddingX: 8, paddingY: 7 },
              incomingEdge: { strokeColor: "#f5f5f5", strokeWidth: 3.5, routeType: "baseline-fork" }
            }
          }
        ]
      }
    }
  }
};

// ../themes/src/themes/candy-pop.ts
init_src();
function deepClone(value) {
  const clone = globalThis.structuredClone;
  if (typeof clone === "function") return clone(value);
  return JSON.parse(JSON.stringify(value));
}
var candyPopTheme = (() => {
  const theme = deepClone(createDefaultThemeDefinition());
  theme.id = "kmind-candy-pop";
  theme.name = "Candy Pop";
  theme.variants.light.tokens.paint = {
    ...theme.variants.light.tokens.paint,
    bg: "#fff1f2",
    panel: "#ffffff",
    text: "#111827",
    muted: "#6b7280",
    border: "#fecdd3",
    nodeFill: "#ffffff",
    nodeFillSelected: "rgba(236, 72, 153, 0.12)",
    nodeStroke: "#ec4899",
    nodeStrokeSelected: "#7c3aed",
    edgeStroke: "#7c3aed",
    summaryStroke: "rgba(124, 58, 237, 0.55)",
    relationStroke: "#0ea5e9",
    relationStrokeSelected: "#f97316"
  };
  theme.variants.light.nodeShape = { type: "pill", strokeWidth: 2.5 };
  theme.variants.dark.tokens.paint = {
    ...theme.variants.dark.tokens.paint,
    bg: "#0b1020",
    panel: "#0f172a",
    text: "#e5e7eb",
    muted: "#94a3b8",
    border: "rgba(148, 163, 184, 0.18)",
    nodeFill: "#0f172a",
    nodeFillSelected: "rgba(236, 72, 153, 0.18)",
    nodeStroke: "#fb7185",
    nodeStrokeSelected: "#a78bfa",
    edgeStroke: "#a78bfa",
    summaryStroke: "rgba(167, 139, 250, 0.55)",
    relationStroke: "#38bdf8",
    relationStrokeSelected: "#fb7185"
  };
  theme.variants.dark.nodeShape = { type: "pill", strokeWidth: 2.5 };
  return theme;
})();

// ../themes/src/themes/material-3.ts
init_src();
function deepClone2(value) {
  const clone = globalThis.structuredClone;
  if (typeof clone === "function") return clone(value);
  return JSON.parse(JSON.stringify(value));
}
var material3Theme = (() => {
  const theme = deepClone2(createDefaultThemeDefinition());
  theme.id = "kmind-material-3";
  theme.name = "Material 3";
  theme.variants.light.tokens.layout = {
    ...theme.variants.light.tokens.layout,
    fontFamily: "ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif",
    fontSize: 14,
    fontWeight: 450,
    lineHeight: 1.45,
    paddingX: 14,
    paddingY: 10,
    nodeMinHeight: 40
  };
  theme.variants.light.tokens.paint = {
    ...theme.variants.light.tokens.paint,
    bg: "#fef7ff",
    panel: "#ffffff",
    text: "#1c1b1f",
    muted: "#49454f",
    border: "#e7e0ec",
    nodeFill: "#f3edf7",
    nodeFillSelected: "#eaddff",
    nodeStroke: "transparent",
    nodeStrokeSelected: "#6750a4",
    edgeStroke: "#79747e",
    summaryStroke: "#cac4d0",
    relationStroke: "#7d5260",
    relationStrokeSelected: "#b3261e"
  };
  theme.variants.light.background = { color: "#fef7ff" };
  theme.variants.light.edges = { strokeWidth: 2, dasharray: "6 4", cap: "round", join: "round" };
  theme.variants.light.nodeShape = { type: "rounded-rect", radius: 16, strokeWidth: 0 };
  theme.variants.dark.tokens.layout = deepClone2(theme.variants.light.tokens.layout);
  theme.variants.dark.tokens.paint = {
    ...theme.variants.dark.tokens.paint,
    bg: "#141218",
    panel: "#1d1b20",
    text: "#e6e1e5",
    muted: "#cac4d0",
    border: "rgba(202, 196, 208, 0.22)",
    nodeFill: "#211f26",
    nodeFillSelected: "#4f378b",
    nodeStroke: "transparent",
    nodeStrokeSelected: "#d0bcff",
    edgeStroke: "#938f99",
    summaryStroke: "#49454f",
    relationStroke: "#efb8c8",
    relationStrokeSelected: "#f2b8b5"
  };
  theme.variants.dark.background = { color: "#141218" };
  theme.variants.dark.edges = deepClone2(theme.variants.light.edges);
  theme.variants.dark.nodeShape = deepClone2(theme.variants.light.nodeShape);
  const rulesLight = [
    {
      id: "m3-root",
      priority: 10,
      when: { kind: "depth", depth: 0 },
      apply: {
        layout: { textAlign: "center", fontWeight: 700, fontSize: 16, paddingX: 18, paddingY: 12 },
        paint: {
          nodeFill: "#eaddff",
          nodeFillSelected: "#d0bcff",
          text: "#21005d"
        },
        incomingEdge: { strokeColor: "#6750a4", strokeWidth: 2.5 }
      }
    },
    {
      id: "m3-depth-1",
      priority: 10,
      when: { kind: "depth", depth: 1 },
      apply: {
        layout: { fontWeight: 600 },
        paint: { nodeFill: "#e8def8", text: "#1d192b" },
        incomingEdge: { strokeColor: "#625b71" }
      }
    },
    {
      id: "m3-depth-2",
      priority: 10,
      when: { kind: "depth", depth: 2 },
      apply: {
        paint: { nodeFill: "#ffd8e4", text: "#31111d" },
        incomingEdge: { strokeColor: "#7d5260" }
      }
    },
    {
      id: "m3-depth-3plus",
      priority: 10,
      when: { kind: "depthRange", minDepth: 3 },
      apply: { incomingEdge: { strokeWidth: 1.75 } }
    }
  ];
  const rulesDark = [
    {
      id: "m3-root",
      priority: 10,
      when: { kind: "depth", depth: 0 },
      apply: {
        layout: { textAlign: "center", fontWeight: 700, fontSize: 16, paddingX: 18, paddingY: 12 },
        paint: {
          nodeFill: "#4f378b",
          nodeFillSelected: "#6750a4",
          text: "#fef7ff"
        },
        incomingEdge: { strokeColor: "#d0bcff", strokeWidth: 2.5 }
      }
    },
    {
      id: "m3-depth-1",
      priority: 10,
      when: { kind: "depth", depth: 1 },
      apply: {
        layout: { fontWeight: 600 },
        paint: { nodeFill: "#332d41", text: "#e6e1e5" },
        incomingEdge: { strokeColor: "#cbc2db" }
      }
    },
    {
      id: "m3-depth-2",
      priority: 10,
      when: { kind: "depth", depth: 2 },
      apply: {
        paint: { nodeFill: "#492532", text: "#fef7ff" },
        incomingEdge: { strokeColor: "#efb8c8" }
      }
    },
    {
      id: "m3-depth-3plus",
      priority: 10,
      when: { kind: "depthRange", minDepth: 3 },
      apply: { incomingEdge: { strokeWidth: 1.75 } }
    }
  ];
  theme.variants.light.rules = { nodeRules: rulesLight };
  theme.variants.dark.rules = { nodeRules: rulesDark };
  return theme;
})();

// ../themes/src/themes/material-3-rounded-orthogonal-aqua.ts
var material3RoundedOrthogonalAquaTheme = {
  "schemaVersion": 1,
  "id": "kmind-material-3-rounded-orthogonal-aqua",
  "name": "Material 3 \xB7 Rounded Orthogonal \xB7 Aqua",
  "variants": {
    "light": {
      "tokens": {
        "layout": {
          "fontFamily": "ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif",
          "fontSize": 14,
          "fontWeight": 450,
          "lineHeight": 1.45,
          "textAlign": "left",
          "paddingX": 14,
          "paddingY": 10,
          "nodeMinWidth": 60,
          "nodeMinHeight": 40
        },
        "paint": {
          "bg": "#f2fffd",
          "panel": "#ffffff",
          "text": "#1a1f1e",
          "muted": "#3f4947",
          "border": "#cfe7e2",
          "nodeFill": "#e8f6f2",
          "nodeFillSelected": "#b9ebe3",
          "nodeStroke": "transparent",
          "nodeStrokeSelected": "#006a60",
          "edgeStroke": "#6b7a76",
          "relationStroke": "#8f4c00",
          "relationStrokeSelected": "#ba1a1a",
          "summaryStroke": "#b7d7d1"
        }
      },
      "edges": {
        "strokeWidth": 4,
        "cap": "round",
        "join": "round",
        "routeType": "orthogonal-rounded"
      },
      "relations": {
        "strokeWidth": 2,
        "cap": "round",
        "join": "round"
      },
      "nodeShape": {
        "type": "rounded-rect",
        "radius": 16,
        "strokeWidth": 0
      },
      "rainbow": {
        "enabled": false,
        "palette": [
          "#006a60",
          "#14b8a6",
          "#06b6d4",
          "#0ea5e9",
          "#60a5fa",
          "#f59e0b",
          "#fb7185",
          "#a78bfa"
        ]
      },
      "background": {
        "color": "#f2fffd"
      },
      "rules": {
        "nodeRules": [
          {
            "id": "m3-root",
            "priority": 10,
            "when": {
              "kind": "depth",
              "depth": 0
            },
            "apply": {
              "layout": {
                "textAlign": "center",
                "fontWeight": 700,
                "fontSize": 24,
                "paddingX": 18,
                "paddingY": 12
              },
              "paint": {
                "nodeFill": "#b9ebe3",
                "nodeFillSelected": "#80d5c9",
                "text": "#00201d"
              },
              "incomingEdge": {
                "strokeColor": "#006a60",
                "strokeWidth": 2.5
              }
            }
          },
          {
            "id": "m3-depth-1",
            "priority": 10,
            "when": {
              "kind": "depth",
              "depth": 1
            },
            "apply": {
              "layout": {
                "fontWeight": 600,
                "fontSize": 18
              },
              "paint": {
                "nodeFill": "#cfe7e2",
                "text": "#10201e"
              },
              "incomingEdge": {
                "strokeColor": "#3f5f5a",
                "routeType": "center-quadratic"
              }
            }
          },
          {
            "id": "m3-depth-2",
            "priority": 10,
            "when": {
              "kind": "depth",
              "depth": 2
            },
            "apply": {
              "paint": {
                "nodeFill": "#ffddb5",
                "text": "#2b1600"
              },
              "incomingEdge": {
                "strokeColor": "#8f4c00"
              }
            }
          },
          {
            "id": "m3-depth-3plus",
            "priority": 10,
            "when": {
              "kind": "depthRange",
              "minDepth": 3
            },
            "apply": {
              "incomingEdge": {
                "strokeWidth": 1.75
              }
            }
          }
        ]
      }
    },
    "dark": {
      "tokens": {
        "layout": {
          "fontFamily": "ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif",
          "fontSize": 14,
          "fontWeight": 450,
          "lineHeight": 1.45,
          "textAlign": "left",
          "paddingX": 14,
          "paddingY": 10,
          "nodeMinWidth": 60,
          "nodeMinHeight": 40
        },
        "paint": {
          "bg": "#0e1413",
          "panel": "#151d1c",
          "text": "#dce5e3",
          "muted": "#b7d7d1",
          "border": "rgba(183, 215, 209, 0.22)",
          "nodeFill": "#1a2221",
          "nodeFillSelected": "#00504a",
          "nodeStroke": "transparent",
          "nodeStrokeSelected": "#b9ebe3",
          "edgeStroke": "#8ea3a0",
          "relationStroke": "#ffb86c",
          "relationStrokeSelected": "#ffb4ab",
          "summaryStroke": "#3f4947"
        }
      },
      "edges": {
        "strokeWidth": 4,
        "cap": "round",
        "join": "round",
        "routeType": "orthogonal-rounded"
      },
      "relations": {
        "strokeWidth": 2,
        "cap": "round",
        "join": "round"
      },
      "nodeShape": {
        "type": "rounded-rect",
        "radius": 16,
        "strokeWidth": 0
      },
      "rainbow": {
        "enabled": false,
        "palette": [
          "#006a60",
          "#14b8a6",
          "#06b6d4",
          "#0ea5e9",
          "#60a5fa",
          "#f59e0b",
          "#fb7185",
          "#a78bfa"
        ]
      },
      "background": {
        "color": "#0e1413"
      },
      "rules": {
        "nodeRules": [
          {
            "id": "m3-root",
            "priority": 10,
            "when": {
              "kind": "depth",
              "depth": 0
            },
            "apply": {
              "layout": {
                "textAlign": "center",
                "fontWeight": 700,
                "fontSize": 24,
                "paddingX": 18,
                "paddingY": 12
              },
              "paint": {
                "nodeFill": "#00504a",
                "nodeFillSelected": "#006a60",
                "text": "#f2fffd"
              },
              "incomingEdge": {
                "strokeColor": "#b9ebe3",
                "strokeWidth": 2.5
              }
            }
          },
          {
            "id": "m3-depth-1",
            "priority": 10,
            "when": {
              "kind": "depth",
              "depth": 1
            },
            "apply": {
              "layout": {
                "fontWeight": 600,
                "fontSize": 18
              },
              "paint": {
                "nodeFill": "#293231",
                "text": "#dce5e3"
              },
              "incomingEdge": {
                "strokeColor": "#a8d1cb",
                "routeType": "center-quadratic"
              }
            }
          },
          {
            "id": "m3-depth-2",
            "priority": 10,
            "when": {
              "kind": "depth",
              "depth": 2
            },
            "apply": {
              "paint": {
                "nodeFill": "#4a2a00",
                "text": "#ffe8cc"
              },
              "incomingEdge": {
                "strokeColor": "#ffb86c"
              }
            }
          },
          {
            "id": "m3-depth-3plus",
            "priority": 10,
            "when": {
              "kind": "depthRange",
              "minDepth": 3
            },
            "apply": {
              "incomingEdge": {
                "strokeWidth": 1.75
              }
            }
          }
        ]
      }
    }
  }
};

// ../themes/src/themes/material-3-rounded-orthogonal-citrus.ts
var material3RoundedOrthogonalCitrusTheme = {
  "schemaVersion": 1,
  "id": "kmind-material-3-rounded-orthogonal-citrus",
  "name": "Material 3 \xB7 Rounded Orthogonal \xB7 Citrus",
  "variants": {
    "light": {
      "tokens": {
        "layout": {
          "fontFamily": "ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif",
          "fontSize": 14,
          "fontWeight": 450,
          "lineHeight": 1.45,
          "textAlign": "left",
          "paddingX": 14,
          "paddingY": 10,
          "nodeMinWidth": 60,
          "nodeMinHeight": 40
        },
        "paint": {
          "bg": "#fff8f1",
          "panel": "#ffffff",
          "text": "#201a13",
          "muted": "#51443a",
          "border": "#f2dccc",
          "nodeFill": "#fff1e6",
          "nodeFillSelected": "#ffddb5",
          "nodeStroke": "transparent",
          "nodeStrokeSelected": "#8f4c00",
          "edgeStroke": "#857468",
          "relationStroke": "#006a6a",
          "relationStrokeSelected": "#ba1a1a",
          "summaryStroke": "#d7c2b3"
        }
      },
      "edges": {
        "strokeWidth": 4,
        "cap": "round",
        "join": "round",
        "routeType": "orthogonal-rounded"
      },
      "relations": {
        "strokeWidth": 2,
        "cap": "round",
        "join": "round"
      },
      "nodeShape": {
        "type": "rounded-rect",
        "radius": 16,
        "strokeWidth": 0
      },
      "rainbow": {
        "enabled": false,
        "palette": [
          "#8f4c00",
          "#f59e0b",
          "#f97316",
          "#ef4444",
          "#fb7185",
          "#a78bfa",
          "#0ea5e9",
          "#14b8a6"
        ]
      },
      "background": {
        "color": "#fff8f1"
      },
      "rules": {
        "nodeRules": [
          {
            "id": "m3-root",
            "priority": 10,
            "when": {
              "kind": "depth",
              "depth": 0
            },
            "apply": {
              "layout": {
                "textAlign": "center",
                "fontWeight": 700,
                "fontSize": 24,
                "paddingX": 18,
                "paddingY": 12
              },
              "paint": {
                "nodeFill": "#ffddb5",
                "nodeFillSelected": "#ffb86c",
                "text": "#2b1600"
              },
              "incomingEdge": {
                "strokeColor": "#8f4c00",
                "strokeWidth": 2.5
              }
            }
          },
          {
            "id": "m3-depth-1",
            "priority": 10,
            "when": {
              "kind": "depth",
              "depth": 1
            },
            "apply": {
              "layout": {
                "fontWeight": 600,
                "fontSize": 18
              },
              "paint": {
                "nodeFill": "#f2dccc",
                "text": "#231a12"
              },
              "incomingEdge": {
                "strokeColor": "#7a5a43",
                "routeType": "center-quadratic"
              }
            }
          },
          {
            "id": "m3-depth-2",
            "priority": 10,
            "when": {
              "kind": "depth",
              "depth": 2
            },
            "apply": {
              "paint": {
                "nodeFill": "#d6f5ff",
                "text": "#002022"
              },
              "incomingEdge": {
                "strokeColor": "#006a6a"
              }
            }
          },
          {
            "id": "m3-depth-3plus",
            "priority": 10,
            "when": {
              "kind": "depthRange",
              "minDepth": 3
            },
            "apply": {
              "incomingEdge": {
                "strokeWidth": 1.75
              }
            }
          }
        ]
      }
    },
    "dark": {
      "tokens": {
        "layout": {
          "fontFamily": "ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif",
          "fontSize": 14,
          "fontWeight": 450,
          "lineHeight": 1.45,
          "textAlign": "left",
          "paddingX": 14,
          "paddingY": 10,
          "nodeMinWidth": 60,
          "nodeMinHeight": 40
        },
        "paint": {
          "bg": "#1a120b",
          "panel": "#241a12",
          "text": "#f2dfd2",
          "muted": "#d7c2b3",
          "border": "rgba(215, 194, 179, 0.22)",
          "nodeFill": "#2a1f16",
          "nodeFillSelected": "#6b3b00",
          "nodeStroke": "transparent",
          "nodeStrokeSelected": "#ffddb5",
          "edgeStroke": "#a39184",
          "relationStroke": "#4fd8eb",
          "relationStrokeSelected": "#ffb4ab",
          "summaryStroke": "#51443a"
        }
      },
      "edges": {
        "strokeWidth": 4,
        "cap": "round",
        "join": "round",
        "routeType": "orthogonal-rounded"
      },
      "relations": {
        "strokeWidth": 2,
        "cap": "round",
        "join": "round"
      },
      "nodeShape": {
        "type": "rounded-rect",
        "radius": 16,
        "strokeWidth": 0
      },
      "rainbow": {
        "enabled": false,
        "palette": [
          "#8f4c00",
          "#f59e0b",
          "#f97316",
          "#ef4444",
          "#fb7185",
          "#a78bfa",
          "#0ea5e9",
          "#14b8a6"
        ]
      },
      "background": {
        "color": "#1a120b"
      },
      "rules": {
        "nodeRules": [
          {
            "id": "m3-root",
            "priority": 10,
            "when": {
              "kind": "depth",
              "depth": 0
            },
            "apply": {
              "layout": {
                "textAlign": "center",
                "fontWeight": 700,
                "fontSize": 24,
                "paddingX": 18,
                "paddingY": 12
              },
              "paint": {
                "nodeFill": "#6b3b00",
                "nodeFillSelected": "#8f4c00",
                "text": "#fff8f1"
              },
              "incomingEdge": {
                "strokeColor": "#ffddb5",
                "strokeWidth": 2.5
              }
            }
          },
          {
            "id": "m3-depth-1",
            "priority": 10,
            "when": {
              "kind": "depth",
              "depth": 1
            },
            "apply": {
              "layout": {
                "fontWeight": 600,
                "fontSize": 18
              },
              "paint": {
                "nodeFill": "#3a2b21",
                "text": "#f2dfd2"
              },
              "incomingEdge": {
                "strokeColor": "#e5c4a5",
                "routeType": "center-quadratic"
              }
            }
          },
          {
            "id": "m3-depth-2",
            "priority": 10,
            "when": {
              "kind": "depth",
              "depth": 2
            },
            "apply": {
              "paint": {
                "nodeFill": "#00363a",
                "text": "#e1f4f5"
              },
              "incomingEdge": {
                "strokeColor": "#4fd8eb"
              }
            }
          },
          {
            "id": "m3-depth-3plus",
            "priority": 10,
            "when": {
              "kind": "depthRange",
              "minDepth": 3
            },
            "apply": {
              "incomingEdge": {
                "strokeWidth": 1.75
              }
            }
          }
        ]
      }
    }
  }
};

// ../themes/src/themes/material-3-rounded-orthogonal-forest.ts
var material3RoundedOrthogonalForestTheme = {
  "schemaVersion": 1,
  "id": "kmind-material-3-rounded-orthogonal-forest",
  "name": "Material 3 \xB7 Rounded Orthogonal \xB7 Forest",
  "variants": {
    "light": {
      "tokens": {
        "layout": {
          "fontFamily": "ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif",
          "fontSize": 14,
          "fontWeight": 450,
          "lineHeight": 1.45,
          "textAlign": "left",
          "paddingX": 14,
          "paddingY": 10,
          "nodeMinWidth": 60,
          "nodeMinHeight": 40
        },
        "paint": {
          "bg": "#f5fff7",
          "panel": "#ffffff",
          "text": "#1b1f1b",
          "muted": "#444a44",
          "border": "#dbe5db",
          "nodeFill": "#eef7ee",
          "nodeFillSelected": "#cfe9d2",
          "nodeStroke": "transparent",
          "nodeStrokeSelected": "#0f6d2b",
          "edgeStroke": "#6f7a6f",
          "relationStroke": "#006a60",
          "relationStrokeSelected": "#ba1a1a",
          "summaryStroke": "#c4cec3"
        }
      },
      "edges": {
        "strokeWidth": 4,
        "cap": "round",
        "join": "round",
        "routeType": "orthogonal-rounded"
      },
      "relations": {
        "strokeWidth": 2,
        "cap": "round",
        "join": "round"
      },
      "nodeShape": {
        "type": "rounded-rect",
        "radius": 16,
        "strokeWidth": 0
      },
      "rainbow": {
        "enabled": false,
        "palette": [
          "#0f6d2b",
          "#22c55e",
          "#14b8a6",
          "#06b6d4",
          "#60a5fa",
          "#f59e0b",
          "#fb7185",
          "#a78bfa"
        ]
      },
      "background": {
        "color": "#f5fff7"
      },
      "rules": {
        "nodeRules": [
          {
            "id": "m3-root",
            "priority": 10,
            "when": {
              "kind": "depth",
              "depth": 0
            },
            "apply": {
              "layout": {
                "textAlign": "center",
                "fontWeight": 700,
                "fontSize": 24,
                "paddingX": 18,
                "paddingY": 12
              },
              "paint": {
                "nodeFill": "#cfe9d2",
                "nodeFillSelected": "#a3d6a8",
                "text": "#00210f"
              },
              "incomingEdge": {
                "strokeColor": "#0f6d2b",
                "strokeWidth": 2.5
              }
            }
          },
          {
            "id": "m3-depth-1",
            "priority": 10,
            "when": {
              "kind": "depth",
              "depth": 1
            },
            "apply": {
              "layout": {
                "fontWeight": 600,
                "fontSize": 18
              },
              "paint": {
                "nodeFill": "#dcebdd",
                "text": "#132016"
              },
              "incomingEdge": {
                "strokeColor": "#3d5e3f",
                "routeType": "center-quadratic"
              }
            }
          },
          {
            "id": "m3-depth-2",
            "priority": 10,
            "when": {
              "kind": "depth",
              "depth": 2
            },
            "apply": {
              "paint": {
                "nodeFill": "#ffe8cc",
                "text": "#2b1600"
              },
              "incomingEdge": {
                "strokeColor": "#8c5000"
              }
            }
          },
          {
            "id": "m3-depth-3plus",
            "priority": 10,
            "when": {
              "kind": "depthRange",
              "minDepth": 3
            },
            "apply": {
              "incomingEdge": {
                "strokeWidth": 1.75
              }
            }
          }
        ]
      }
    },
    "dark": {
      "tokens": {
        "layout": {
          "fontFamily": "ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif",
          "fontSize": 14,
          "fontWeight": 450,
          "lineHeight": 1.45,
          "textAlign": "left",
          "paddingX": 14,
          "paddingY": 10,
          "nodeMinWidth": 60,
          "nodeMinHeight": 40
        },
        "paint": {
          "bg": "#0f1410",
          "panel": "#171d18",
          "text": "#e0e4dd",
          "muted": "#c4cec3",
          "border": "rgba(196, 206, 195, 0.22)",
          "nodeFill": "#1a221b",
          "nodeFillSelected": "#1b5e20",
          "nodeStroke": "transparent",
          "nodeStrokeSelected": "#a3d6a8",
          "edgeStroke": "#909a90",
          "relationStroke": "#4fd8c7",
          "relationStrokeSelected": "#ffb4ab",
          "summaryStroke": "#444a44"
        }
      },
      "edges": {
        "strokeWidth": 4,
        "cap": "round",
        "join": "round",
        "routeType": "orthogonal-rounded"
      },
      "relations": {
        "strokeWidth": 2,
        "cap": "round",
        "join": "round"
      },
      "nodeShape": {
        "type": "rounded-rect",
        "radius": 16,
        "strokeWidth": 0
      },
      "rainbow": {
        "enabled": false,
        "palette": [
          "#0f6d2b",
          "#22c55e",
          "#14b8a6",
          "#06b6d4",
          "#60a5fa",
          "#f59e0b",
          "#fb7185",
          "#a78bfa"
        ]
      },
      "background": {
        "color": "#0f1410"
      },
      "rules": {
        "nodeRules": [
          {
            "id": "m3-root",
            "priority": 10,
            "when": {
              "kind": "depth",
              "depth": 0
            },
            "apply": {
              "layout": {
                "textAlign": "center",
                "fontWeight": 700,
                "fontSize": 24,
                "paddingX": 18,
                "paddingY": 12
              },
              "paint": {
                "nodeFill": "#1b5e20",
                "nodeFillSelected": "#0f6d2b",
                "text": "#f5fff7"
              },
              "incomingEdge": {
                "strokeColor": "#a3d6a8",
                "strokeWidth": 2.5
              }
            }
          },
          {
            "id": "m3-depth-1",
            "priority": 10,
            "when": {
              "kind": "depth",
              "depth": 1
            },
            "apply": {
              "layout": {
                "fontWeight": 600,
                "fontSize": 18
              },
              "paint": {
                "nodeFill": "#2a322b",
                "text": "#e0e4dd"
              },
              "incomingEdge": {
                "strokeColor": "#b1d9b3",
                "routeType": "center-quadratic"
              }
            }
          },
          {
            "id": "m3-depth-2",
            "priority": 10,
            "when": {
              "kind": "depth",
              "depth": 2
            },
            "apply": {
              "paint": {
                "nodeFill": "#4a2a00",
                "text": "#ffe8cc"
              },
              "incomingEdge": {
                "strokeColor": "#ffb86c"
              }
            }
          },
          {
            "id": "m3-depth-3plus",
            "priority": 10,
            "when": {
              "kind": "depthRange",
              "minDepth": 3
            },
            "apply": {
              "incomingEdge": {
                "strokeWidth": 1.75
              }
            }
          }
        ]
      }
    }
  }
};

// ../themes/src/themes/material-3-rounded-orthogonal-ocean.ts
var material3RoundedOrthogonalOceanTheme = {
  "schemaVersion": 1,
  "id": "kmind-material-3-rounded-orthogonal-ocean",
  "name": "Material 3 \xB7 Rounded Orthogonal \xB7 Ocean",
  "variants": {
    "light": {
      "tokens": {
        "layout": {
          "fontFamily": "ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif",
          "fontSize": 14,
          "fontWeight": 450,
          "lineHeight": 1.45,
          "textAlign": "left",
          "paddingX": 14,
          "paddingY": 10,
          "nodeMinWidth": 60,
          "nodeMinHeight": 40
        },
        "paint": {
          "bg": "#f6f9ff",
          "panel": "#ffffff",
          "text": "#1a1b1f",
          "muted": "#44474f",
          "border": "#dfe3eb",
          "nodeFill": "#eef2fb",
          "nodeFillSelected": "#d7e3ff",
          "nodeStroke": "transparent",
          "nodeStrokeSelected": "#1b5fa7",
          "edgeStroke": "#6c778a",
          "relationStroke": "#006a6a",
          "relationStrokeSelected": "#ba1a1a",
          "summaryStroke": "#c3c7cf"
        }
      },
      "edges": {
        "strokeWidth": 4,
        "cap": "round",
        "join": "round",
        "routeType": "orthogonal-rounded"
      },
      "relations": {
        "strokeWidth": 2,
        "cap": "round",
        "join": "round"
      },
      "nodeShape": {
        "type": "rounded-rect",
        "radius": 16,
        "strokeWidth": 0
      },
      "rainbow": {
        "enabled": false,
        "palette": [
          "#1b5fa7",
          "#2f6fe3",
          "#0ea5e9",
          "#14b8a6",
          "#22c55e",
          "#f59e0b",
          "#fb7185",
          "#a78bfa"
        ]
      },
      "background": {
        "color": "#f6f9ff"
      },
      "rules": {
        "nodeRules": [
          {
            "id": "m3-root",
            "priority": 10,
            "when": {
              "kind": "depth",
              "depth": 0
            },
            "apply": {
              "layout": {
                "textAlign": "center",
                "fontWeight": 700,
                "fontSize": 24,
                "paddingX": 18,
                "paddingY": 12
              },
              "paint": {
                "nodeFill": "#d7e3ff",
                "nodeFillSelected": "#aec6ff",
                "text": "#001b3f"
              },
              "incomingEdge": {
                "strokeColor": "#1b5fa7",
                "strokeWidth": 2.5
              }
            }
          },
          {
            "id": "m3-depth-1",
            "priority": 10,
            "when": {
              "kind": "depth",
              "depth": 1
            },
            "apply": {
              "layout": {
                "fontWeight": 600,
                "fontSize": 18
              },
              "paint": {
                "nodeFill": "#d7e3f8",
                "text": "#1c1e24"
              },
              "incomingEdge": {
                "strokeColor": "#415f91",
                "routeType": "center-quadratic"
              }
            }
          },
          {
            "id": "m3-depth-2",
            "priority": 10,
            "when": {
              "kind": "depth",
              "depth": 2
            },
            "apply": {
              "paint": {
                "nodeFill": "#cfe9ff",
                "text": "#002022"
              },
              "incomingEdge": {
                "strokeColor": "#006a6a"
              }
            }
          },
          {
            "id": "m3-depth-3plus",
            "priority": 10,
            "when": {
              "kind": "depthRange",
              "minDepth": 3
            },
            "apply": {
              "incomingEdge": {
                "strokeWidth": 1.75
              }
            }
          }
        ]
      }
    },
    "dark": {
      "tokens": {
        "layout": {
          "fontFamily": "ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif",
          "fontSize": 14,
          "fontWeight": 450,
          "lineHeight": 1.45,
          "textAlign": "left",
          "paddingX": 14,
          "paddingY": 10,
          "nodeMinWidth": 60,
          "nodeMinHeight": 40
        },
        "paint": {
          "bg": "#0f1117",
          "panel": "#161b22",
          "text": "#e1e2e6",
          "muted": "#c3c7cf",
          "border": "rgba(195, 199, 207, 0.22)",
          "nodeFill": "#1a1f27",
          "nodeFillSelected": "#0e4b8a",
          "nodeStroke": "transparent",
          "nodeStrokeSelected": "#d7e3ff",
          "edgeStroke": "#8f98a7",
          "relationStroke": "#4fd8eb",
          "relationStrokeSelected": "#ffb4ab",
          "summaryStroke": "#44474f"
        }
      },
      "edges": {
        "strokeWidth": 4,
        "cap": "round",
        "join": "round",
        "routeType": "orthogonal-rounded"
      },
      "relations": {
        "strokeWidth": 2,
        "cap": "round",
        "join": "round"
      },
      "nodeShape": {
        "type": "rounded-rect",
        "radius": 16,
        "strokeWidth": 0
      },
      "rainbow": {
        "enabled": false,
        "palette": [
          "#1b5fa7",
          "#2f6fe3",
          "#0ea5e9",
          "#14b8a6",
          "#22c55e",
          "#f59e0b",
          "#fb7185",
          "#a78bfa"
        ]
      },
      "background": {
        "color": "#0f1117"
      },
      "rules": {
        "nodeRules": [
          {
            "id": "m3-root",
            "priority": 10,
            "when": {
              "kind": "depth",
              "depth": 0
            },
            "apply": {
              "layout": {
                "textAlign": "center",
                "fontWeight": 700,
                "fontSize": 24,
                "paddingX": 18,
                "paddingY": 12
              },
              "paint": {
                "nodeFill": "#0e4b8a",
                "nodeFillSelected": "#1b5fa7",
                "text": "#f6f9ff"
              },
              "incomingEdge": {
                "strokeColor": "#d7e3ff",
                "strokeWidth": 2.5
              }
            }
          },
          {
            "id": "m3-depth-1",
            "priority": 10,
            "when": {
              "kind": "depth",
              "depth": 1
            },
            "apply": {
              "layout": {
                "fontWeight": 600,
                "fontSize": 18
              },
              "paint": {
                "nodeFill": "#2a3140",
                "text": "#e1e2e6"
              },
              "incomingEdge": {
                "strokeColor": "#b0c6ff",
                "routeType": "center-quadratic"
              }
            }
          },
          {
            "id": "m3-depth-2",
            "priority": 10,
            "when": {
              "kind": "depth",
              "depth": 2
            },
            "apply": {
              "paint": {
                "nodeFill": "#00363a",
                "text": "#e1f4f5"
              },
              "incomingEdge": {
                "strokeColor": "#4fd8eb"
              }
            }
          },
          {
            "id": "m3-depth-3plus",
            "priority": 10,
            "when": {
              "kind": "depthRange",
              "minDepth": 3
            },
            "apply": {
              "incomingEdge": {
                "strokeWidth": 1.75
              }
            }
          }
        ]
      }
    }
  }
};

// ../themes/src/themes/material-3-rounded-orthogonal-rose.ts
var material3RoundedOrthogonalRoseTheme = {
  "schemaVersion": 1,
  "id": "kmind-material-3-rounded-orthogonal-rose",
  "name": "Material 3 \xB7 Rounded Orthogonal \xB7 Rose",
  "variants": {
    "light": {
      "tokens": {
        "layout": {
          "fontFamily": "ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif",
          "fontSize": 14,
          "fontWeight": 450,
          "lineHeight": 1.45,
          "textAlign": "left",
          "paddingX": 14,
          "paddingY": 10,
          "nodeMinWidth": 60,
          "nodeMinHeight": 40
        },
        "paint": {
          "bg": "#fff7f9",
          "panel": "#ffffff",
          "text": "#201a1b",
          "muted": "#514345",
          "border": "#f2dce0",
          "nodeFill": "#fff0f3",
          "nodeFillSelected": "#ffd9e0",
          "nodeStroke": "transparent",
          "nodeStrokeSelected": "#b0003a",
          "edgeStroke": "#857376",
          "relationStroke": "#006a6a",
          "relationStrokeSelected": "#ba1a1a",
          "summaryStroke": "#d7c2c6"
        }
      },
      "edges": {
        "strokeWidth": 4,
        "cap": "round",
        "join": "round",
        "routeType": "orthogonal-rounded"
      },
      "relations": {
        "strokeWidth": 2,
        "cap": "round",
        "join": "round"
      },
      "nodeShape": {
        "type": "rounded-rect",
        "radius": 16,
        "strokeWidth": 0
      },
      "rainbow": {
        "enabled": false,
        "palette": [
          "#b0003a",
          "#fb7185",
          "#ef4444",
          "#f59e0b",
          "#22c55e",
          "#14b8a6",
          "#0ea5e9",
          "#a78bfa"
        ]
      },
      "background": {
        "color": "#fff7f9"
      },
      "rules": {
        "nodeRules": [
          {
            "id": "m3-root",
            "priority": 10,
            "when": {
              "kind": "depth",
              "depth": 0
            },
            "apply": {
              "layout": {
                "textAlign": "center",
                "fontWeight": 700,
                "fontSize": 24,
                "paddingX": 18,
                "paddingY": 12
              },
              "paint": {
                "nodeFill": "#ffd9e0",
                "nodeFillSelected": "#ffb1c3",
                "text": "#3a0713"
              },
              "incomingEdge": {
                "strokeColor": "#b0003a",
                "strokeWidth": 2.5
              }
            }
          },
          {
            "id": "m3-depth-1",
            "priority": 10,
            "when": {
              "kind": "depth",
              "depth": 1
            },
            "apply": {
              "layout": {
                "fontWeight": 600,
                "fontSize": 18
              },
              "paint": {
                "nodeFill": "#f2dce0",
                "text": "#231a1b"
              },
              "incomingEdge": {
                "strokeColor": "#7a4a56",
                "routeType": "center-quadratic"
              }
            }
          },
          {
            "id": "m3-depth-2",
            "priority": 10,
            "when": {
              "kind": "depth",
              "depth": 2
            },
            "apply": {
              "paint": {
                "nodeFill": "#eaddff",
                "text": "#21005d"
              },
              "incomingEdge": {
                "strokeColor": "#6750a4"
              }
            }
          },
          {
            "id": "m3-depth-3plus",
            "priority": 10,
            "when": {
              "kind": "depthRange",
              "minDepth": 3
            },
            "apply": {
              "incomingEdge": {
                "strokeWidth": 1.75
              }
            }
          }
        ]
      }
    },
    "dark": {
      "tokens": {
        "layout": {
          "fontFamily": "ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif",
          "fontSize": 14,
          "fontWeight": 450,
          "lineHeight": 1.45,
          "textAlign": "left",
          "paddingX": 14,
          "paddingY": 10,
          "nodeMinWidth": 60,
          "nodeMinHeight": 40
        },
        "paint": {
          "bg": "#1a1113",
          "panel": "#241a1c",
          "text": "#f2dfe2",
          "muted": "#d7c2c6",
          "border": "rgba(215, 194, 198, 0.22)",
          "nodeFill": "#2a1f21",
          "nodeFillSelected": "#8c0030",
          "nodeStroke": "transparent",
          "nodeStrokeSelected": "#ffd9e0",
          "edgeStroke": "#a39195",
          "relationStroke": "#4fd8eb",
          "relationStrokeSelected": "#ffb4ab",
          "summaryStroke": "#514345"
        }
      },
      "edges": {
        "strokeWidth": 4,
        "cap": "round",
        "join": "round",
        "routeType": "orthogonal-rounded"
      },
      "relations": {
        "strokeWidth": 2,
        "cap": "round",
        "join": "round"
      },
      "nodeShape": {
        "type": "rounded-rect",
        "radius": 16,
        "strokeWidth": 0
      },
      "rainbow": {
        "enabled": false,
        "palette": [
          "#b0003a",
          "#fb7185",
          "#ef4444",
          "#f59e0b",
          "#22c55e",
          "#14b8a6",
          "#0ea5e9",
          "#a78bfa"
        ]
      },
      "background": {
        "color": "#1a1113"
      },
      "rules": {
        "nodeRules": [
          {
            "id": "m3-root",
            "priority": 10,
            "when": {
              "kind": "depth",
              "depth": 0
            },
            "apply": {
              "layout": {
                "textAlign": "center",
                "fontWeight": 700,
                "fontSize": 24,
                "paddingX": 18,
                "paddingY": 12
              },
              "paint": {
                "nodeFill": "#8c0030",
                "nodeFillSelected": "#b0003a",
                "text": "#fff7f9"
              },
              "incomingEdge": {
                "strokeColor": "#ffd9e0",
                "strokeWidth": 2.5
              }
            }
          },
          {
            "id": "m3-depth-1",
            "priority": 10,
            "when": {
              "kind": "depth",
              "depth": 1
            },
            "apply": {
              "layout": {
                "fontWeight": 600,
                "fontSize": 18
              },
              "paint": {
                "nodeFill": "#3a2b2d",
                "text": "#f2dfe2"
              },
              "incomingEdge": {
                "strokeColor": "#f0b6c1",
                "routeType": "center-quadratic"
              }
            }
          },
          {
            "id": "m3-depth-2",
            "priority": 10,
            "when": {
              "kind": "depth",
              "depth": 2
            },
            "apply": {
              "paint": {
                "nodeFill": "#4f378b",
                "text": "#fef7ff"
              },
              "incomingEdge": {
                "strokeColor": "#d0bcff"
              }
            }
          },
          {
            "id": "m3-depth-3plus",
            "priority": 10,
            "when": {
              "kind": "depthRange",
              "minDepth": 3
            },
            "apply": {
              "incomingEdge": {
                "strokeWidth": 1.75
              }
            }
          }
        ]
      }
    }
  }
};

// ../themes/src/themes/material-3-rounded-orthogonal-violet.ts
var material3RoundedOrthogonalVioletTheme = {
  "schemaVersion": 1,
  "id": "kmind-material-3-rounded-orthogonal-violet",
  "name": "Material 3 \xB7 Rounded Orthogonal \xB7 Violet",
  "variants": {
    "light": {
      "tokens": {
        "layout": {
          "fontFamily": "ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif",
          "fontSize": 14,
          "fontWeight": 450,
          "lineHeight": 1.45,
          "textAlign": "left",
          "paddingX": 14,
          "paddingY": 10,
          "nodeMinWidth": 60,
          "nodeMinHeight": 40
        },
        "paint": {
          "bg": "#fef7ff",
          "panel": "#ffffff",
          "text": "#1c1b1f",
          "muted": "#49454f",
          "border": "#e7e0ec",
          "nodeFill": "#f3edf7",
          "nodeFillSelected": "#eaddff",
          "nodeStroke": "transparent",
          "nodeStrokeSelected": "#6750a4",
          "edgeStroke": "#79747e",
          "relationStroke": "#7d5260",
          "relationStrokeSelected": "#b3261e",
          "summaryStroke": "#cac4d0"
        }
      },
      "edges": {
        "strokeWidth": 4,
        "cap": "round",
        "join": "round",
        "routeType": "orthogonal-rounded"
      },
      "relations": {
        "strokeWidth": 2,
        "cap": "round",
        "join": "round"
      },
      "nodeShape": {
        "type": "rounded-rect",
        "radius": 16,
        "strokeWidth": 0
      },
      "rainbow": {
        "enabled": false,
        "palette": [
          "#ef4444",
          "#f97316",
          "#eab308",
          "#22c55e",
          "#06b6d4",
          "#3b82f6",
          "#8b5cf6",
          "#ec4899"
        ]
      },
      "background": {
        "color": "#fef7ff"
      },
      "rules": {
        "nodeRules": [
          {
            "id": "m3-root",
            "priority": 10,
            "when": {
              "kind": "depth",
              "depth": 0
            },
            "apply": {
              "layout": {
                "textAlign": "center",
                "fontWeight": 700,
                "fontSize": 24,
                "paddingX": 18,
                "paddingY": 12
              },
              "paint": {
                "nodeFill": "#eaddff",
                "nodeFillSelected": "#d0bcff",
                "text": "#21005d"
              },
              "incomingEdge": {
                "strokeColor": "#6750a4",
                "strokeWidth": 2.5
              }
            }
          },
          {
            "id": "m3-depth-1",
            "priority": 10,
            "when": {
              "kind": "depth",
              "depth": 1
            },
            "apply": {
              "layout": {
                "fontWeight": 600,
                "fontSize": 18
              },
              "paint": {
                "nodeFill": "#e8def8",
                "text": "#1d192b"
              },
              "incomingEdge": {
                "strokeColor": "#625b71",
                "routeType": "center-quadratic"
              }
            }
          },
          {
            "id": "m3-depth-2",
            "priority": 10,
            "when": {
              "kind": "depth",
              "depth": 2
            },
            "apply": {
              "paint": {
                "nodeFill": "#ffd8e4",
                "text": "#31111d"
              },
              "incomingEdge": {
                "strokeColor": "#7d5260"
              }
            }
          }
        ]
      }
    },
    "dark": {
      "tokens": {
        "layout": {
          "fontFamily": "ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif",
          "fontSize": 14,
          "fontWeight": 450,
          "lineHeight": 1.45,
          "textAlign": "left",
          "paddingX": 14,
          "paddingY": 10,
          "nodeMinWidth": 60,
          "nodeMinHeight": 40
        },
        "paint": {
          "bg": "#141218",
          "panel": "#1d1b20",
          "text": "#e6e1e5",
          "muted": "#cac4d0",
          "border": "rgba(202, 196, 208, 0.22)",
          "nodeFill": "#211f26",
          "nodeFillSelected": "#4f378b",
          "nodeStroke": "transparent",
          "nodeStrokeSelected": "#d0bcff",
          "edgeStroke": "#938f99",
          "relationStroke": "#efb8c8",
          "relationStrokeSelected": "#f2b8b5",
          "summaryStroke": "#49454f"
        }
      },
      "edges": {
        "strokeWidth": 4,
        "cap": "round",
        "join": "round",
        "routeType": "orthogonal-rounded"
      },
      "relations": {
        "strokeWidth": 2,
        "cap": "round",
        "join": "round"
      },
      "nodeShape": {
        "type": "rounded-rect",
        "radius": 16,
        "strokeWidth": 0
      },
      "rainbow": {
        "enabled": false,
        "palette": [
          "#ef4444",
          "#f97316",
          "#eab308",
          "#22c55e",
          "#06b6d4",
          "#3b82f6",
          "#8b5cf6",
          "#ec4899"
        ]
      },
      "background": {
        "color": "#141218"
      },
      "rules": {
        "nodeRules": [
          {
            "id": "m3-root",
            "priority": 10,
            "when": {
              "kind": "depth",
              "depth": 0
            },
            "apply": {
              "layout": {
                "textAlign": "center",
                "fontWeight": 700,
                "fontSize": 24,
                "paddingX": 18,
                "paddingY": 12
              },
              "paint": {
                "nodeFill": "#4f378b",
                "nodeFillSelected": "#6750a4",
                "text": "#fef7ff"
              },
              "incomingEdge": {
                "strokeColor": "#d0bcff",
                "strokeWidth": 2.5
              }
            }
          },
          {
            "id": "m3-depth-1",
            "priority": 10,
            "when": {
              "kind": "depth",
              "depth": 1
            },
            "apply": {
              "layout": {
                "fontWeight": 600,
                "fontSize": 18
              },
              "paint": {
                "nodeFill": "#332d41",
                "text": "#e6e1e5"
              },
              "incomingEdge": {
                "strokeColor": "#cbc2db",
                "routeType": "center-quadratic"
              }
            }
          },
          {
            "id": "m3-depth-2",
            "priority": 10,
            "when": {
              "kind": "depth",
              "depth": 2
            },
            "apply": {
              "paint": {
                "nodeFill": "#492532",
                "text": "#fef7ff"
              },
              "incomingEdge": {
                "strokeColor": "#efb8c8"
              }
            }
          },
          {
            "id": "m3-depth-3plus",
            "priority": 10,
            "when": {
              "kind": "depthRange",
              "minDepth": 3
            },
            "apply": {
              "incomingEdge": {
                "strokeWidth": 1.75
              }
            }
          }
        ]
      }
    }
  }
};

// ../themes/src/themes/material-3-slate.ts
var material3SlateTheme = {
  "schemaVersion": 1,
  "id": "kmind-material-3-slate",
  "name": "KMind Slate",
  "description": "Material 3 seed #303745",
  "variants": {
    "light": {
      "tokens": {
        "layout": {
          "fontFamily": "ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif",
          "fontSize": 14,
          "fontWeight": 450,
          "lineHeight": 1.45,
          "textAlign": "left",
          "paddingX": 14,
          "paddingY": 10,
          "nodeMinWidth": 60,
          "nodeMinHeight": 40
        },
        "paint": {
          "bg": "#f6f7fb",
          "panel": "#ffffff",
          "text": "#1a1f27",
          "muted": "#525b6b",
          "border": "#e1e6ef",
          "nodeFill": "#eef1f6",
          "nodeFillSelected": "#dfe5f0",
          "nodeStroke": "transparent",
          "nodeStrokeSelected": "#303745",
          "edgeStroke": "#606a7a",
          "relationStroke": "#4f5d78",
          "relationStrokeSelected": "#ba1a1a",
          "summaryStroke": "#c5cad4"
        }
      },
      "edges": {
        "strokeWidth": 4,
        "cap": "round",
        "join": "round",
        "routeType": "orthogonal-rounded"
      },
      "relations": {
        "strokeWidth": 2,
        "cap": "round",
        "join": "round"
      },
      "nodeShape": {
        "type": "rounded-rect",
        "radius": 16,
        "strokeWidth": 0
      },
      "rainbow": {
        "enabled": false,
        "palette": [
          "#303745",
          "#1b5fa7",
          "#0ea5e9",
          "#14b8a6",
          "#22c55e",
          "#f59e0b",
          "#fb7185",
          "#a78bfa"
        ]
      },
      "background": {
        "color": "#f6f7fb"
      },
      "rules": {
        "nodeRules": [
          {
            "id": "m3-root",
            "priority": 10,
            "when": {
              "kind": "depth",
              "depth": 0
            },
            "apply": {
              "layout": {
                "textAlign": "center",
                "fontWeight": 700,
                "fontSize": 24,
                "paddingX": 18,
                "paddingY": 12
              },
              "paint": {
                "nodeFill": "#3949a9",
                "nodeFillSelected": "#c9d3e5",
                "text": "#ffffff"
              }
            }
          },
          {
            "id": "m3-depth-1",
            "priority": 10,
            "when": {
              "kind": "depth",
              "depth": 1
            },
            "apply": {
              "layout": {
                "fontWeight": 600,
                "fontSize": 18
              },
              "paint": {
                "nodeFill": "#eef1f6",
                "text": "#1a1f27"
              },
              "incomingEdge": {
                "strokeColor": "#303745",
                "routeType": "center-quadratic"
              }
            }
          },
          {
            "id": "m3-depth-2",
            "priority": 10,
            "when": {
              "kind": "depth",
              "depth": 2
            },
            "apply": {
              "incomingEdge": {
                "strokeColor": "#4f5d78"
              }
            }
          },
          {
            "id": "m3-depth-3plus",
            "priority": 10,
            "when": {
              "kind": "depthRange",
              "minDepth": 3
            },
            "apply": {
              "incomingEdge": {
                "strokeWidth": 1.75
              }
            }
          }
        ]
      }
    },
    "dark": {
      "tokens": {
        "layout": {
          "fontFamily": "ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif",
          "fontSize": 14,
          "fontWeight": 450,
          "lineHeight": 1.45,
          "textAlign": "left",
          "paddingX": 14,
          "paddingY": 10,
          "nodeMinWidth": 60,
          "nodeMinHeight": 40
        },
        "paint": {
          "bg": "#0e1219",
          "panel": "#151a24",
          "text": "#e6e9ef",
          "muted": "#c5cad4",
          "border": "rgba(197, 202, 212, 0.22)",
          "nodeFill": "#1a202b",
          "nodeFillSelected": "#303745",
          "nodeStroke": "transparent",
          "nodeStrokeSelected": "#dfe5f0",
          "edgeStroke": "#a9b0bd",
          "relationStroke": "#8bb4ff",
          "relationStrokeSelected": "#ffb4ab",
          "summaryStroke": "#525b6b"
        }
      },
      "edges": {
        "strokeWidth": 4,
        "cap": "round",
        "join": "round",
        "routeType": "orthogonal-rounded"
      },
      "relations": {
        "strokeWidth": 2,
        "cap": "round",
        "join": "round"
      },
      "nodeShape": {
        "type": "rounded-rect",
        "radius": 16,
        "strokeWidth": 0
      },
      "rainbow": {
        "enabled": false,
        "palette": [
          "#303745",
          "#1b5fa7",
          "#0ea5e9",
          "#14b8a6",
          "#22c55e",
          "#f59e0b",
          "#fb7185",
          "#a78bfa"
        ]
      },
      "background": {
        "color": "#0e1219"
      },
      "rules": {
        "nodeRules": [
          {
            "id": "m3-root",
            "priority": 10,
            "when": {
              "kind": "depth",
              "depth": 0
            },
            "apply": {
              "layout": {
                "textAlign": "center",
                "fontWeight": 700,
                "fontSize": 24,
                "paddingX": 18,
                "paddingY": 12
              },
              "paint": {
                "nodeFill": "#303745",
                "nodeFillSelected": "#3a4354",
                "text": "#f6f7fb"
              }
            }
          },
          {
            "id": "m3-depth-1",
            "priority": 10,
            "when": {
              "kind": "depth",
              "depth": 1
            },
            "apply": {
              "layout": {
                "fontWeight": 600,
                "fontSize": 18
              },
              "paint": {
                "nodeFill": "#242b37",
                "text": "#e6e9ef"
              },
              "incomingEdge": {
                "strokeColor": "#c5cad4",
                "routeType": "center-quadratic"
              }
            }
          },
          {
            "id": "m3-depth-2",
            "priority": 10,
            "when": {
              "kind": "depth",
              "depth": 2
            },
            "apply": {
              "paint": {
                "nodeFill": "#1a2435",
                "text": "#dce3f3"
              },
              "incomingEdge": {
                "strokeColor": "#8bb4ff"
              }
            }
          },
          {
            "id": "m3-depth-3plus",
            "priority": 10,
            "when": {
              "kind": "depthRange",
              "minDepth": 3
            },
            "apply": {
              "incomingEdge": {
                "strokeWidth": 1.75
              }
            }
          }
        ]
      }
    }
  }
};

// ../themes/src/themes/midnight-neon.ts
var midnightNeonTheme = {
  "schemaVersion": 1,
  "id": "kmind-midnight-neon",
  "name": "Midnight Neon",
  "variants": {
    "light": {
      "tokens": {
        "layout": {
          "fontFamily": "ui-sans-serif, system-ui, sans-serif",
          "fontSize": 14,
          "fontWeight": 400,
          "lineHeight": 1.4,
          "textAlign": "left",
          "paddingX": 12,
          "paddingY": 8,
          "nodeMinWidth": 60,
          "nodeMinHeight": 34
        },
        "paint": {
          "bg": "#070a14",
          "panel": "#0b1020",
          "text": "#e2e8f0",
          "muted": "#94a3b8",
          "border": "rgba(148, 163, 184, 0.18)",
          "nodeFill": "#0b1020",
          "nodeFillSelected": "rgba(56, 189, 248, 0.14)",
          "nodeStroke": "#a855f7",
          "nodeStrokeSelected": "#22c55e",
          "edgeStroke": "#a855f7",
          "relationStroke": "#f59e0b",
          "relationStrokeSelected": "#fb7185",
          "summaryStroke": "rgba(168, 85, 247, 0.65)"
        }
      },
      "edges": {
        "routeType": "center-quadratic-tapered",
        "strokeWidth": 4,
        "cap": "round",
        "join": "round"
      },
      "relations": {
        "strokeWidth": 2,
        "cap": "round",
        "join": "round"
      },
      "nodeShape": {
        "type": "rounded-rect",
        "radius": 14,
        "strokeWidth": 3
      },
      "rainbow": {
        "enabled": true,
        "palette": [
          "#ef4444",
          "#f97316",
          "#eab308",
          "#22c55e",
          "#06b6d4",
          "#3b82f6",
          "#8b5cf6",
          "#ec4899"
        ]
      },
      "rules": {
        "nodeRules": [
          {
            "id": "root",
            "priority": 10,
            "when": {
              "kind": "depth",
              "depth": 0
            },
            "apply": {
              "layout": {
                "fontSize": 24,
                "textAlign": "center",
                "fontWeight": 800
              }
            }
          },
          {
            "id": "first",
            "priority": 10,
            "when": {
              "kind": "depth",
              "depth": 1
            },
            "apply": {
              "layout": {
                "fontSize": 18,
                "fontWeight": 600
              }
            }
          }
        ]
      }
    },
    "dark": {
      "tokens": {
        "layout": {
          "fontFamily": "ui-sans-serif, system-ui, sans-serif",
          "fontSize": 14,
          "fontWeight": 400,
          "lineHeight": 1.4,
          "textAlign": "left",
          "paddingX": 12,
          "paddingY": 8,
          "nodeMinWidth": 60,
          "nodeMinHeight": 34
        },
        "paint": {
          "bg": "#070a14",
          "panel": "#0b1020",
          "text": "#e2e8f0",
          "muted": "#94a3b8",
          "border": "rgba(148, 163, 184, 0.18)",
          "nodeFill": "#0b1020",
          "nodeFillSelected": "rgba(56, 189, 248, 0.14)",
          "nodeStroke": "#a855f7",
          "nodeStrokeSelected": "#22c55e",
          "edgeStroke": "#a855f7",
          "relationStroke": "#f59e0b",
          "relationStrokeSelected": "#fb7185",
          "summaryStroke": "rgba(168, 85, 247, 0.65)"
        }
      },
      "edges": {
        "routeType": "center-quadratic-tapered",
        "strokeWidth": 4,
        "cap": "round",
        "join": "round"
      },
      "relations": {
        "strokeWidth": 2,
        "cap": "round",
        "join": "round"
      },
      "nodeShape": {
        "type": "rounded-rect",
        "radius": 14,
        "strokeWidth": 3
      },
      "rainbow": {
        "enabled": true,
        "palette": [
          "#ef4444",
          "#f97316",
          "#eab308",
          "#22c55e",
          "#06b6d4",
          "#3b82f6",
          "#8b5cf6",
          "#ec4899"
        ]
      },
      "rules": {
        "nodeRules": [
          {
            "id": "root",
            "priority": 10,
            "when": {
              "kind": "depth",
              "depth": 0
            },
            "apply": {
              "layout": {
                "fontSize": 24,
                "textAlign": "center"
              }
            }
          },
          {
            "id": "first",
            "priority": 10,
            "when": {
              "kind": "depth",
              "depth": 1
            },
            "apply": {
              "layout": {
                "fontSize": 18
              }
            }
          }
        ]
      }
    }
  }
};

// ../themes/src/themes/rainbow-breeze.ts
var rainbowBreezeTheme = {
  "schemaVersion": 1,
  "id": "kmind-rainbow-breeze",
  "name": "Rainbow Breeze",
  "variants": {
    "light": {
      "tokens": {
        "layout": {
          "fontFamily": "ui-sans-serif, system-ui, sans-serif",
          "fontSize": 14,
          "fontWeight": 400,
          "lineHeight": 1.4,
          "textAlign": "left",
          "paddingX": 12,
          "paddingY": 8,
          "nodeMinWidth": 60,
          "nodeMinHeight": 34
        },
        "paint": {
          "bg": "#f8fafc",
          "panel": "#ffffff",
          "text": "#0f172a",
          "muted": "#64748b",
          "border": "#e2e8f0",
          "nodeFill": "#ffffff",
          "nodeFillSelected": "rgba(14, 165, 233, 0.08)",
          "nodeStroke": "#0ea5e9",
          "nodeStrokeSelected": "#a78bfa",
          "edgeStroke": "#0ea5e9",
          "relationStroke": "#fb7185",
          "relationStrokeSelected": "#a78bfa",
          "summaryStroke": "rgba(14, 165, 233, 0.45)"
        }
      },
      "edges": {
        "routeType": "edge-lead-quadratic",
        "strokeWidth": 3,
        "cap": "round",
        "join": "round"
      },
      "relations": {
        "strokeWidth": 2,
        "cap": "round",
        "join": "round"
      },
      "nodeShape": {
        "type": "rounded-rect",
        "radius": 16,
        "strokeWidth": 2.5
      },
      "rainbow": {
        "enabled": true,
        "palette": [
          "#fb7185",
          "#f97316",
          "#fbbf24",
          "#34d399",
          "#22d3ee",
          "#60a5fa",
          "#a78bfa",
          "#f472b6"
        ]
      },
      "rules": {
        "nodeRules": [
          {
            "id": "root",
            "priority": 10,
            "when": {
              "kind": "depth",
              "depth": 0
            },
            "apply": {
              "layout": {
                "fontSize": 24,
                "fontWeight": 800,
                "textAlign": "center"
              },
              "paint": {
                "text": "#ffffff",
                "nodeFill": "#e53935",
                "nodeStroke": "transparent"
              }
            }
          },
          {
            "id": "first",
            "priority": 10,
            "when": {
              "kind": "depth",
              "depth": 1
            },
            "apply": {
              "layout": {
                "fontSize": 18,
                "fontWeight": 700
              }
            }
          }
        ]
      }
    },
    "dark": {
      "tokens": {
        "layout": {
          "fontFamily": "ui-sans-serif, system-ui, sans-serif",
          "fontSize": 14,
          "fontWeight": 400,
          "lineHeight": 1.4,
          "textAlign": "left",
          "paddingX": 12,
          "paddingY": 8,
          "nodeMinWidth": 60,
          "nodeMinHeight": 34
        },
        "paint": {
          "bg": "#0b1020",
          "panel": "#0f172a",
          "text": "#e2e8f0",
          "muted": "#94a3b8",
          "border": "rgba(148, 163, 184, 0.18)",
          "nodeFill": "#0f172a",
          "nodeFillSelected": "rgba(56, 189, 248, 0.16)",
          "nodeStroke": "#38bdf8",
          "nodeStrokeSelected": "#a78bfa",
          "edgeStroke": "#38bdf8",
          "relationStroke": "#fb7185",
          "relationStrokeSelected": "#a78bfa",
          "summaryStroke": "rgba(56, 189, 248, 0.55)"
        }
      },
      "edges": {
        "routeType": "edge-lead-quadratic",
        "strokeWidth": 3,
        "cap": "round",
        "join": "round"
      },
      "relations": {
        "strokeWidth": 2,
        "cap": "round",
        "join": "round"
      },
      "nodeShape": {
        "type": "rounded-rect",
        "radius": 16,
        "strokeWidth": 2.5
      },
      "rainbow": {
        "enabled": true,
        "palette": [
          "#fb7185",
          "#f97316",
          "#fbbf24",
          "#34d399",
          "#22d3ee",
          "#60a5fa",
          "#a78bfa",
          "#f472b6"
        ]
      },
      "rules": {
        "nodeRules": [
          {
            "id": "root",
            "priority": 10,
            "when": {
              "kind": "depth",
              "depth": 0
            },
            "apply": {
              "layout": {
                "fontSize": 24,
                "fontWeight": 800,
                "textAlign": "center"
              },
              "paint": {
                "text": "#ffffff",
                "nodeFill": "#e53935",
                "nodeStroke": "transparent"
              }
            }
          },
          {
            "id": "first",
            "priority": 10,
            "when": {
              "kind": "depth",
              "depth": 1
            },
            "apply": {
              "layout": {
                "fontSize": 18,
                "fontWeight": 700
              }
            }
          }
        ]
      }
    }
  }
};

// ../themes/src/presets.ts
var defaultTheme = createDefaultThemeDefinition();
var THEME_PRESETS = [
  { id: defaultTheme.id, name: defaultTheme.name, theme: defaultTheme },
  { id: material3SlateTheme.id, name: material3SlateTheme.name, theme: material3SlateTheme },
  { id: material3Theme.id, name: material3Theme.name, theme: material3Theme, visibility: { app: false } },
  { id: candyPopTheme.id, name: candyPopTheme.name, theme: candyPopTheme },
  { id: midnightNeonTheme.id, name: midnightNeonTheme.name, theme: midnightNeonTheme },
  { id: rainbowBreezeTheme.id, name: rainbowBreezeTheme.name, theme: rainbowBreezeTheme },
  { id: baselineForkInkTheme.id, name: baselineForkInkTheme.name, theme: baselineForkInkTheme, visibility: { app: false } },
  { id: material3RoundedOrthogonalVioletTheme.id, name: material3RoundedOrthogonalVioletTheme.name, theme: material3RoundedOrthogonalVioletTheme },
  { id: material3RoundedOrthogonalOceanTheme.id, name: material3RoundedOrthogonalOceanTheme.name, theme: material3RoundedOrthogonalOceanTheme },
  { id: material3RoundedOrthogonalForestTheme.id, name: material3RoundedOrthogonalForestTheme.name, theme: material3RoundedOrthogonalForestTheme },
  { id: material3RoundedOrthogonalCitrusTheme.id, name: material3RoundedOrthogonalCitrusTheme.name, theme: material3RoundedOrthogonalCitrusTheme },
  { id: material3RoundedOrthogonalRoseTheme.id, name: material3RoundedOrthogonalRoseTheme.name, theme: material3RoundedOrthogonalRoseTheme },
  { id: material3RoundedOrthogonalAquaTheme.id, name: material3RoundedOrthogonalAquaTheme.name, theme: material3RoundedOrthogonalAquaTheme }
];
var THEME_PRESETS_APP = THEME_PRESETS.filter((preset) => preset.visibility?.app !== false);

// ../app/src/services/project-settings-v1.ts
var ROOT_LAYOUT_SOURCE_KEY_V1 = "kmind.rootLayout.source.v1";

// ../app/src/utils/externalize-document-assets.ts
init_src();

// ../app/src/features/mindmap-feature.ts
init_src();

// ../app/src/services/document-zip-v1.ts
init_dist();
init_src();

// ../app/src/utils/crc32.ts
var CRC32_TABLE = (() => {
  const table = new Uint32Array(256);
  for (let i = 0; i < 256; i += 1) {
    let c = i;
    for (let k = 0; k < 8; k += 1) {
      c = c & 1 ? 3988292384 ^ c >>> 1 : c >>> 1;
    }
    table[i] = c >>> 0;
  }
  return table;
})();

// ../app/src/services/workspace-view-state-v1.ts
function makeWorkspaceCameraKeyV1(docId) {
  return `kmind:workspace:camera.v1:${docId}`;
}
function clampNumber2(value) {
  if (typeof value !== "number" || !Number.isFinite(value)) return null;
  return value;
}
function clampZoom(value) {
  const raw = clampNumber2(value);
  if (raw === null) return null;
  return Math.min(4, Math.max(0.1, raw));
}
function tryParseWorkspaceCameraV1(raw) {
  if (!raw) return null;
  try {
    const json = JSON.parse(raw);
    if (!json || json.schemaVersion !== 1) return null;
    const x5 = clampNumber2(json.x);
    const y = clampNumber2(json.y);
    const zoom = clampZoom(json.zoom);
    if (x5 === null || y === null || zoom === null) return null;
    const updatedAt = typeof json.updatedAt === "number" && Number.isFinite(json.updatedAt) ? json.updatedAt : Date.now();
    return { schemaVersion: 1, updatedAt, x: x5, y, zoom };
  } catch {
    return null;
  }
}
function writeWorkspaceCameraV1(storage, docId, camera) {
  const key = makeWorkspaceCameraKeyV1(docId);
  const payload = { schemaVersion: 1, updatedAt: Date.now(), x: camera.x, y: camera.y, zoom: camera.zoom };
  storage.setItem(key, JSON.stringify(payload));
}

// ../app/src/utils/image-package-v1.ts
var PNG_SIGNATURE = new Uint8Array([137, 80, 78, 71, 13, 10, 26, 10]);

// ../app/src/features/submap-feature.ts
init_src();

// ../app/src/features/node-content-feature.ts
init_src();

// ../app/src/utils/node-links.ts
init_src();

// ../app/src/features/node-clipboard-feature.ts
init_src();

// ../app/src/features/node-width-feature.ts
init_src();

// ../app/src/features/theme-feature.ts
init_src();

// ../app/src/themes/resolve-apply-target.ts
init_src();

// ../app/src/themes/theme-package-v1.ts
init_src();
var KMIND_THEME_PACKAGE_MAX_BYTES = 512 * 1024;

// ../app/src/features/layout-feature.ts
init_src();

// ../app/src/utils/node-layout.ts
var TIDY_ONLY_LAYOUTS = /* @__PURE__ */ new Set([
  "mindmap-both",
  "mindmap-both-auto",
  "timeline-right",
  "timeline-down",
  "fishbone-left",
  "fishbone-right"
]);
var ALL_LAYOUT_TYPES = [
  "logical-right",
  "logical-left",
  "tree-down",
  "tree-up",
  "mindmap-both",
  "mindmap-both-auto",
  "timeline-right",
  "timeline-down",
  "fishbone-left",
  "fishbone-right"
];
var ALLOWED_NODE_LAYOUTS_BY_DIRECTION = {
  right: ["logical-right", "tree-down", "tree-up", "timeline-right", "timeline-down", "fishbone-left"],
  left: ["logical-left", "tree-down", "tree-up", "timeline-down", "fishbone-right"],
  down: ["tree-down", "timeline-down"],
  up: ["tree-up"]
};
function isTidyOnlyLayout(layout) {
  return TIDY_ONLY_LAYOUTS.has(layout);
}
function resolveAllowedNodeLayouts(args) {
  if (args.direction === "unknown") {
    const merged = /* @__PURE__ */ new Set();
    for (const key of Object.keys(ALLOWED_NODE_LAYOUTS_BY_DIRECTION)) {
      for (const layout of ALLOWED_NODE_LAYOUTS_BY_DIRECTION[key]) merged.add(layout);
    }
    return Array.from(merged);
  }
  const allowed = ALLOWED_NODE_LAYOUTS_BY_DIRECTION[args.direction].slice();
  if (args.layoutEngine !== "tidy") return allowed.filter((layout) => !isTidyOnlyLayout(layout));
  return allowed;
}
function buildSummaryById(doc3) {
  return new Map(doc3.summaries.map((summary) => [summary.id, summary]));
}
function buildSummaryIdsByParent(doc3) {
  const map2 = /* @__PURE__ */ new Map();
  for (const summary of doc3.summaries) {
    const key = String(summary.parentId);
    const bucket = map2.get(key);
    if (bucket) bucket.push(summary.id);
    else map2.set(key, [summary.id]);
  }
  return map2;
}
function createMindmapBothAutoSideResolver(doc3, summaryById, summaryIdsByParent) {
  const isNodeCollapsed = (nodeId) => doc3.viewState?.collapsedNodeIds?.[nodeId] === true;
  const visibleSubtreeNodeCountMemo = /* @__PURE__ */ new Map();
  const countVisibleSubtreeNodes = (startNodeId) => {
    const cached = visibleSubtreeNodeCountMemo.get(startNodeId);
    if (cached !== void 0) return cached;
    const stack = [startNodeId];
    const visited = /* @__PURE__ */ new Set();
    let count = 0;
    while (stack.length > 0) {
      const current = stack.pop();
      if (!current) break;
      if (visited.has(current)) continue;
      visited.add(current);
      const node = doc3.nodes[current];
      if (node) {
        count += 1;
        const collapsed = isNodeCollapsed(node.id);
        if (!collapsed) {
          for (const childId of node.children) {
            if (!doc3.nodes[childId]) continue;
            stack.push(childId);
          }
          const nested = summaryIdsByParent.get(node.id);
          if (nested) {
            for (const summaryId of nested) stack.push(summaryId);
          }
        }
      }
      const summary = summaryById.get(current);
      if (summary) {
        for (const childId of summary.children) {
          if (!doc3.nodes[childId]) continue;
          stack.push(childId);
        }
        const nested = summaryIdsByParent.get(summary.id);
        if (nested) {
          for (const summaryId of nested) stack.push(summaryId);
        }
      }
    }
    visibleSubtreeNodeCountMemo.set(startNodeId, count);
    return count;
  };
  const mindmapBothAutoSideCache = /* @__PURE__ */ new Map();
  return (containerId, childId) => {
    const child = doc3.nodes[childId];
    if (child?.branchSide === "left") return "left";
    if (child?.branchSide === "right") return "right";
    let cached = mindmapBothAutoSideCache.get(containerId);
    if (!cached) {
      const container = doc3.nodes[containerId];
      const mapping = {};
      if (container) {
        let leftTotal = 0;
        let rightTotal = 0;
        const weightByChild = /* @__PURE__ */ new Map();
        const getWeight = (id) => {
          const existing = weightByChild.get(id);
          if (existing !== void 0) return existing;
          const weight = countVisibleSubtreeNodes(id);
          weightByChild.set(id, weight);
          return weight;
        };
        for (const id of container.children) {
          const node = doc3.nodes[id];
          if (!node) continue;
          const weight = getWeight(id);
          if (node.branchSide === "left") {
            mapping[id] = "left";
            leftTotal += weight;
          } else if (node.branchSide === "right") {
            mapping[id] = "right";
            rightTotal += weight;
          }
        }
        let tieFlip = "right";
        for (const id of container.children) {
          if (!doc3.nodes[id]) continue;
          if (mapping[id]) continue;
          const weight = getWeight(id);
          const side = leftTotal < rightTotal ? "left" : rightTotal < leftTotal ? "right" : tieFlip = tieFlip === "left" ? "right" : "left";
          mapping[id] = side;
          if (side === "left") leftTotal += weight;
          else rightTotal += weight;
        }
      }
      cached = mapping;
      mindmapBothAutoSideCache.set(containerId, cached);
    }
    return cached[childId] ?? "right";
  };
}
function resolveNodeContainerLayoutType(args) {
  const node = args.doc.nodes[args.nodeId];
  if (!node) return args.inheritedLayout;
  if (node.layout) return node.layout;
  if (args.inheritedLayout === "mindmap-both") return node.branchSide === "left" ? "logical-left" : "logical-right";
  if (args.inheritedLayout === "mindmap-both-auto") {
    const parentId = node.parentId;
    if (!parentId) return "logical-right";
    return args.resolveMindmapBothAutoSide(parentId, args.nodeId) === "left" ? "logical-left" : "logical-right";
  }
  if (args.inheritedLayout === "fishbone-left") return "logical-right";
  if (args.inheritedLayout === "fishbone-right") return "logical-left";
  return args.inheritedLayout;
}
function resolveSummaryContainerLayoutType(args) {
  const summary = args.summaryById.get(args.summaryId);
  if (!summary) return args.inheritedLayout;
  if (summary.layout) return summary.layout;
  if (args.inheritedLayout === "mindmap-both" || args.inheritedLayout === "mindmap-both-auto") return "logical-right";
  if (args.inheritedLayout === "fishbone-left") return "logical-right";
  if (args.inheritedLayout === "fishbone-right") return "logical-left";
  return args.inheritedLayout;
}
function resolveChildOutwardDirection(args) {
  const layout = args.containerLayout;
  if (layout === "logical-right" || layout === "timeline-right" || layout === "fishbone-left") return "right";
  if (layout === "logical-left" || layout === "fishbone-right") return "left";
  if (layout === "tree-down" || layout === "timeline-down") return "down";
  if (layout === "tree-up") return "up";
  if (layout === "mindmap-both") {
    const child = args.doc.nodes[args.childId];
    return child?.branchSide === "left" ? "left" : "right";
  }
  if (layout === "mindmap-both-auto") {
    const child = args.doc.nodes[args.childId];
    if (args.containerKind === "node") {
      return args.resolveMindmapBothAutoSide(args.containerId, args.childId) === "left" ? "left" : "right";
    }
    return child?.branchSide === "left" ? "left" : "right";
  }
  return "unknown";
}
function buildOutwardDirectionByNodeId(doc3) {
  const result = /* @__PURE__ */ new Map();
  const summaryById = buildSummaryById(doc3);
  const summaryIdsByParent = buildSummaryIdsByParent(doc3);
  const resolveMindmapBothAutoSide = createMindmapBothAutoSideResolver(doc3, summaryById, summaryIdsByParent);
  const visitedNodes = /* @__PURE__ */ new Set();
  const visitedSummaries = /* @__PURE__ */ new Set();
  const traverseSummaryContainer = (summaryId, inheritedLayout) => {
    if (visitedSummaries.has(summaryId)) return;
    visitedSummaries.add(summaryId);
    const summary = summaryById.get(summaryId);
    if (!summary) return;
    const containerLayout = resolveSummaryContainerLayoutType({ summaryId, inheritedLayout, summaryById });
    const nestedSummaries = summaryIdsByParent.get(summary.id) ?? [];
    for (const nestedId of nestedSummaries) {
      traverseSummaryContainer(nestedId, containerLayout);
    }
    for (const childId of summary.children) {
      if (!doc3.nodes[childId]) continue;
      result.set(
        childId,
        resolveChildOutwardDirection({
          doc: doc3,
          containerKind: "summary",
          containerId: summary.id,
          containerLayout,
          childId,
          resolveMindmapBothAutoSide
        })
      );
      traverseNodeContainer(childId, containerLayout);
    }
  };
  const traverseNodeContainer = (nodeId, inheritedLayout) => {
    if (visitedNodes.has(nodeId)) return;
    visitedNodes.add(nodeId);
    const node = doc3.nodes[nodeId];
    if (!node) return;
    const containerLayout = resolveNodeContainerLayoutType({ doc: doc3, nodeId, inheritedLayout, resolveMindmapBothAutoSide });
    const attachedSummaries = summaryIdsByParent.get(node.id) ?? [];
    for (const summaryId of attachedSummaries) {
      traverseSummaryContainer(summaryId, containerLayout);
    }
    for (const childId of node.children) {
      if (!doc3.nodes[childId]) continue;
      result.set(
        childId,
        resolveChildOutwardDirection({
          doc: doc3,
          containerKind: "node",
          containerId: node.id,
          containerLayout,
          childId,
          resolveMindmapBothAutoSide
        })
      );
      traverseNodeContainer(childId, containerLayout);
    }
  };
  for (const rootId of doc3.roots) {
    if (!doc3.nodes[rootId]) continue;
    traverseNodeContainer(rootId, "logical-right");
  }
  return result;
}

// ../app/src/features/context-menu-feature.ts
init_src();

// ../app/src/services/import-legacy-kmind.ts
init_src();

// ../app/src/services/import-builders.ts
init_src();

// ../app/src/services/import-xmind.ts
init_src();

// ../app/src/index.ts
init_src();
init_src();
init_src();

// ../app/src/themes/theme-designer-draft.ts
init_src();

// ../app/src/themes/theme-designer-descriptors.ts
var WEBAPP_OPEN_EDGE_ROUTE_TYPES = [
  "cubic",
  "quadratic",
  "center-quadratic",
  "center-quadratic-tapered",
  "edge-lead-quadratic",
  "edge-lead-quadratic-tapered",
  "straight",
  "orthogonal",
  "orthogonal-rounded",
  "tapered"
];
var THEME_DESIGNER_EDGE_ROUTE_LABELS = {
  cubic: "Cubic",
  quadratic: "Quadratic",
  "center-quadratic": "Center Quadratic",
  "center-quadratic-tapered": "Center Tapered",
  "edge-lead-quadratic": "Lead Quadratic",
  "edge-lead-quadratic-tapered": "Lead Tapered",
  straight: "Straight",
  orthogonal: "Orthogonal",
  "orthogonal-rounded": "Rounded Orthogonal",
  tapered: "Tapered"
};
var THEME_DESIGNER_EDGE_ROUTES = WEBAPP_OPEN_EDGE_ROUTE_TYPES.map((value) => ({
  value,
  label: THEME_DESIGNER_EDGE_ROUTE_LABELS[value]
}));

// ../app/src/services/markdown-headings.ts
function trimBlankLines(text5) {
  const lines = String(text5 ?? "").split(/\r?\n/);
  let start = 0;
  while (start < lines.length && lines[start]?.trim().length === 0) start += 1;
  let end = lines.length - 1;
  while (end >= start && lines[end]?.trim().length === 0) end -= 1;
  return lines.slice(start, end + 1).join("\n");
}
function buildNotesContent(body, args) {
  const trimmed = trimBlankLines(body);
  if (trimmed.length === 0) return null;
  const notes = {
    id: args.id,
    type: "notes",
    region: "right",
    order: 0,
    text: trimmed
  };
  return { schemaVersion: 1, kind: "blocks", blocks: [notes] };
}
function buildSubtreeFromMarkdownHeadings(markdown) {
  const lines = String(markdown ?? "").split(/\r?\n/);
  const sections = [];
  for (const rawLine of lines) {
    const line = String(rawLine ?? "");
    const match = /^(#{1,6})\s+(.*)$/.exec(line);
    if (!match) {
      const last = sections[sections.length - 1];
      if (last) last.bodyLines.push(line);
      continue;
    }
    const level = match[1]?.length ?? 0;
    const title = String(match[2] ?? "").trim();
    sections.push({ level, title, bodyLines: [] });
  }
  if (sections.length === 0) return null;
  const nodes = {};
  const roots = [];
  const stack = [];
  for (let i = 0; i < sections.length; i += 1) {
    const section = sections[i];
    const id = `md_${i + 1}`;
    const content = buildNotesContent(section.bodyLines.join("\n"), { id: `notes_${i + 1}` });
    const targetStackLength = Math.max(0, section.level - 1);
    stack.splice(targetStackLength);
    const parentId = stack[targetStackLength - 1] ?? null;
    nodes[id] = {
      id,
      children: [],
      text: section.title,
      content: content ?? void 0,
      parentId: parentId ?? void 0
    };
    if (parentId) {
      const parent = nodes[parentId];
      if (parent) parent.children.push(id);
    } else {
      roots.push(id);
    }
    stack[targetStackLength] = id;
  }
  return { roots, nodes };
}

// ../app/src/services/keymap-overrides.ts
function resolveEffectiveCombos(binding, overrides) {
  if (!overrides) return binding.combos;
  if (!Object.prototype.hasOwnProperty.call(overrides, binding.id)) return binding.combos;
  return overrides[binding.id] ?? [];
}
function resolveEffectiveKeymap(bindings, overrides) {
  if (!overrides || Object.keys(overrides).length === 0) return bindings;
  return bindings.map((binding) => ({ ...binding, combos: resolveEffectiveCombos(binding, overrides) }));
}
function stableStringifyValue(value) {
  if (value === void 0) return "";
  try {
    return JSON.stringify(value, (_key, nested) => {
      if (!nested || typeof nested !== "object" || Array.isArray(nested)) return nested;
      return Object.fromEntries(Object.entries(nested).sort(([a2], [b2]) => a2.localeCompare(b2)));
    });
  } catch {
    return "";
  }
}
function resolveCommandKeymapLabel(args) {
  const effective = resolveEffectiveKeymap(args.bindings, args.overrides);
  const requestedArgs = stableStringifyValue(args.commandArgs);
  const candidates = effective.filter((binding) => binding.commandId === args.commandId);
  const exact = candidates.find((binding) => stableStringifyValue(binding.args) === requestedArgs && binding.combos.length > 0);
  const fallback = exact ?? candidates.find((binding) => binding.args === void 0 && binding.combos.length > 0) ?? candidates.find((binding) => binding.combos.length > 0);
  if (!fallback) return null;
  const label = formatKeyCombos(fallback.combos);
  return label || null;
}
function formatKeyCombo(combo) {
  const parts = [];
  if (combo.ctrl) parts.push("Ctrl");
  if (combo.meta) parts.push("Cmd");
  if (combo.shift) parts.push("Shift");
  if (combo.alt) parts.push("Alt");
  const key = typeof combo.key === "string" && combo.key.trim().length > 0 ? combo.key : formatKeyCode(combo.code);
  if (key) parts.push(String(key));
  return parts.join("+");
}
function formatKeyCode(code) {
  if (typeof code !== "string" || code.trim().length === 0) return void 0;
  if (/^Key[A-Z]$/.test(code)) return code.slice(3);
  if (/^Digit[0-9]$/.test(code)) return code.slice(5);
  return code;
}
function formatKeyCombos(combos) {
  const parts = combos.map(formatKeyCombo).filter(Boolean);
  return parts.length > 0 ? parts.join(" / ") : "";
}

// ../app/src/services/outline-projection-v1.ts
init_src();

// ../app/src/services/node-ref-resolver.ts
init_src();

// ../app/src/services/import-debug.ts
init_src();

// ../react/src/i18n-messages.ts
var KMIND_REACT_MESSAGES = {
  "en-US": {
    "editor.selectionToolbar.button.link": "Link",
    "editor.selectionToolbar.button.image": "Image",
    "editor.selectionToolbar.button.brush": "Brush",
    "editor.selectionToolbar.button.icons": "Icons",
    "editor.selectionToolbar.button.tags": "Tags",
    "editor.selectionToolbar.button.notes": "Notes",
    "editor.selectionToolbar.button.comments": "Comments",
    "editor.selectionToolbar.cursor.relation": "Relation",
    "editor.selectionToolbar.cursor.backlinkPick": "Backlink pick",
    "editor.summaryBubble.relation.start": "Relation",
    "editor.summaryBubble.relation.picking": "Pick target",
    "editor.summary.edit.readonly": "This summary is locked/read-only and cannot be edited.",
    "editor.summary.create.error.rootUnsupported": "Root nodes cannot create summaries. Select non-root siblings in the same parent container.",
    "editor.summary.create.error.siblingContainerRequired": "Create a summary from sibling nodes in the same parent container. Selecting endpoints is supported; the range expands automatically.",
    "editor.relationBubble.label": "Relation label",
    "editor.relationBubble.label.placeholder": "Enter text",
    "editor.relationBubble.direction": "Arrow",
    "editor.relationBubble.direction.inherit": "Default",
    "editor.relationBubble.direction.none": "No arrow",
    "editor.relationBubble.direction.forward": "Forward arrow",
    "editor.relationBubble.direction.backward": "Backward arrow",
    "editor.relationBubble.direction.both": "Two-way arrow",
    "editor.relationBubble.color": "Color",
    "editor.relationBubble.dash": "Line style",
    "editor.relationBubble.dash.inherit": "Default",
    "editor.relationBubble.dash.solid": "Solid",
    "editor.relationBubble.dash.dashed": "Dashed",
    "editor.relationBubble.dash.dotted": "Dotted",
    "editor.relationBubble.width": "Width",
    "editor.relationBubble.width.default": "Default",
    "editor.relationBubble.width.hairline": "Hairline",
    "editor.relationBubble.width.thin": "Thin",
    "editor.relationBubble.width.regular": "Regular",
    "editor.relationBubble.width.bold": "Bold",
    "editor.relationBubble.width.heavy": "Heavy",
    "editor.relationBubble.width.extraHeavy": "Extra bold",
    "editor.relationBubble.inherit": "Default",
    "editor.relationBubble.reset": "Reset relation style",
    "editor.relationBubble.delete": "Delete relation",
    "editor.selectionToolbar.formatPainter.hint": "Format brush (Esc)",
    "editor.drag.groupHint.nodes": "{count} nodes",
    "editor.viewModes.hint.zen": "Zen mode",
    "editor.viewModes.hint.readOnly": "Read-only mode",
    "editor.viewModes.badge.title": "Modes",
    "editor.viewModes.action.dismiss": "Dismiss",
    "editor.meta.title.notes": "Notes",
    "editor.meta.title.comments": "Comments",
    "editor.meta.action.edit": "Edit",
    "editor.meta.action.close": "Close",
    "editor.meta.action.cancel": "Cancel",
    "editor.meta.action.save": "Save",
    "editor.meta.notes.empty": "No notes",
    "editor.meta.notes.action.clear": "Clear",
    "editor.meta.notes.action.save": "Save",
    "editor.meta.comments.empty": "No comments",
    "editor.meta.comments.action.delete": "Delete",
    "editor.meta.comments.placeholder.new": "Add comment\u2026",
    "editor.meta.comments.action.clearAll": "Clear all",
    "editor.meta.comments.action.add": "Add",
    "editor.changeTheme.section.layout": "Layout",
    "editor.changeTheme.section.reset": "Reset",
    "editor.changeTheme.section.edgeRoute": "Edge Route",
    "editor.changeTheme.section.edgeStyle": "Edge Style",
    "editor.changeTheme.section.edgeWidth": "Edge Width",
    "editor.changeTheme.section.theme": "Theme",
    "editor.changeTheme.option.inherit": "Inherit",
    "editor.changeTheme.action.clearChildLayouts": "Clear child layouts",
    "editor.changeTheme.rainbowEdges": "Rainbow edges",
    "editor.changeTheme.toggle.on": "On",
    "editor.changeTheme.toggle.off": "Off",
    "editor.changeTheme.edgeStyle.solid": "Solid",
    "editor.changeTheme.edgeStyle.dashed": "Dashed",
    "kmind.label.layout.logical-right": "Right logic",
    "kmind.label.layout.logical-left": "Left logic",
    "kmind.label.layout.tree-down": "Tree down",
    "kmind.label.layout.tree-up": "Tree up",
    "kmind.label.layout.mindmap-both": "Mind map both sides",
    "kmind.label.layout.mindmap-both-auto": "Auto balanced mind map",
    "kmind.label.layout.timeline-right": "Right timeline",
    "kmind.label.layout.timeline-down": "Vertical timeline",
    "kmind.label.layout.fishbone-left": "Left fishbone",
    "kmind.label.layout.fishbone-right": "Right fishbone",
    "kmind.label.edgeRoute.cubic": "Smooth curve",
    "kmind.label.edgeRoute.quadratic": "Soft curve",
    "kmind.label.edgeRoute.center-quadratic": "Center arc",
    "kmind.label.edgeRoute.center-quadratic-tapered": "Center arc \xB7 tapered",
    "kmind.label.edgeRoute.edge-lead-quadratic": "Edge arc",
    "kmind.label.edgeRoute.edge-lead-quadratic-tapered": "Edge arc \xB7 tapered",
    "kmind.label.edgeRoute.cubic-tail": "Tail curve",
    "kmind.label.edgeRoute.baseline-fork": "Baseline fork",
    "kmind.label.edgeRoute.straight": "Straight line",
    "kmind.label.edgeRoute.orthogonal": "Orthogonal",
    "kmind.label.edgeRoute.orthogonal-rounded": "Rounded orthogonal",
    "kmind.label.edgeRoute.tapered": "Tapered curve",
    "kmind.label.theme.kmind-default": "KMind Default",
    "kmind.label.theme.kmind-material-3-slate": "KMind Slate",
    "kmind.label.theme.kmind-material-3": "Material 3 Basic",
    "kmind.label.theme.kmind-candy-pop": "Candy Pop",
    "kmind.label.theme.kmind-midnight-neon": "Midnight Neon",
    "kmind.label.theme.kmind-rainbow-breeze": "Rainbow Breeze",
    "kmind.label.theme.kmind-baseline-fork-ink": "Baseline Fork \xB7 Ink",
    "kmind.label.theme.kmind-material-3-rounded-orthogonal-violet": "Violet",
    "kmind.label.theme.kmind-material-3-rounded-orthogonal-ocean": "Ocean",
    "kmind.label.theme.kmind-material-3-rounded-orthogonal-forest": "Forest",
    "kmind.label.theme.kmind-material-3-rounded-orthogonal-citrus": "Citrus",
    "kmind.label.theme.kmind-material-3-rounded-orthogonal-rose": "Rose",
    "kmind.label.theme.kmind-material-3-rounded-orthogonal-aqua": "Aqua",
    "editor.nodeStyle.action.reset": "Reset",
    "editor.nodeStyle.preview.title": "Preview",
    "editor.nodeStyle.preview.nodeLabel": "Node",
    "editor.nodeStyle.section.text": "Text",
    "editor.nodeStyle.text.fontSize.inherit": "Inherit ({size}px)",
    "editor.nodeStyle.text.fontWeight.inherit": "Inherit ({weight})",
    "editor.nodeStyle.text.fontWeight.normal": "Normal",
    "editor.nodeStyle.text.fontWeight.bold": "Bold",
    "editor.nodeStyle.text.align.inherit": "Inherit ({align})",
    "editor.nodeStyle.text.align.left": "Left",
    "editor.nodeStyle.text.align.center": "Center",
    "editor.nodeStyle.text.align.right": "Right",
    "editor.nodeStyle.text.color.inherit": "Inherit",
    "editor.nodeStyle.section.shape": "Shape",
    "editor.nodeStyle.shape.rounded": "Rounded",
    "editor.nodeStyle.shape.rect": "Rect",
    "editor.nodeStyle.shape.diamond": "Diamond",
    "editor.nodeStyle.shape.ellipse": "Ellipse",
    "editor.nodeStyle.shape.pill": "Pill",
    "editor.nodeStyle.section.border": "Border",
    "editor.nodeStyle.border.solid": "Solid",
    "editor.nodeStyle.border.dashed": "Dashed",
    "editor.nodeStyle.border.width": "Width",
    "editor.nodeStyle.border.width.aria": "Border width",
    "editor.nodeStyle.border.clear": "Clear",
    "editor.nodeStyle.section.background": "Background",
    "editor.nodeStyle.background.clear": "Clear",
    "editor.nodeStyle.section.scope": "Scope",
    "editor.nodeStyle.scope.applyToSiblings": "Apply to siblings",
    "editor.image.title": "Image",
    "editor.image.empty": "No image in this node.",
    "editor.image.action.insert": "Insert image",
    "editor.image.hint.pasteReplace": "Tip: you can also paste an image to replace.",
    "editor.image.action.replace": "Replace",
    "editor.image.action.delete": "Delete",
    "editor.image.action.reset": "Reset",
    "editor.image.action.preview": "Preview",
    "editor.image.section.position": "Position",
    "editor.image.position.top": "Top",
    "editor.image.position.bottom": "Bottom",
    "editor.image.position.left": "Left",
    "editor.image.position.right": "Right",
    "editor.image.section.fit": "Fit",
    "editor.image.fit.contain": "Contain",
    "editor.image.fit.cover": "Cover",
    "editor.image.section.size": "Size",
    "editor.image.hint.dragResize": "Drag to resize (keeps aspect ratio).",
    "editor.image.lightbox.fallbackTitle": "Image",
    "editor.image.lightbox.close": "Close",
    "editor.icons.title": "Icons",
    "editor.icons.lockedReadonly": "This node is locked/readonly.",
    "editor.icons.slot": "Slot {index}",
    "editor.icons.action.addPlaceholder": "Add icon\u2026",
    "editor.icons.hint.max3": "Max 3 icons.",
    "editor.icons.action.clearAll": "Clear all",
    "editor.icons.action.clearSlot": "Clear slot",
    "editor.icons.picker.title": "Pick icon (Slot {index})",
    "editor.icons.picker.close": "Close",
    "editor.tags.title": "Tags",
    "editor.tags.empty": "No tags",
    "editor.tags.input.placeholder": "Add tag\u2026",
    "editor.tags.action.add": "Add",
    "editor.links.title": "Links",
    "editor.links.action.edit": "Edit",
    "editor.links.action.preview": "Preview",
    "editor.links.action.done": "Done",
    "editor.links.action.copyLink": "Copy Link",
    "editor.links.action.copyId": "Copy ID",
    "editor.links.action.copied": "Copied",
    "editor.links.action.close": "Close",
    "editor.links.action.cleanBroken": "Clean broken",
    "editor.links.section.add": "Add links",
    "editor.links.section.outgoing": "Outgoing ({count})",
    "editor.links.section.backlinks": "Backlinks ({count})",
    "editor.links.section.external": "External ({count})",
    "editor.links.empty": "No links",
    "editor.links.status.broken": "Broken",
    "editor.links.status.unknown": "Unknown",
    "editor.links.add.icon": "Icon",
    "editor.links.add.external.url.placeholder": "External url\u2026",
    "editor.links.add.external.action": "Add external",
    "editor.links.add.external.label.placeholder": "External label (optional)\u2026",
    "editor.links.add.internal.target.placeholder": "Internal nodeId / kmind-node://\u2026",
    "editor.links.add.internal.action": "Add internal",
    "editor.links.add.internal.label.placeholder": "Internal label (optional)\u2026",
    "editor.links.external.action.open": "Open",
    "editor.links.external.action.openRight": "Open in right tab",
    "editor.links.external.action.openBottom": "Open in bottom tab",
    "editor.links.external.edit.url.placeholder": "URL",
    "editor.links.external.edit.label.placeholder": "Label (optional)",
    "editor.links.iconPicker.title": "Pick icon",
    "editor.links.iconPicker.action.close": "Close",
    "editor.links.iconPicker.action.auto": "Auto",
    "editor.links.iconPicker.action.clear": "Clear",
    "editor.links.alert.clipboardUnavailable": "Clipboard write is not supported in this host.",
    "editor.links.alert.copyFailed": "Copy failed.",
    "editor.links.alert.crossDocUnavailable": "Cross-document navigation is not supported in this host."
  },
  "zh-CN": {
    "editor.selectionToolbar.button.link": "\u94FE\u63A5",
    "editor.selectionToolbar.button.image": "\u56FE\u7247",
    "editor.selectionToolbar.button.brush": "\u683C\u5F0F\u5237",
    "editor.selectionToolbar.button.icons": "\u56FE\u6807",
    "editor.selectionToolbar.button.tags": "\u6807\u7B7E",
    "editor.selectionToolbar.button.notes": "\u5907\u6CE8",
    "editor.selectionToolbar.button.comments": "\u6279\u6CE8",
    "editor.selectionToolbar.cursor.relation": "\u5173\u8054\u7EBF",
    "editor.selectionToolbar.cursor.backlinkPick": "\u53CC\u94FE\u9009\u62E9",
    "editor.summaryBubble.relation.start": "\u5173\u8054\u7EBF",
    "editor.summaryBubble.relation.picking": "\u9009\u62E9\u76EE\u6807",
    "editor.summary.edit.readonly": "\u8BE5\u6982\u8981\u5DF2\u9501\u5B9A/\u53EA\u8BFB\uFF0C\u65E0\u6CD5\u7F16\u8F91\u3002",
    "editor.summary.create.error.rootUnsupported": "Root \u8282\u70B9\u4E0D\u652F\u6301\u521B\u5EFA\u6982\u8981\uFF0C\u8BF7\u9009\u62E9\u540C\u4E00\u7236\u5BB9\u5668\u4E0B\u7684\u975E Root \u5144\u5F1F\u8282\u70B9\u3002",
    "editor.summary.create.error.siblingContainerRequired": "\u521B\u5EFA\u6982\u8981\u9700\u8981\u9009\u62E9\u540C\u4E00\u7236\u5BB9\u5668\u4E0B\u7684\u5144\u5F1F\u8282\u70B9\uFF08\u652F\u6301\u9009\u62E9\u7AEF\u70B9\uFF0C\u8303\u56F4\u4F1A\u81EA\u52A8\u6269\u5F20\uFF09\u3002",
    "editor.relationBubble.label": "\u5173\u8054\u7EBF\u6807\u7B7E",
    "editor.relationBubble.label.placeholder": "\u8BF7\u8F93\u5165\u6587\u672C",
    "editor.relationBubble.direction": "\u7BAD\u5934",
    "editor.relationBubble.direction.inherit": "\u9ED8\u8BA4",
    "editor.relationBubble.direction.none": "\u65E0\u7BAD\u5934",
    "editor.relationBubble.direction.forward": "\u5355\u5411\u7BAD\u5934",
    "editor.relationBubble.direction.backward": "\u53CD\u5411\u7BAD\u5934",
    "editor.relationBubble.direction.both": "\u53CC\u5411\u7BAD\u5934",
    "editor.relationBubble.color": "\u989C\u8272",
    "editor.relationBubble.dash": "\u7EBF\u578B",
    "editor.relationBubble.dash.inherit": "\u9ED8\u8BA4",
    "editor.relationBubble.dash.solid": "\u5B9E\u7EBF",
    "editor.relationBubble.dash.dashed": "\u865A\u7EBF",
    "editor.relationBubble.dash.dotted": "\u70B9\u7EBF",
    "editor.relationBubble.width": "\u7EBF\u5BBD",
    "editor.relationBubble.width.default": "\u9ED8\u8BA4",
    "editor.relationBubble.width.hairline": "\u6781\u7EC6",
    "editor.relationBubble.width.thin": "\u7EC6",
    "editor.relationBubble.width.regular": "\u5E38\u89C4",
    "editor.relationBubble.width.bold": "\u7C97",
    "editor.relationBubble.width.heavy": "\u5F88\u7C97",
    "editor.relationBubble.width.extraHeavy": "\u52A0\u7C97",
    "editor.relationBubble.inherit": "\u9ED8\u8BA4",
    "editor.relationBubble.reset": "\u91CD\u7F6E\u5173\u8054\u7EBF\u6837\u5F0F",
    "editor.relationBubble.delete": "\u5220\u9664\u5173\u8054\u7EBF",
    "editor.selectionToolbar.formatPainter.hint": "\u683C\u5F0F\u5237\uFF08Esc\uFF09",
    "editor.drag.groupHint.nodes": "{count} \u4E2A\u8282\u70B9",
    "editor.viewModes.hint.zen": "\u7985\u6A21\u5F0F",
    "editor.viewModes.hint.readOnly": "\u53EA\u8BFB\u6A21\u5F0F",
    "editor.viewModes.badge.title": "\u6A21\u5F0F",
    "editor.viewModes.action.dismiss": "\u77E5\u9053\u4E86",
    "editor.meta.title.notes": "\u5907\u6CE8",
    "editor.meta.title.comments": "\u6279\u6CE8",
    "editor.meta.action.edit": "\u7F16\u8F91",
    "editor.meta.action.close": "\u5173\u95ED",
    "editor.meta.action.cancel": "\u53D6\u6D88",
    "editor.meta.action.save": "\u4FDD\u5B58",
    "editor.meta.notes.empty": "\u6682\u65E0\u5907\u6CE8",
    "editor.meta.notes.action.clear": "\u6E05\u7A7A",
    "editor.meta.notes.action.save": "\u4FDD\u5B58",
    "editor.meta.comments.empty": "\u6682\u65E0\u6279\u6CE8",
    "editor.meta.comments.action.delete": "\u5220\u9664",
    "editor.meta.comments.placeholder.new": "\u65B0\u589E\u6279\u6CE8\u2026",
    "editor.meta.comments.action.clearAll": "\u6E05\u7A7A\u5168\u90E8",
    "editor.meta.comments.action.add": "\u6DFB\u52A0",
    "editor.changeTheme.section.layout": "\u5E03\u5C40",
    "editor.changeTheme.section.reset": "\u91CD\u7F6E",
    "editor.changeTheme.section.edgeRoute": "\u8FDE\u7EBF\u8DEF\u7531",
    "editor.changeTheme.section.edgeStyle": "\u8FDE\u7EBF\u6837\u5F0F",
    "editor.changeTheme.section.edgeWidth": "\u8FDE\u7EBF\u5BBD\u5EA6",
    "editor.changeTheme.section.theme": "\u4E3B\u9898",
    "editor.changeTheme.option.inherit": "\u7EE7\u627F",
    "editor.changeTheme.action.clearChildLayouts": "\u6E05\u9664\u5B50\u8282\u70B9\u5E03\u5C40",
    "editor.changeTheme.rainbowEdges": "\u5F69\u8679\u8FDE\u7EBF",
    "editor.changeTheme.toggle.on": "\u5F00",
    "editor.changeTheme.toggle.off": "\u5173",
    "editor.changeTheme.edgeStyle.solid": "\u5B9E\u7EBF",
    "editor.changeTheme.edgeStyle.dashed": "\u865A\u7EBF",
    "kmind.label.layout.logical-right": "\u53F3\u5411\u903B\u8F91\u56FE",
    "kmind.label.layout.logical-left": "\u5DE6\u5411\u903B\u8F91\u56FE",
    "kmind.label.layout.tree-down": "\u5411\u4E0B\u6811\u72B6\u56FE",
    "kmind.label.layout.tree-up": "\u5411\u4E0A\u6811\u72B6\u56FE",
    "kmind.label.layout.mindmap-both": "\u53CC\u5411\u601D\u7EF4\u5BFC\u56FE",
    "kmind.label.layout.mindmap-both-auto": "\u81EA\u52A8\u53CC\u5411\u601D\u7EF4\u5BFC\u56FE",
    "kmind.label.layout.timeline-right": "\u53F3\u5411\u65F6\u95F4\u7EBF",
    "kmind.label.layout.timeline-down": "\u7EB5\u5411\u65F6\u95F4\u7EBF",
    "kmind.label.layout.fishbone-left": "\u5DE6\u5411\u9C7C\u9AA8\u56FE",
    "kmind.label.layout.fishbone-right": "\u53F3\u5411\u9C7C\u9AA8\u56FE",
    "kmind.label.edgeRoute.cubic": "\u5E73\u6ED1\u66F2\u7EBF",
    "kmind.label.edgeRoute.quadratic": "\u67D4\u548C\u66F2\u7EBF",
    "kmind.label.edgeRoute.center-quadratic": "\u4E2D\u5FC3\u5F27\u7EBF",
    "kmind.label.edgeRoute.center-quadratic-tapered": "\u4E2D\u5FC3\u5F27\u7EBF \xB7 \u6E10\u7EC6",
    "kmind.label.edgeRoute.edge-lead-quadratic": "\u8FB9\u7F18\u5F27\u7EBF",
    "kmind.label.edgeRoute.edge-lead-quadratic-tapered": "\u8FB9\u7F18\u5F27\u7EBF \xB7 \u6E10\u7EC6",
    "kmind.label.edgeRoute.cubic-tail": "\u62D6\u5C3E\u66F2\u7EBF",
    "kmind.label.edgeRoute.baseline-fork": "\u57FA\u7EBF\u5206\u53C9",
    "kmind.label.edgeRoute.straight": "\u76F4\u7EBF",
    "kmind.label.edgeRoute.orthogonal": "\u76F4\u89D2\u6298\u7EBF",
    "kmind.label.edgeRoute.orthogonal-rounded": "\u5706\u89D2\u6298\u7EBF",
    "kmind.label.edgeRoute.tapered": "\u6E10\u7EC6\u66F2\u7EBF",
    "kmind.label.theme.kmind-default": "KMind \u9ED8\u8BA4",
    "kmind.label.theme.kmind-material-3-slate": "KMind \u84DD\u7070",
    "kmind.label.theme.kmind-material-3": "Material 3 \u57FA\u7840",
    "kmind.label.theme.kmind-candy-pop": "\u7CD6\u679C\u6CE1\u6CE1",
    "kmind.label.theme.kmind-midnight-neon": "\u5348\u591C\u9713\u8679",
    "kmind.label.theme.kmind-rainbow-breeze": "\u5F69\u8679\u5FAE\u98CE",
    "kmind.label.theme.kmind-baseline-fork-ink": "\u57FA\u7EBF\u5206\u53C9 \xB7 \u58A8\u7EBF",
    "kmind.label.theme.kmind-material-3-rounded-orthogonal-violet": "\u7D2B\u7F57\u5170",
    "kmind.label.theme.kmind-material-3-rounded-orthogonal-ocean": "\u6D77\u6D0B",
    "kmind.label.theme.kmind-material-3-rounded-orthogonal-forest": "\u68EE\u6797",
    "kmind.label.theme.kmind-material-3-rounded-orthogonal-citrus": "\u67D1\u6A58",
    "kmind.label.theme.kmind-material-3-rounded-orthogonal-rose": "\u73AB\u7470",
    "kmind.label.theme.kmind-material-3-rounded-orthogonal-aqua": "\u6C34\u9752",
    "editor.nodeStyle.action.reset": "\u91CD\u7F6E",
    "editor.nodeStyle.preview.title": "\u9884\u89C8",
    "editor.nodeStyle.preview.nodeLabel": "\u8282\u70B9",
    "editor.nodeStyle.section.text": "\u6587\u672C",
    "editor.nodeStyle.text.fontSize.inherit": "\u7EE7\u627F\uFF08{size}px\uFF09",
    "editor.nodeStyle.text.fontWeight.inherit": "\u7EE7\u627F\uFF08{weight}\uFF09",
    "editor.nodeStyle.text.fontWeight.normal": "\u5E38\u89C4",
    "editor.nodeStyle.text.fontWeight.bold": "\u52A0\u7C97",
    "editor.nodeStyle.text.align.inherit": "\u7EE7\u627F\uFF08{align}\uFF09",
    "editor.nodeStyle.text.align.left": "\u5DE6\u5BF9\u9F50",
    "editor.nodeStyle.text.align.center": "\u5C45\u4E2D",
    "editor.nodeStyle.text.align.right": "\u53F3\u5BF9\u9F50",
    "editor.nodeStyle.text.color.inherit": "\u7EE7\u627F",
    "editor.nodeStyle.section.shape": "\u5F62\u72B6",
    "editor.nodeStyle.shape.rounded": "\u5706\u89D2",
    "editor.nodeStyle.shape.rect": "\u77E9\u5F62",
    "editor.nodeStyle.shape.diamond": "\u83F1\u5F62",
    "editor.nodeStyle.shape.ellipse": "\u692D\u5706",
    "editor.nodeStyle.shape.pill": "\u80F6\u56CA",
    "editor.nodeStyle.section.border": "\u8FB9\u6846",
    "editor.nodeStyle.border.solid": "\u5B9E\u7EBF",
    "editor.nodeStyle.border.dashed": "\u865A\u7EBF",
    "editor.nodeStyle.border.width": "\u5BBD\u5EA6",
    "editor.nodeStyle.border.width.aria": "\u8FB9\u6846\u5BBD\u5EA6",
    "editor.nodeStyle.border.clear": "\u6E05\u9664",
    "editor.nodeStyle.section.background": "\u80CC\u666F",
    "editor.nodeStyle.background.clear": "\u6E05\u9664",
    "editor.nodeStyle.section.scope": "\u4F5C\u7528\u8303\u56F4",
    "editor.nodeStyle.scope.applyToSiblings": "\u5E94\u7528\u5230\u540C\u7EA7\u8282\u70B9",
    "editor.image.title": "\u56FE\u7247",
    "editor.image.empty": "\u8BE5\u8282\u70B9\u6682\u65E0\u56FE\u7247\u3002",
    "editor.image.action.insert": "\u63D2\u5165\u56FE\u7247",
    "editor.image.hint.pasteReplace": "\u63D0\u793A\uFF1A\u4E5F\u53EF\u4EE5\u76F4\u63A5\u7C98\u8D34\u56FE\u7247\u6765\u66FF\u6362\u3002",
    "editor.image.action.replace": "\u66FF\u6362",
    "editor.image.action.delete": "\u5220\u9664",
    "editor.image.action.reset": "\u91CD\u7F6E",
    "editor.image.action.preview": "\u9884\u89C8",
    "editor.image.section.position": "\u4F4D\u7F6E",
    "editor.image.position.top": "\u4E0A",
    "editor.image.position.bottom": "\u4E0B",
    "editor.image.position.left": "\u5DE6",
    "editor.image.position.right": "\u53F3",
    "editor.image.section.fit": "\u9002\u914D",
    "editor.image.fit.contain": "\u5305\u542B",
    "editor.image.fit.cover": "\u8986\u76D6",
    "editor.image.section.size": "\u5C3A\u5BF8",
    "editor.image.hint.dragResize": "\u62D6\u52A8\u8C03\u6574\u5927\u5C0F\uFF08\u4FDD\u6301\u5BBD\u9AD8\u6BD4\uFF09\u3002",
    "editor.image.lightbox.fallbackTitle": "\u56FE\u7247",
    "editor.image.lightbox.close": "\u5173\u95ED",
    "editor.icons.title": "\u56FE\u6807",
    "editor.icons.lockedReadonly": "\u8BE5\u8282\u70B9\u4E3A locked/readonly\u3002",
    "editor.icons.slot": "\u69FD\u4F4D {index}",
    "editor.icons.action.addPlaceholder": "\u6DFB\u52A0\u56FE\u6807\u2026",
    "editor.icons.hint.max3": "\u6700\u591A 3 \u4E2A\u56FE\u6807\u3002",
    "editor.icons.action.clearAll": "\u6E05\u9664\u5168\u90E8",
    "editor.icons.action.clearSlot": "\u6E05\u9664\u69FD\u4F4D",
    "editor.icons.picker.title": "\u9009\u62E9\u56FE\u6807\uFF08\u69FD\u4F4D {index}\uFF09",
    "editor.icons.picker.close": "\u5173\u95ED",
    "editor.tags.title": "\u6807\u7B7E",
    "editor.tags.empty": "\u6682\u65E0\u6807\u7B7E",
    "editor.tags.input.placeholder": "\u6DFB\u52A0\u6807\u7B7E\u2026",
    "editor.tags.action.add": "\u6DFB\u52A0",
    "editor.links.title": "\u94FE\u63A5",
    "editor.links.action.edit": "\u7F16\u8F91",
    "editor.links.action.preview": "\u9884\u89C8",
    "editor.links.action.done": "\u5B8C\u6210",
    "editor.links.action.copyLink": "\u590D\u5236\u94FE\u63A5",
    "editor.links.action.copyId": "\u590D\u5236 ID",
    "editor.links.action.copied": "\u5DF2\u590D\u5236",
    "editor.links.action.close": "\u5173\u95ED",
    "editor.links.action.cleanBroken": "\u6E05\u7406\u5931\u6548",
    "editor.links.section.add": "\u6DFB\u52A0\u94FE\u63A5",
    "editor.links.section.outgoing": "\u51FA\u94FE\uFF08{count}\uFF09",
    "editor.links.section.backlinks": "\u53CD\u94FE\uFF08{count}\uFF09",
    "editor.links.section.external": "\u5916\u94FE\uFF08{count}\uFF09",
    "editor.links.empty": "\u6682\u65E0\u94FE\u63A5",
    "editor.links.status.broken": "\u5DF2\u5931\u6548",
    "editor.links.status.unknown": "\u672A\u77E5",
    "editor.links.add.icon": "\u56FE\u6807",
    "editor.links.add.external.url.placeholder": "\u5916\u94FE URL\u2026",
    "editor.links.add.external.action": "\u6DFB\u52A0\u5916\u94FE",
    "editor.links.add.external.label.placeholder": "\u5916\u94FE\u6807\u9898\uFF08\u53EF\u9009\uFF09\u2026",
    "editor.links.add.internal.target.placeholder": "\u5185\u90E8 nodeId / kmind-node://\u2026",
    "editor.links.add.internal.action": "\u6DFB\u52A0\u5185\u90E8\u94FE\u63A5",
    "editor.links.add.internal.label.placeholder": "\u5185\u90E8\u6807\u9898\uFF08\u53EF\u9009\uFF09\u2026",
    "editor.links.external.action.open": "\u6253\u5F00",
    "editor.links.external.action.openRight": "\u53F3\u4FA7\u6253\u5F00",
    "editor.links.external.action.openBottom": "\u4E0B\u65B9\u6253\u5F00",
    "editor.links.external.edit.url.placeholder": "URL",
    "editor.links.external.edit.label.placeholder": "\u6807\u9898\uFF08\u53EF\u9009\uFF09",
    "editor.links.iconPicker.title": "\u9009\u62E9\u56FE\u6807",
    "editor.links.iconPicker.action.close": "\u5173\u95ED",
    "editor.links.iconPicker.action.auto": "\u81EA\u52A8",
    "editor.links.iconPicker.action.clear": "\u6E05\u9664",
    "editor.links.alert.clipboardUnavailable": "\u5F53\u524D\u73AF\u5883\u4E0D\u652F\u6301\u5199\u5165\u526A\u8D34\u677F\u3002",
    "editor.links.alert.copyFailed": "\u590D\u5236\u5931\u8D25\u3002",
    "editor.links.alert.crossDocUnavailable": "\u5F53\u524D\u5BBF\u4E3B\u672A\u63D0\u4F9B\u8DE8\u6587\u6863\u8DF3\u8F6C\u80FD\u529B\u3002"
  }
};

// ../react/src/i18n.tsx
var import_jsx_runtime3 = __toESM(require_jsx_runtime(), 1);
var { createContext, useCallback, useContext, useMemo, useSyncExternalStore } = React;
var I18nContext = createContext(null);
function useI18n() {
  const i18n = useContext(I18nContext);
  const fallbackI18n = useMemo(() => {
    return createI18n({
      locale: "en-US",
      fallbackLocale: "en-US",
      messagesByLocale: mergeMessagesByLocale(KMIND_APP_MESSAGES, KMIND_REACT_MESSAGES)
    });
  }, []);
  return i18n ?? fallbackI18n;
}
function useT() {
  const i18n = useI18n();
  useSyncExternalStore(i18n.subscribe, i18n.getVersion, i18n.getVersion);
  return useCallback((key, params) => i18n.t(key, params), [i18n]);
}

// ../react/src/mindmap-editor/panels/node-inspector-panel.tsx
init_src();
var import_jsx_runtime4 = __toESM(require_jsx_runtime(), 1);
function NodeInspectorPanel(props) {
  const { core, doc: doc3, selection, onSelectNode, setBlurViewState, backlinksIndex, dialog } = props;
  if (!selection || selection.type !== "node") {
    return /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("div", { style: { marginTop: 12, fontSize: 12, color: "var(--km-muted)" }, children: "\u9009\u4E2D\u4E00\u4E2A\u8282\u70B9\u4EE5\u7F16\u8F91\u5176 NodeContent / attrs\uFF08tags/icons/images/tasks/links/notes/embed/subMap\uFF09\u3002" });
  }
  const node = doc3.nodes[selection.id];
  if (!node) return null;
  const dispatchContent = (next) => {
    const result = core.dispatch({
      type: "set_node_content",
      payload: { nodeId: node.id, content: next.content, plainText: next.plainText, assets: next.assets }
    });
    if (!result.ok) void dialog.alert(result.error);
  };
  const ensureBlocksContent = () => {
    if (node.content?.schemaVersion === 1 && node.content.kind === "blocks") {
      return { content: node.content, plainText: node.text };
    }
    const blocks = [];
    if (node.content?.schemaVersion === 1 && node.content.kind === "richtext") {
      blocks.push({
        id: createKmindId("rt"),
        type: "richtext",
        region: "main",
        order: 0,
        engine: "prosemirror",
        doc: node.content.doc,
        html: node.content.html
      });
    } else {
      const docJson = fromKmind({ content: node.content, fallbackText: node.text });
      blocks.push({
        id: createKmindId("rt"),
        type: "richtext",
        region: "main",
        order: 0,
        engine: "prosemirror",
        doc: docJson,
        html: void 0
      });
    }
    return { content: { schemaVersion: 1, kind: "blocks", blocks }, plainText: node.text };
  };
  const updateAttrs = (updater) => {
    const next = updater(node.attrs ?? {});
    const result = core.dispatch({ type: "set_node_attrs", payload: { nodeId: node.id, attrs: next } });
    if (!result.ok) void dialog.alert(result.error);
  };
  const updateSubMapId = (subMapId) => {
    const result = core.dispatch({ type: "set_node_submap", payload: { nodeId: node.id, subMapId } });
    if (!result.ok) void dialog.alert(result.error);
  };
  const createLinkId = () => createKmindId("link");
  const blocksContent = node.content?.schemaVersion === 1 && node.content.kind === "blocks" ? node.content : null;
  const getBlocks = () => blocksContent ? blocksContent.blocks : ensureBlocksContent().content.blocks;
  const setBlocks = (blocks, assets) => {
    const base2 = ensureBlocksContent();
    dispatchContent({
      content: { ...base2.content, blocks },
      plainText: base2.plainText,
      ...assets ? { assets } : {}
    });
  };
  const upsertBlock = (type, create) => {
    const blocks = getBlocks();
    if (blocks.some((block) => block.type === type)) return blocks;
    return [...blocks, create()];
  };
  const updateBlock = (blockId, updater) => {
    return getBlocks().map((block) => block.id === blockId ? updater(block) : block);
  };
  const updateBlockOfType = (blockId, type, updater) => {
    return getBlocks().map((block) => {
      if (block.id !== blockId) return block;
      if (block.type !== type) return block;
      return updater(block);
    });
  };
  const removeBlock = (blockId) => {
    setBlocks(getBlocks().filter((block) => block.id !== blockId));
  };
  const tagsBlock = getBlocks().find((block) => block.type === "tags");
  const iconsBlock = getBlocks().find((block) => block.type === "icons");
  const notesBlock = getBlocks().find((block) => block.type === "notes");
  const tasksBlock = getBlocks().find((block) => block.type === "tasks");
  const linksBlock = getBlocks().find((block) => block.type === "links");
  const progressBlock = getBlocks().find((block) => block.type === "progress");
  const sequenceBlock = getBlocks().find((block) => block.type === "sequence");
  const imageBlocks = getBlocks().filter((block) => block.type === "image");
  const embedBlocks = getBlocks().filter((block) => block.type === "embed");
  const backlinks = backlinksIndex[node.id] ?? [];
  const jumpToNode = (nodeId) => {
    if (!doc3.nodes[nodeId]) {
      void dialog.alert("\u8BE5 nodeId \u4E0D\u5B58\u5728\u3002");
      return;
    }
    onSelectNode(nodeId);
  };
  return /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)("div", { style: { marginTop: 12, border: "1px solid var(--km-border)", borderRadius: 12, background: "var(--km-panel)", padding: 12 }, children: [
    /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)("div", { style: { display: "flex", alignItems: "center", justifyContent: "space-between", gap: 12, marginBottom: 10 }, children: [
      /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)("div", { style: { fontSize: 13, fontWeight: 600, color: "var(--km-text)" }, children: [
        "Node Inspector ",
        /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)("span", { style: { fontWeight: 400, color: "var(--km-muted)" }, children: [
          "(",
          node.id,
          ")"
        ] })
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("div", { style: { display: "flex", gap: 8 }, children: /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
        "button",
        {
          onClick: () => {
            const ensured = ensureBlocksContent();
            dispatchContent({ content: ensured.content, plainText: ensured.plainText });
          },
          style: buttonStyle,
          type: "button",
          children: "\u8F6C\u4E3A blocks"
        }
      ) })
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)("div", { style: { display: "flex", flexWrap: "wrap", gap: 10, alignItems: "center", marginBottom: 10, fontSize: 12, color: "var(--km-muted)" }, children: [
      /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)("label", { style: { display: "inline-flex", alignItems: "center", gap: 6 }, children: [
        /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
          "input",
          {
            checked: Boolean(node.attrs?.locked),
            onChange: (e) => updateAttrs((prev) => ({ ...prev, locked: e.target.checked })),
            type: "checkbox"
          }
        ),
        "locked"
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)("label", { style: { display: "inline-flex", alignItems: "center", gap: 6 }, children: [
        /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
          "input",
          {
            checked: Boolean(node.attrs?.readonly),
            onChange: (e) => updateAttrs((prev) => ({ ...prev, readonly: e.target.checked })),
            type: "checkbox"
          }
        ),
        "readonly"
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)("label", { style: { display: "inline-flex", alignItems: "center", gap: 6 }, children: [
        /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
          "input",
          {
            checked: node.attrs?.blur?.kind === "node",
            onChange: (e) => updateAttrs((prev) => ({ ...prev, blur: e.target.checked ? { kind: "node" } : void 0 })),
            type: "checkbox"
          }
        ),
        "blur(node)"
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
        "button",
        {
          disabled: node.attrs?.blur?.kind !== "node",
          onClick: () => setBlurViewState((prev) => toggleBlurForNode(prev, node.id)),
          style: { ...buttonStyle, opacity: node.attrs?.blur?.kind === "node" ? 1 : 0.45 },
          type: "button",
          children: "toggle reveal"
        }
      )
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(Section, { title: "SubMap\uFF08\u4E0B\u94BB\uFF09", children: /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)("div", { style: { display: "flex", gap: 8, alignItems: "center", flexWrap: "wrap" }, children: [
      /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)("div", { style: { fontSize: 12, color: "var(--km-muted)" }, children: [
        "subMapId: ",
        node.subMapId ?? "\u2014"
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
        "button",
        {
          onClick: () => {
            void (async () => {
              const id = await dialog.prompt({ message: "\u8F93\u5165 subMapId\uFF08\u4E3A\u7A7A\u5219\u53D6\u6D88\uFF09", initialValue: node.subMapId ?? "" });
              if (id === null) return;
              const next = id.trim();
              updateSubMapId(next.length > 0 ? next : null);
            })();
          },
          style: buttonStyle,
          type: "button",
          children: "\u8BBE\u7F6E subMapId"
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
        "button",
        {
          onClick: () => updateSubMapId(null),
          style: buttonStyle,
          type: "button",
          children: "\u6E05\u9664 subMapId"
        }
      )
    ] }) }),
    /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(Section, { title: "Sequence\uFF08\u5E8F\u53F7\uFF09", children: /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)("div", { style: { display: "flex", gap: 8, alignItems: "center", flexWrap: "wrap" }, children: [
      /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
        "button",
        {
          onClick: () => {
            if (sequenceBlock) {
              removeBlock(sequenceBlock.id);
              return;
            }
            const blocks = upsertBlock("sequence", () => ({
              id: createKmindId("seq"),
              type: "sequence",
              region: "left",
              order: 0,
              mode: "siblings"
            }));
            setBlocks(blocks);
          },
          style: buttonStyle,
          type: "button",
          children: sequenceBlock ? "\u79FB\u9664\u5E8F\u53F7" : "\u6DFB\u52A0\u5E8F\u53F7"
        }
      ),
      sequenceBlock ? /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)(import_jsx_runtime4.Fragment, { children: [
        /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)("label", { style: { display: "inline-flex", alignItems: "center", gap: 6, fontSize: 12, color: "var(--km-muted)" }, children: [
          "region",
          /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)(
            "select",
            {
              onChange: (e) => setBlocks(updateBlock(sequenceBlock.id, (b2) => ({ ...b2, region: e.target.value }))),
              style: { ...buttonStyle, padding: "4px 8px" },
              value: sequenceBlock.region,
              children: [
                /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("option", { value: "top", children: "top" }),
                /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("option", { value: "left", children: "left" }),
                /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("option", { value: "main", children: "main" }),
                /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("option", { value: "right", children: "right" }),
                /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("option", { value: "bottom", children: "bottom" })
              ]
            }
          )
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)("label", { style: { display: "inline-flex", alignItems: "center", gap: 6, fontSize: 12, color: "var(--km-muted)" }, children: [
          "order",
          /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
            "input",
            {
              onChange: (e) => {
                const nextOrder = Number(e.target.value);
                if (!Number.isFinite(nextOrder)) return;
                setBlocks(updateBlock(sequenceBlock.id, (b2) => ({ ...b2, order: Math.trunc(nextOrder) })));
              },
              style: { ...buttonStyle, padding: "4px 8px", width: 80 },
              type: "number",
              value: sequenceBlock.order
            }
          )
        ] })
      ] }) : null
    ] }) }),
    /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)(Section, { title: "Tags", children: [
      /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)("div", { style: { display: "flex", gap: 8, alignItems: "center", flexWrap: "wrap", marginBottom: 8 }, children: [
        /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
          "button",
          {
            onClick: () => {
              const blocks = upsertBlock("tags", () => ({
                id: createKmindId("tags"),
                type: "tags",
                region: "bottom",
                order: 10,
                tags: []
              }));
              setBlocks(blocks);
            },
            style: buttonStyle,
            type: "button",
            children: tagsBlock ? "\u5DF2\u542F\u7528" : "\u542F\u7528 tags"
          }
        ),
        tagsBlock ? /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
          "button",
          {
            onClick: () => {
              void (async () => {
                const text5 = await dialog.prompt({ message: "\u8F93\u5165 tag \u6587\u672C\uFF1A" });
                if (!text5) return;
                setBlocks(
                  updateBlockOfType(tagsBlock.id, "tags", (block) => ({
                    ...block,
                    tags: [
                      ...block.tags,
                      { id: createKmindId("tag"), text: text5 }
                    ]
                  }))
                );
              })();
            },
            style: buttonStyle,
            type: "button",
            children: "\u6DFB\u52A0 tag"
          }
        ) : null
      ] }),
      tagsBlock ? /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("div", { style: { display: "flex", flexWrap: "wrap", gap: 8 }, children: tagsBlock.tags.map((tag, index) => /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)("div", { style: { display: "inline-flex", alignItems: "center", gap: 6 }, children: [
        /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("span", { style: { fontSize: 12, color: "var(--km-text)" }, children: tag.text }),
        /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
          "button",
          {
            onClick: () => {
              const nextTags = tagsBlock.tags.filter((item) => item.id !== tag.id);
              setBlocks(updateBlockOfType(tagsBlock.id, "tags", (block) => ({ ...block, tags: nextTags })));
            },
            style: { ...buttonStyle, padding: "2px 8px" },
            type: "button",
            children: "\u5220\u9664"
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
          "button",
          {
            disabled: index === 0,
            onClick: () => {
              const next = [...tagsBlock.tags];
              const item = next[index];
              if (!item) return;
              next.splice(index, 1);
              next.splice(index - 1, 0, item);
              setBlocks(updateBlockOfType(tagsBlock.id, "tags", (block) => ({ ...block, tags: next })));
            },
            style: { ...buttonStyle, padding: "2px 8px", opacity: index === 0 ? 0.4 : 1 },
            type: "button",
            children: "\u2191"
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
          "button",
          {
            disabled: index === tagsBlock.tags.length - 1,
            onClick: () => {
              const next = [...tagsBlock.tags];
              const item = next[index];
              if (!item) return;
              next.splice(index, 1);
              next.splice(index + 1, 0, item);
              setBlocks(updateBlockOfType(tagsBlock.id, "tags", (block) => ({ ...block, tags: next })));
            },
            style: { ...buttonStyle, padding: "2px 8px", opacity: index === tagsBlock.tags.length - 1 ? 0.4 : 1 },
            type: "button",
            children: "\u2193"
          }
        )
      ] }, tag.id)) }) : null
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)(Section, { title: "Icons", children: [
      /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)("div", { style: { display: "flex", gap: 8, alignItems: "center", flexWrap: "wrap", marginBottom: 8 }, children: [
        /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
          "button",
          {
            onClick: () => {
              const blocks = upsertBlock("icons", () => ({
                id: createKmindId("icons"),
                type: "icons",
                region: "left",
                order: 10,
                icons: []
              }));
              setBlocks(blocks);
            },
            style: buttonStyle,
            type: "button",
            children: iconsBlock ? "\u5DF2\u542F\u7528" : "\u542F\u7528 icons"
          }
        ),
        iconsBlock ? /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
          "button",
          {
            onClick: () => {
              void (async () => {
                const value = await dialog.prompt({ message: "\u8F93\u5165 icon\uFF08emoji \u6216\u6587\u672C\uFF09" });
                if (!value) return;
                setBlocks(
                  updateBlockOfType(iconsBlock.id, "icons", (block) => ({
                    ...block,
                    icons: [
                      ...block.icons,
                      { id: createKmindId("icon"), value }
                    ]
                  }))
                );
              })();
            },
            style: buttonStyle,
            type: "button",
            children: "\u6DFB\u52A0 icon"
          }
        ) : null
      ] }),
      iconsBlock ? /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("div", { style: { display: "flex", flexWrap: "wrap", gap: 8 }, children: iconsBlock.icons.map((icon, index) => /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)("div", { style: { display: "inline-flex", alignItems: "center", gap: 6 }, children: [
        /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("span", { style: { fontSize: 12, color: "var(--km-text)" }, children: icon.value }),
        /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
          "button",
          {
            onClick: () => {
              const nextIcons = iconsBlock.icons.filter((item) => item.id !== icon.id);
              setBlocks(updateBlockOfType(iconsBlock.id, "icons", (block) => ({ ...block, icons: nextIcons })));
            },
            style: { ...buttonStyle, padding: "2px 8px" },
            type: "button",
            children: "\u5220\u9664"
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
          "button",
          {
            disabled: index === 0,
            onClick: () => {
              const next = [...iconsBlock.icons];
              const item = next[index];
              if (!item) return;
              next.splice(index, 1);
              next.splice(index - 1, 0, item);
              setBlocks(updateBlockOfType(iconsBlock.id, "icons", (block) => ({ ...block, icons: next })));
            },
            style: { ...buttonStyle, padding: "2px 8px", opacity: index === 0 ? 0.4 : 1 },
            type: "button",
            children: "\u2191"
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
          "button",
          {
            disabled: index === iconsBlock.icons.length - 1,
            onClick: () => {
              const next = [...iconsBlock.icons];
              const item = next[index];
              if (!item) return;
              next.splice(index, 1);
              next.splice(index + 1, 0, item);
              setBlocks(updateBlockOfType(iconsBlock.id, "icons", (block) => ({ ...block, icons: next })));
            },
            style: { ...buttonStyle, padding: "2px 8px", opacity: index === iconsBlock.icons.length - 1 ? 0.4 : 1 },
            type: "button",
            children: "\u2193"
          }
        )
      ] }, icon.id)) }) : null
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)(Section, { title: "Images\uFF08\u79BB\u7EBF assets\uFF09", children: [
      /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)("div", { style: { display: "flex", gap: 8, alignItems: "center", flexWrap: "wrap", marginBottom: 8 }, children: [
        /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)("label", { style: { display: "inline-flex", alignItems: "center", gap: 6, fontSize: 12, color: "var(--km-muted)" }, children: [
          "\u6DFB\u52A0\u56FE\u7247",
          /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
            "input",
            {
              accept: "image/*",
              onChange: (event) => {
                const file = event.target.files?.[0];
                if (!file) return;
                void (async () => {
                  const dataUrl = await blobToDataUrl(file);
                  const dims = await getImageDimensions(dataUrl).catch(() => null);
                  const assetId = createKmindId("asset");
                  const asset = {
                    id: assetId,
                    kind: "image",
                    mimeType: file.type || "image/png",
                    dataUrl,
                    width: dims?.width,
                    height: dims?.height
                  };
                  const ensured = ensureBlocksContent();
                  const imageBlock = {
                    id: createKmindId("img"),
                    type: "image",
                    region: "top",
                    order: 0,
                    assetId,
                    width: dims?.width ? Math.min(240, dims.width) : 180,
                    height: dims?.height ? Math.min(180, dims.height) : 120,
                    fit: "contain"
                  };
                  dispatchContent({
                    content: { ...ensured.content, blocks: [...ensured.content.blocks, imageBlock] },
                    plainText: ensured.plainText,
                    assets: { [assetId]: asset }
                  });
                })();
                event.target.value = "";
              },
              style: { fontSize: 12 },
              type: "file"
            }
          )
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
          "button",
          {
            onClick: () => {
              void (async () => {
                if (!navigator.clipboard?.read) {
                  await dialog.alert("\u5F53\u524D\u6D4F\u89C8\u5668\u4E0D\u652F\u6301\u8BFB\u53D6\u526A\u8D34\u677F\u56FE\u7247\uFF08navigator.clipboard.read\uFF09\u3002");
                  return;
                }
                try {
                  const items = await navigator.clipboard.read();
                  const imageItem = items.find((item) => item.types.some((type2) => type2.startsWith("image/")));
                  if (!imageItem) {
                    await dialog.alert("\u526A\u8D34\u677F\u4E2D\u672A\u53D1\u73B0\u56FE\u7247\u3002");
                    return;
                  }
                  const type = imageItem.types.find((t) => t.startsWith("image/")) ?? "image/png";
                  const blob = await imageItem.getType(type);
                  const dataUrl = await blobToDataUrl(blob);
                  const dims = await getImageDimensions(dataUrl).catch(() => null);
                  const assetId = createKmindId("asset");
                  const asset = {
                    id: assetId,
                    kind: "image",
                    mimeType: blob.type || "image/png",
                    dataUrl,
                    width: dims?.width,
                    height: dims?.height
                  };
                  const ensured = ensureBlocksContent();
                  const imageBlock = {
                    id: createKmindId("img"),
                    type: "image",
                    region: "top",
                    order: 0,
                    assetId,
                    width: dims?.width ? Math.min(240, dims.width) : 180,
                    height: dims?.height ? Math.min(180, dims.height) : 120,
                    fit: "contain"
                  };
                  dispatchContent({
                    content: { ...ensured.content, blocks: [...ensured.content.blocks, imageBlock] },
                    plainText: ensured.plainText,
                    assets: { [assetId]: asset }
                  });
                } catch (error) {
                  await dialog.alert(error instanceof Error ? error.message : "\u8BFB\u53D6\u526A\u8D34\u677F\u5931\u8D25\u3002");
                }
              })();
            },
            style: buttonStyle,
            type: "button",
            children: "\u7C98\u8D34\u56FE\u7247"
          }
        )
      ] }),
      imageBlocks.length > 0 ? /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("div", { style: { display: "flex", flexDirection: "column", gap: 8 }, children: imageBlocks.map((block) => /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)("div", { style: { display: "flex", gap: 8, alignItems: "center", flexWrap: "wrap" }, children: [
        /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)("div", { style: { fontSize: 12, color: "var(--km-muted)" }, children: [
          block.assetId,
          " (",
          block.region,
          "@",
          block.order,
          ")"
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)("label", { style: { display: "inline-flex", alignItems: "center", gap: 6, fontSize: 12, color: "var(--km-muted)" }, children: [
          "region",
          /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)(
            "select",
            {
              onChange: (e) => setBlocks(updateBlock(block.id, (b2) => ({ ...b2, region: e.target.value }))),
              style: { ...buttonStyle, padding: "4px 8px" },
              value: block.region,
              children: [
                /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("option", { value: "top", children: "top" }),
                /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("option", { value: "left", children: "left" }),
                /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("option", { value: "right", children: "right" }),
                /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("option", { value: "bottom", children: "bottom" }),
                /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("option", { value: "main", children: "main" })
              ]
            }
          )
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)("label", { style: { display: "inline-flex", alignItems: "center", gap: 6, fontSize: 12, color: "var(--km-muted)" }, children: [
          "w",
          /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
            "input",
            {
              onChange: (e) => setBlocks(updateBlock(block.id, (b2) => ({ ...b2, width: Math.max(20, Number(e.target.value)) }))),
              style: { ...buttonStyle, padding: "4px 8px", width: 90 },
              type: "number",
              value: block.width ?? 180
            }
          )
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)("label", { style: { display: "inline-flex", alignItems: "center", gap: 6, fontSize: 12, color: "var(--km-muted)" }, children: [
          "h",
          /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
            "input",
            {
              onChange: (e) => setBlocks(updateBlock(block.id, (b2) => ({ ...b2, height: Math.max(20, Number(e.target.value)) }))),
              style: { ...buttonStyle, padding: "4px 8px", width: 90 },
              type: "number",
              value: block.height ?? 120
            }
          )
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("button", { onClick: () => removeBlock(block.id), style: buttonStyle, type: "button", children: "\u79FB\u9664" })
      ] }, block.id)) }) : /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("div", { style: { fontSize: 12, color: "var(--km-muted)" }, children: "\u5C1A\u672A\u6DFB\u52A0\u56FE\u7247\u3002" })
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)(Section, { title: "Tasks\uFF08checkbox\uFF09+ Progress", children: [
      /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)("div", { style: { display: "flex", gap: 8, alignItems: "center", flexWrap: "wrap", marginBottom: 8 }, children: [
        /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
          "button",
          {
            onClick: () => {
              const blocks = upsertBlock("tasks", () => ({
                id: createKmindId("tasks"),
                type: "tasks",
                region: "bottom",
                order: 20,
                items: []
              }));
              setBlocks(blocks);
            },
            style: buttonStyle,
            type: "button",
            children: tasksBlock ? "\u5DF2\u542F\u7528" : "\u542F\u7528 tasks"
          }
        ),
        tasksBlock ? /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
          "button",
          {
            onClick: () => {
              void (async () => {
                const text5 = await dialog.prompt({ message: "\u4EFB\u52A1\u6587\u672C\uFF1A" });
                if (!text5) return;
                setBlocks(
                  updateBlockOfType(tasksBlock.id, "tasks", (block) => ({
                    ...block,
                    items: [
                      ...block.items,
                      {
                        id: createKmindId("task"),
                        text: text5,
                        checked: false
                      }
                    ]
                  }))
                );
              })();
            },
            style: buttonStyle,
            type: "button",
            children: "\u6DFB\u52A0\u4EFB\u52A1"
          }
        ) : null,
        /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
          "button",
          {
            onClick: () => {
              if (progressBlock) {
                removeBlock(progressBlock.id);
                return;
              }
              const blocks = upsertBlock("progress", () => ({
                id: createKmindId("prog"),
                type: "progress",
                region: "right",
                order: 0,
                variant: "ring"
              }));
              setBlocks(blocks);
            },
            style: buttonStyle,
            type: "button",
            children: progressBlock ? "\u79FB\u9664\u8FDB\u5EA6" : "\u663E\u793A\u8FDB\u5EA6"
          }
        ),
        progressBlock ? /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)("label", { style: { display: "inline-flex", alignItems: "center", gap: 6, fontSize: 12, color: "var(--km-muted)" }, children: [
          "variant",
          /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)(
            "select",
            {
              onChange: (e) => setBlocks(updateBlock(progressBlock.id, (b2) => ({ ...b2, variant: e.target.value }))),
              style: { ...buttonStyle, padding: "4px 8px" },
              value: progressBlock.variant ?? "ring",
              children: [
                /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("option", { value: "ring", children: "ring" }),
                /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("option", { value: "bar", children: "bar" })
              ]
            }
          )
        ] }) : null
      ] }),
      tasksBlock ? /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("div", { style: { display: "flex", flexDirection: "column", gap: 6 }, children: tasksBlock.items.map((item) => /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)("label", { style: { display: "flex", alignItems: "center", gap: 8, fontSize: 12, color: "var(--km-text)" }, children: [
        /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
          "input",
          {
            checked: item.checked,
            onChange: (e) => setBlocks(
              updateBlockOfType(tasksBlock.id, "tasks", (block) => ({
                ...block,
                items: block.items.map((it) => it.id === item.id ? { ...it, checked: e.target.checked } : it)
              }))
            ),
            type: "checkbox"
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("span", { style: { flex: 1 }, children: item.text }),
        /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
          "button",
          {
            onClick: (e) => {
              e.preventDefault();
              setBlocks(
                updateBlockOfType(tasksBlock.id, "tasks", (block) => ({
                  ...block,
                  items: block.items.filter((it) => it.id !== item.id)
                }))
              );
            },
            style: { ...buttonStyle, padding: "2px 8px" },
            type: "button",
            children: "\u5220\u9664"
          }
        )
      ] }, item.id)) }) : /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("div", { style: { fontSize: 12, color: "var(--km-muted)" }, children: "\u5C1A\u672A\u542F\u7528 tasks\u3002" })
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)(Section, { title: "Links / Backlinks", children: [
      /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)("div", { style: { display: "flex", gap: 8, alignItems: "center", flexWrap: "wrap", marginBottom: 8 }, children: [
        /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
          "button",
          {
            onClick: () => {
              const blocks = upsertBlock("links", () => ({
                id: createKmindId("links"),
                type: "links",
                region: "bottom",
                order: 30,
                links: []
              }));
              setBlocks(blocks);
            },
            style: buttonStyle,
            type: "button",
            children: linksBlock ? "\u5DF2\u542F\u7528" : "\u542F\u7528 links"
          }
        ),
        linksBlock ? /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)(import_jsx_runtime4.Fragment, { children: [
          /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
            "button",
            {
              onClick: () => {
                void (async () => {
                  const target2 = await dialog.prompt({ message: "\u5185\u90E8\u94FE\u63A5 nodeId\uFF1A" });
                  if (!target2) return;
                  const nodeId = target2.trim();
                  if (!nodeId) return;
                  if (!doc3.nodes[nodeId]) {
                    await dialog.alert("\u8BE5 nodeId \u4E0D\u5B58\u5728\u3002");
                    return;
                  }
                  setBlocks(
                    updateBlockOfType(linksBlock.id, "links", (block) => ({
                      ...block,
                      links: [...block.links, { kind: "internal", id: createLinkId(), nodeId }]
                    }))
                  );
                })();
              },
              style: buttonStyle,
              type: "button",
              children: "+ internal"
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
            "button",
            {
              onClick: () => {
                void (async () => {
                  const url = await dialog.prompt({ message: "\u5916\u90E8\u94FE\u63A5 URL\uFF1A" });
                  if (!url) return;
                  const nextUrl = url.trim();
                  if (!nextUrl) return;
                  setBlocks(
                    updateBlockOfType(linksBlock.id, "links", (block) => ({
                      ...block,
                      links: [...block.links, { kind: "external", id: createLinkId(), url: nextUrl }]
                    }))
                  );
                })();
              },
              style: buttonStyle,
              type: "button",
              children: "+ external"
            }
          )
        ] }) : null
      ] }),
      linksBlock ? /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("div", { style: { display: "flex", flexDirection: "column", gap: 6 }, children: linksBlock.links.map((link, index) => /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)("div", { style: { display: "flex", gap: 8, alignItems: "center", flexWrap: "wrap" }, children: [
        /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("div", { style: { fontSize: 12, color: "var(--km-text)" }, children: link.kind === "internal" ? typeof link.docId === "string" && link.docId.trim().length > 0 ? `${link.docId.trim()}#${link.nodeId}` : `#${link.nodeId}` : link.url }),
        link.kind === "internal" ? /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
          "button",
          {
            onClick: () => {
              if (typeof link.docId === "string" && link.docId.trim().length > 0) {
                void dialog.alert("\u8DE8\u6587\u6863\u8DF3\u8F6C\u8BF7\u4F7F\u7528 /app \u7684 links \u9762\u677F\uFF08\u5BBF\u4E3B\u8D1F\u8D23\u5BFC\u822A\uFF09\u3002");
                return;
              }
              jumpToNode(link.nodeId);
            },
            style: { ...buttonStyle, padding: "2px 8px" },
            type: "button",
            children: "\u8DF3\u8F6C"
          }
        ) : /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
          "button",
          {
            onClick: () => window.open(link.url, "_blank", "noopener,noreferrer"),
            style: { ...buttonStyle, padding: "2px 8px" },
            type: "button",
            children: "\u6253\u5F00"
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
          "button",
          {
            onClick: () => {
              setBlocks(
                updateBlockOfType(linksBlock.id, "links", (block) => ({
                  ...block,
                  links: block.links.filter((_10, i) => i !== index)
                }))
              );
            },
            style: { ...buttonStyle, padding: "2px 8px" },
            type: "button",
            children: "\u5220\u9664"
          }
        )
      ] }, `${link.kind}-${index}`)) }) : null,
      /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)("div", { style: { marginTop: 8, fontSize: 12, color: "var(--km-muted)" }, children: [
        "Backlinks:",
        " ",
        backlinks.length > 0 ? /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("span", { style: { display: "inline-flex", flexWrap: "wrap", gap: 6 }, children: backlinks.map((ref) => {
          const docId = typeof ref.docId === "string" && ref.docId.trim().length > 0 ? ref.docId.trim() : null;
          const label = docId ? `${docId}#${ref.nodeId}` : `#${ref.nodeId}`;
          const canJump = !docId;
          return /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
            "button",
            {
              onClick: () => {
                if (!canJump) {
                  void dialog.alert("\u8DE8\u6587\u6863 backlinks \u4EC5\u5728 /app links \u9762\u677F\u4E2D\u53EF\u8DF3\u8F6C\u3002");
                  return;
                }
                jumpToNode(ref.nodeId);
              },
              style: { ...buttonStyle, padding: "2px 8px", opacity: canJump ? 1 : 0.55 },
              type: "button",
              children: label
            },
            label
          );
        }) }) : "\u2014"
      ] })
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)(Section, { title: "Notes\uFF08\u5907\u6CE8/\u6279\u6CE8\uFF09", children: [
      /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("div", { style: { display: "flex", gap: 8, alignItems: "center", flexWrap: "wrap", marginBottom: 8 }, children: /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
        "button",
        {
          onClick: () => {
            if (notesBlock) {
              removeBlock(notesBlock.id);
              return;
            }
            const docJson = createDocFromText("");
            const blocks = upsertBlock("notes", () => ({
              id: createKmindId("notes"),
              type: "notes",
              region: "right",
              order: 0,
              engine: "prosemirror",
              doc: docJson,
              html: renderHtml(docJson)
            }));
            setBlocks(blocks);
          },
          style: buttonStyle,
          type: "button",
          children: notesBlock ? "\u79FB\u9664\u5907\u6CE8" : "\u542F\u7528\u5907\u6CE8"
        }
      ) }),
      notesBlock ? /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("div", { style: { fontSize: 12, color: "var(--km-muted)" }, children: "\u5907\u6CE8\u5DF2\u542F\u7528\uFF1A\u8BF7\u4F7F\u7528\u8282\u70B9\u4E0A\u7684\u5907\u6CE8 icon \u8FDB\u884C\u9884\u89C8/\u7F16\u8F91\uFF08Card v1\uFF09\u3002" }) : /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("div", { style: { fontSize: 12, color: "var(--km-muted)" }, children: "\u5C1A\u672A\u542F\u7528\u5907\u6CE8\u3002" })
    ] }),
    /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)(Section, { title: "Embeds + Custom Data\uFF08assets: json\uFF09", children: [
      /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)("div", { style: { display: "flex", gap: 8, alignItems: "center", flexWrap: "wrap", marginBottom: 8 }, children: [
        /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
          "button",
          {
            onClick: () => {
              void (async () => {
                const type = await dialog.prompt({
                  message: "embed.type\uFF08\u4F8B\u5982 demo:counter / kmind:protyle\uFF09",
                  initialValue: "demo:counter"
                });
                if (!type) return;
                const embedType = type.trim();
                if (!embedType) return;
                const ensured = ensureBlocksContent();
                const embedBlock = {
                  id: createKmindId("emb"),
                  type: "embed",
                  region: "bottom",
                  order: 60,
                  embed: { type: embedType },
                  width: 220,
                  height: 90
                };
                dispatchContent({
                  content: { ...ensured.content, blocks: [...ensured.content.blocks, embedBlock] },
                  plainText: ensured.plainText
                });
              })();
            },
            style: buttonStyle,
            type: "button",
            children: "\u6DFB\u52A0 embed"
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)("label", { style: { display: "inline-flex", alignItems: "center", gap: 6, fontSize: 12, color: "var(--km-muted)" }, children: [
          "\u5BFC\u5165 JSON \u4F5C\u4E3A asset\uFF08\u793A\u4F8B\uFF1AExcalidraw/protyle \u6570\u636E\uFF09",
          /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
            "input",
            {
              accept: "application/json,.json",
              onChange: (event) => {
                const file = event.target.files?.[0];
                if (!file) return;
                void (async () => {
                  const text5 = await file.text();
                  const data = JSON.parse(text5);
                  const assetId = createKmindId("asset");
                  const asset = { id: assetId, kind: "json", data };
                  const type = await dialog.prompt({ message: "embed.type\uFF08\u5C06\u5F15\u7528\u8BE5 json asset\uFF09", initialValue: "kmind:json" });
                  if (!type) return;
                  const embedType = type.trim();
                  if (!embedType) return;
                  const ensured = ensureBlocksContent();
                  const embedBlock = {
                    id: createKmindId("emb"),
                    type: "embed",
                    region: "bottom",
                    order: 60,
                    embed: { type: embedType, assetId },
                    width: 240,
                    height: 120
                  };
                  dispatchContent({
                    content: { ...ensured.content, blocks: [...ensured.content.blocks, embedBlock] },
                    plainText: ensured.plainText,
                    assets: { [assetId]: asset }
                  });
                })();
                event.target.value = "";
              },
              style: { fontSize: 12 },
              type: "file"
            }
          )
        ] })
      ] }),
      embedBlocks.length > 0 ? /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("div", { style: { display: "flex", flexDirection: "column", gap: 8 }, children: embedBlocks.map((block) => /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)("div", { style: { display: "flex", gap: 8, alignItems: "center", flexWrap: "wrap" }, children: [
        /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)("div", { style: { fontSize: 12, color: "var(--km-muted)" }, children: [
          block.embed.type,
          " ",
          block.embed.assetId ? `(${block.embed.assetId})` : ""
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("button", { onClick: () => removeBlock(block.id), style: buttonStyle, type: "button", children: "\u79FB\u9664" })
      ] }, block.id)) }) : /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("div", { style: { fontSize: 12, color: "var(--km-muted)" }, children: "\u5C1A\u672A\u6DFB\u52A0 embed\u3002" })
    ] })
  ] });
}
function Section(props) {
  return /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)("div", { style: { paddingTop: 10, marginTop: 10, borderTop: "1px solid var(--km-border)" }, children: [
    /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("div", { style: { fontSize: 12, fontWeight: 600, color: "var(--km-text)", marginBottom: 8 }, children: props.title }),
    props.children
  ] });
}

// ../react/src/mindmap-editor/layers/edges.tsx
var import_react = __toESM(require_react(), 1);

// ../react/src/edge-router.ts
init_src();

// ../react/src/mindmap-editor/layers/edges.tsx
var import_jsx_runtime5 = __toESM(require_jsx_runtime(), 1);
function Edges(props) {
  const { layout, hiddenNodeIds, hiddenSummaryIds, nodeThemeById, visibleNodeIds, visibleSummaryIds, perfEnabled, perfStatsRef } = props;
  const rectsOverlap2 = (a2, b2) => a2.x < b2.x + b2.width && a2.x + a2.width > b2.x && a2.y < b2.y + b2.height && a2.y + a2.height > b2.y;
  const isEdgeInView = (edge, fromRect, toRect) => {
    if (!visibleNodeIds && !visibleSummaryIds) return true;
    const toVisible = visibleNodeIds?.has(edge.to) ?? false;
    const fromVisible = (visibleNodeIds?.has(edge.from) ?? false) || (visibleSummaryIds?.has(edge.from) ?? false);
    if (toVisible || fromVisible) return true;
    if (!props.viewportCullRect) return false;
    const x1 = Math.min(fromRect.x, toRect.x);
    const y1 = Math.min(fromRect.y, toRect.y);
    const x22 = Math.max(fromRect.x + fromRect.width, toRect.x + toRect.width);
    const y2 = Math.max(fromRect.y + fromRect.height, toRect.y + toRect.height);
    return rectsOverlap2({ x: x1, y: y1, width: x22 - x1, height: y2 - y1 }, props.viewportCullRect);
  };
  const firstChildByParent = (0, import_react.useMemo)(() => {
    const map2 = /* @__PURE__ */ new Map();
    for (const edge of layout.edges) {
      const fromId = edge.from;
      const childLayout = layout.nodes[edge.to];
      if (!childLayout) continue;
      const existing = map2.get(fromId);
      if (!existing) {
        map2.set(fromId, edge.to);
        continue;
      }
      const existingLayout = layout.nodes[existing];
      if (!existingLayout || childLayout.y < existingLayout.y) {
        map2.set(fromId, edge.to);
      }
    }
    return map2;
  }, [layout.edges, layout.nodes]);
  const nodesWithIncoming = (0, import_react.useMemo)(() => {
    const ids = /* @__PURE__ */ new Set();
    for (const edge of layout.edges) ids.add(edge.to);
    return ids;
  }, [layout.edges]);
  const renderEdge = (edge, from2, to, anchorsOverride) => {
    const theme = nodeThemeById[edge.to];
    const stroke = theme?.incomingEdge?.strokeColor ?? theme?.paint.edgeStroke ?? "var(--km-edge-stroke)";
    const strokeWidth = theme?.incomingEdge?.strokeWidth ?? theme?.edges?.strokeWidth ?? 2;
    const dasharray = theme?.incomingEdge?.dasharray ?? theme?.edges?.dasharray;
    const cap = theme?.incomingEdge?.cap ?? theme?.edges?.cap;
    const join2 = theme?.incomingEdge?.join ?? theme?.edges?.join;
    const routeType = theme?.incomingEdge?.routeType ?? theme?.edges?.routeType ?? "cubic";
    const routeOptions = theme?.incomingEdge?.routeOptions ?? theme?.edges?.routeOptions;
    const routed = (() => {
      if (routeType === "tapered") {
        return {
          path: routeTaperedEdgePath({
            from: from2,
            to,
            startWidth: Math.max(1, strokeWidth * 2),
            endWidth: Math.max(0.6, strokeWidth * 0.5),
            anchorsOverride
          }),
          renderMode: "fill"
        };
      }
      const layoutType = props.containerLayoutTypeById[String(edge.from)] ?? "logical-right";
      const isFishboneLayout = layoutType === "fishbone-left" || layoutType === "fishbone-right";
      const anchors = anchorsOverride ?? resolveEdgeAnchorsForLayout(layoutType, from2, to);
      if (routeType === "center-quadratic-tapered" && !isFishboneLayout) {
        return {
          path: routeCenterQuadraticTaperedEdgePath({
            from: from2,
            to,
            anchors,
            containerWidth: layout.bounds.width,
            containerHeight: layout.bounds.height,
            startWidth: Math.max(1, strokeWidth * 2),
            endWidth: Math.max(0.6, strokeWidth * 0.5)
          }),
          renderMode: "fill"
        };
      }
      if (routeType === "edge-lead-quadratic-tapered" && !isFishboneLayout) {
        return {
          path: routeEdgeLeadQuadraticTaperedEdgePath({
            from: from2,
            to,
            anchors,
            startWidth: Math.max(1, strokeWidth * 2),
            endWidth: Math.max(0.6, strokeWidth * 0.5),
            options: routeOptions?.["edge-lead-quadratic"]
          }),
          renderMode: "fill"
        };
      }
      if (routeType === "center-quadratic" && !isFishboneLayout) {
        return {
          path: routeCenterQuadraticEdgePath({
            from: from2,
            to,
            anchors,
            containerWidth: layout.bounds.width,
            containerHeight: layout.bounds.height
          }),
          renderMode: "stroke"
        };
      }
      if (routeType === "cubic-tail" && !isFishboneLayout) {
        return {
          path: routeCubicTailEdgePath({
            from: from2,
            to,
            anchors,
            startFromCenter: firstChildByParent.get(edge.from) === edge.to,
            options: routeOptions?.["cubic-tail"]
          }),
          renderMode: "stroke"
        };
      }
      if (routeType === "baseline-fork" && !isFishboneLayout) {
        return {
          path: routeBaselineForkEdgePath({
            from: from2,
            to,
            anchors,
            fromIsRoot: Boolean(layout.nodes[edge.from]) && !nodesWithIncoming.has(edge.from),
            options: routeOptions?.["baseline-fork"]
          }),
          renderMode: "stroke"
        };
      }
      const fallbackRouteType = isFishboneLayout && (routeType === "center-quadratic" || routeType === "center-quadratic-tapered" || routeType === "edge-lead-quadratic" || routeType === "edge-lead-quadratic-tapered" || routeType === "cubic-tail" || routeType === "baseline-fork") ? "cubic" : routeType;
      return {
        path: routeEdgePath(fallbackRouteType, from2, to, anchors, routeOptions),
        renderMode: "stroke"
      };
    })();
    return routed.renderMode === "fill" ? /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
      "path",
      {
        d: routed.path,
        "data-edge-id": edge.id,
        fill: stroke,
        opacity: 0.92
      },
      edge.id
    ) : /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
      "path",
      {
        d: routed.path,
        "data-edge-id": edge.id,
        fill: "none",
        stroke,
        strokeDasharray: dasharray,
        strokeLinecap: cap,
        strokeLinejoin: join2,
        strokeWidth
      },
      edge.id
    );
  };
  const fishboneEdgesByFrom = /* @__PURE__ */ new Map();
  const standardEdges = [];
  for (const edge of layout.edges) {
    const fromNodeRect = layout.nodes[edge.from];
    const fromSummaryRect = fromNodeRect ? null : layout.summaries[edge.from];
    const fromRect = fromNodeRect ?? fromSummaryRect;
    const toRect = layout.nodes[edge.to];
    if (!fromRect || !toRect) continue;
    if (hiddenNodeIds?.has(edge.to)) continue;
    if (fromNodeRect && hiddenNodeIds?.has(edge.from)) continue;
    if (fromSummaryRect && hiddenSummaryIds?.has(edge.from)) continue;
    if (!isEdgeInView(edge, fromRect, toRect)) continue;
    const layoutType = props.containerLayoutTypeById[String(edge.from)] ?? "logical-right";
    if (layoutType === "fishbone-left" || layoutType === "fishbone-right") {
      const key = String(edge.from);
      const bucket = fishboneEdgesByFrom.get(key);
      if (bucket) bucket.edges.push(edge);
      else fishboneEdgesByFrom.set(key, { layoutType, edges: [edge] });
      continue;
    }
    standardEdges.push(edge);
  }
  return /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("g", { children: [
    Array.from(fishboneEdgesByFrom.entries()).map(([fromId, entry]) => {
      if (hiddenNodeIds?.has(fromId)) return null;
      if (hiddenSummaryIds?.has(fromId)) return null;
      const from2 = layout.nodes[fromId] ?? layout.summaries[fromId];
      if (!from2) return null;
      const fishboneDir = entry.layoutType;
      const spineStartX = fishboneDir === "fishbone-left" ? from2.x + from2.width : from2.x;
      const spineY = from2.y + from2.height / 2;
      const tan = Math.tan(45 * Math.PI / 180) || 1;
      const ribs = entry.edges.map((edge) => {
        if (hiddenNodeIds?.has(edge.to)) return null;
        const to = layout.nodes[edge.to];
        if (!to) return null;
        const toCy = to.y + to.height / 2;
        const verticalDistance = Math.abs(toCy - spineY);
        const offsetX = verticalDistance / tan;
        const childRightX = to.x + to.width;
        const attachX = fishboneDir === "fishbone-left" ? Math.max(spineStartX, to.x - offsetX) : Math.min(spineStartX, childRightX + offsetX);
        return {
          edge,
          to,
          anchors: {
            axis: "x",
            dir: fishboneDir === "fishbone-left" ? 1 : -1,
            start: { x: attachX, y: spineY },
            end: fishboneDir === "fishbone-left" ? { x: to.x, y: toCy } : { x: childRightX, y: toCy }
          },
          attachX
        };
      }).filter((item) => Boolean(item));
      if (ribs.length === 0) return null;
      if (perfEnabled && perfStatsRef) perfStatsRef.current.culling.renderedEdges += ribs.length;
      const spineEndX = fishboneDir === "fishbone-left" ? Math.max(spineStartX, ...ribs.map((rib) => rib.attachX)) + 24 : Math.min(spineStartX, ...ribs.map((rib) => rib.attachX)) - 24;
      const rootTheme = nodeThemeById[fromId];
      const spineStroke = rootTheme?.paint.edgeStroke ?? "var(--km-edge-stroke)";
      const spineStrokeWidth = rootTheme?.edges?.strokeWidth ?? 2;
      const spineDasharray = rootTheme?.edges?.dasharray;
      const spineCap = rootTheme?.edges?.cap;
      const spineJoin = rootTheme?.edges?.join;
      return /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("g", { children: [
        /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
          "path",
          {
            d: `M ${spineStartX} ${spineY} L ${spineEndX} ${spineY}`,
            fill: "none",
            stroke: spineStroke,
            strokeDasharray: spineDasharray,
            strokeLinecap: spineCap,
            strokeLinejoin: spineJoin,
            strokeWidth: spineStrokeWidth
          }
        ),
        ribs.map((rib) => renderEdge(rib.edge, from2, rib.to, rib.anchors))
      ] }, `fishbone:${fromId}`);
    }),
    standardEdges.map((edge) => {
      if (hiddenNodeIds?.has(edge.to)) return null;
      if (hiddenNodeIds?.has(edge.from)) return null;
      if (hiddenSummaryIds?.has(edge.from)) return null;
      const from2 = layout.nodes[edge.from] ?? layout.summaries[edge.from];
      const to = layout.nodes[edge.to];
      if (!from2 || !to) return null;
      if (perfEnabled && perfStatsRef) perfStatsRef.current.culling.renderedEdges += 1;
      const layoutType = props.containerLayoutTypeById[String(edge.from)] ?? "logical-right";
      const anchors = resolveEdgeAnchorsForLayout(layoutType, from2, to);
      return renderEdge(edge, from2, to, anchors);
    })
  ] });
}

// ../react/src/mindmap-editor/layers/ghost-layer.tsx
var import_react2 = __toESM(require_react(), 1);

// ../react/src/mindmap-editor/utils/embed-frame.ts
function resolveExclusiveMainEmbedBlock(node) {
  const content = node.content;
  if (!content || content.schemaVersion !== 1 || content.kind !== "blocks") return null;
  if (content.blocks.some((block2) => block2.type === "richtext")) return null;
  const block = content.blocks.find((item) => {
    if (item.type !== "embed") return false;
    if (item.region !== "main") return false;
    const props = item.embed.props;
    if (!props || typeof props !== "object" || Array.isArray(props)) return false;
    return props.exclusive === true;
  });
  return block ?? null;
}
function resolveExclusiveEmbedFrameProfile(node, embedRegistry) {
  const block = resolveExclusiveMainEmbedBlock(node);
  if (!block) return null;
  const definition = embedRegistry[block.embed.type];
  return definition?.frame ?? null;
}

// ../react/src/mindmap-editor/utils/node-shape.tsx
var import_jsx_runtime6 = __toESM(require_jsx_runtime(), 1);
var CARD_V1_CORNER_INSET_FACTOR = (1 - Math.SQRT1_2) / 2;
function resolveCardV1NodeShapeSafeInsets(shape, width, height) {
  const type = shape?.type ?? "rounded-rect";
  if (type === "diamond") {
    return { insetX: Math.max(0, Math.round(width * 0.25)), insetY: Math.max(0, Math.round(height * 0.25)) };
  }
  if (type === "ellipse") {
    return {
      insetX: Math.max(0, Math.round(width * CARD_V1_CORNER_INSET_FACTOR)),
      insetY: Math.max(0, Math.round(height * CARD_V1_CORNER_INSET_FACTOR))
    };
  }
  if (type === "pill") {
    return { insetX: Math.max(0, Math.round(height * CARD_V1_CORNER_INSET_FACTOR)), insetY: 0 };
  }
  return { insetX: 0, insetY: 0 };
}
function inflateCardV1NodeSizeForShape(size, shape) {
  const type = shape?.type ?? "rounded-rect";
  if (type === "diamond") {
    return { width: Math.round(size.width * 2), height: Math.round(size.height * 2) };
  }
  if (type === "ellipse") {
    return { width: Math.round(size.width * Math.SQRT2), height: Math.round(size.height * Math.SQRT2) };
  }
  if (type === "pill") {
    const insetX = Math.max(0, Math.round(size.height * CARD_V1_CORNER_INSET_FACTOR));
    return { width: Math.round(size.width + insetX * 2), height: size.height };
  }
  return size;
}
function resolveBorderRadius(shape, width, height) {
  const type = shape?.type ?? "rounded-rect";
  if (type === "rect" || type === "diamond") return 0;
  if (type === "ellipse") return Math.min(width, height) / 2;
  if (type === "pill") return Math.min(width, height) / 2;
  return shape?.radius ?? 10;
}
function resolveNodeStrokeWidth(shape) {
  const value = shape?.strokeWidth;
  if (typeof value === "number" && Number.isFinite(value) && value >= 0) return value;
  return 2;
}
function renderNodeShape(args) {
  const shape = args.shape ?? { type: "rounded-rect", radius: 10 };
  const strokeWidth = Number.isFinite(args.strokeWidth) ? Math.max(0, args.strokeWidth) : 0;
  const inset = strokeWidth / 2;
  const x5 = args.x + inset;
  const y = args.y + inset;
  const width = Math.max(0, args.width - strokeWidth);
  const height = Math.max(0, args.height - strokeWidth);
  if (shape.type === "ellipse") {
    return /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(
      "ellipse",
      {
        cx: args.x + args.width / 2,
        cy: args.y + args.height / 2,
        fill: args.fill,
        rx: Math.max(0, width / 2),
        ry: Math.max(0, height / 2),
        stroke: args.stroke,
        strokeDasharray: shape.dasharray,
        strokeWidth,
        ...args.svgProps
      }
    );
  }
  if (shape.type === "diamond") {
    const cx = args.x + args.width / 2;
    const cy = args.y + args.height / 2;
    const d2 = [
      `M ${cx} ${args.y + inset}`,
      `L ${args.x + args.width - inset} ${cy}`,
      `L ${cx} ${args.y + args.height - inset}`,
      `L ${args.x + inset} ${cy}`,
      "Z"
    ].join(" ");
    return /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(
      "path",
      {
        d: d2,
        fill: args.fill,
        stroke: args.stroke,
        strokeDasharray: shape.dasharray,
        strokeWidth,
        ...args.svgProps
      }
    );
  }
  const rx = shape.type === "rect" ? 0 : shape.type === "pill" ? Math.min(width, height) / 2 : Math.max(0, (shape.radius ?? 10) - inset);
  return /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(
    "rect",
    {
      fill: args.fill,
      height,
      rx,
      ry: rx,
      stroke: args.stroke,
      strokeDasharray: shape.dasharray,
      strokeWidth,
      width,
      x: x5,
      y,
      ...args.svgProps
    }
  );
}

// ../react/src/mindmap-editor/utils/svg-path.ts
function translatePath3(path2, dx, dy) {
  if (!path2) return path2;
  let coordIndex = 0;
  return path2.replace(/-?\d*\.?\d+/g, (match) => {
    const value = Number(match);
    const next = coordIndex % 2 === 0 ? value + dx : value + dy;
    coordIndex += 1;
    return String(next);
  });
}

// ../react/src/mindmap-editor/layers/ghost-layer.tsx
var import_jsx_runtime7 = __toESM(require_jsx_runtime(), 1);
function GhostNodeBodyHtml(props) {
  const { doc: doc3, embedRegistry, html } = props;
  const rootRef = (0, import_react2.useRef)(null);
  const innerHtml = (0, import_react2.useMemo)(() => ({ __html: html }), [html]);
  const docRef = (0, import_react2.useRef)(doc3);
  (0, import_react2.useEffect)(() => {
    docRef.current = doc3;
  }, [doc3]);
  (0, import_react2.useEffect)(() => {
    const root = rootRef.current;
    if (!root) return;
    return mountEmbeds(root, { doc: docRef.current, embedRegistry });
  }, [embedRegistry, html, doc3.assets]);
  return /* @__PURE__ */ (0, import_jsx_runtime7.jsx)("div", { ref: rootRef, dangerouslySetInnerHTML: innerHtml });
}
function GhostLayer(props) {
  const {
    assetObjectUrlById,
    doc: doc3,
    embedRegistry,
    layout,
    drag,
    ghostDelta,
    hiddenNodeIds,
    hiddenSummaryIds,
    ghostMode,
    nodeBodyLayout,
    nodeThemeById,
    summaryThemeById,
    containerLayoutTypeById
  } = props;
  if (!drag || !ghostDelta || !hiddenNodeIds) return null;
  const dx = ghostDelta.dx;
  const dy = ghostDelta.dy;
  const shadow = "drop-shadow(0 14px 22px rgba(15, 23, 42, 0.18))";
  const summaryById = new Map(doc3.summaries.map((summary) => [summary.id, summary]));
  const renderRichGhost = ghostMode === "rich";
  const firstChildByParent = /* @__PURE__ */ new Map();
  for (const edge of layout.edges) {
    const fromId = edge.from;
    const childLayout = layout.nodes[edge.to];
    if (!childLayout) continue;
    const existing = firstChildByParent.get(fromId);
    if (!existing) {
      firstChildByParent.set(fromId, edge.to);
      continue;
    }
    const existingLayout = layout.nodes[existing];
    if (!existingLayout || childLayout.y < existingLayout.y) {
      firstChildByParent.set(fromId, edge.to);
    }
  }
  return /* @__PURE__ */ (0, import_jsx_runtime7.jsxs)("g", { "data-export-exclude": "true", style: { pointerEvents: "none", filter: shadow }, children: [
    layout.edges.map((edge) => {
      if (!hiddenNodeIds.has(edge.to)) return null;
      if (edge.to === drag.nodeId) return null;
      const fromInSubtree = hiddenNodeIds.has(edge.from) || hiddenSummaryIds?.has(edge.from);
      if (!fromInSubtree) return null;
      const fromBase = layout.nodes[edge.from] ?? layout.summaries[edge.from];
      const toBase = layout.nodes[edge.to];
      if (!fromBase || !toBase) return null;
      const from2 = { x: fromBase.x + dx, y: fromBase.y + dy, width: fromBase.width, height: fromBase.height };
      const to = { x: toBase.x + dx, y: toBase.y + dy, width: toBase.width, height: toBase.height };
      const theme = nodeThemeById[edge.to];
      const stroke = theme?.incomingEdge?.strokeColor ?? theme?.paint.edgeStroke ?? "var(--km-edge-stroke)";
      const strokeWidth = theme?.incomingEdge?.strokeWidth ?? theme?.edges?.strokeWidth ?? 2;
      const dasharray = theme?.incomingEdge?.dasharray ?? theme?.edges?.dasharray;
      const cap = theme?.incomingEdge?.cap ?? theme?.edges?.cap;
      const join2 = theme?.incomingEdge?.join ?? theme?.edges?.join;
      const routeType = theme?.incomingEdge?.routeType ?? theme?.edges?.routeType ?? "cubic";
      const routeOptions = theme?.incomingEdge?.routeOptions ?? theme?.edges?.routeOptions;
      const layoutType = containerLayoutTypeById[String(edge.from)] ?? "logical-right";
      const isFishboneLayout = layoutType === "fishbone-left" || layoutType === "fishbone-right";
      const anchors = resolveEdgeAnchorsForLayout(layoutType, from2, to);
      const routed = (() => {
        if (routeType === "tapered") {
          return {
            path: routeTaperedEdgePath({
              from: from2,
              to,
              startWidth: Math.max(1, strokeWidth * 2),
              endWidth: Math.max(0.6, strokeWidth * 0.5),
              anchorsOverride: anchors
            }),
            renderMode: "fill"
          };
        }
        if (routeType === "center-quadratic-tapered" && !isFishboneLayout) {
          return {
            path: routeCenterQuadraticTaperedEdgePath({
              from: from2,
              to,
              anchors,
              containerWidth: layout.bounds.width,
              containerHeight: layout.bounds.height,
              startWidth: Math.max(1, strokeWidth * 2),
              endWidth: Math.max(0.6, strokeWidth * 0.5)
            }),
            renderMode: "fill"
          };
        }
        if (routeType === "edge-lead-quadratic-tapered" && !isFishboneLayout) {
          return {
            path: routeEdgeLeadQuadraticTaperedEdgePath({
              from: from2,
              to,
              anchors,
              startWidth: Math.max(1, strokeWidth * 2),
              endWidth: Math.max(0.6, strokeWidth * 0.5),
              options: routeOptions?.["edge-lead-quadratic"]
            }),
            renderMode: "fill"
          };
        }
        if (routeType === "center-quadratic" && !isFishboneLayout) {
          return {
            path: routeCenterQuadraticEdgePath({
              from: from2,
              to,
              anchors,
              containerWidth: layout.bounds.width,
              containerHeight: layout.bounds.height
            }),
            renderMode: "stroke"
          };
        }
        if (routeType === "cubic-tail" && !isFishboneLayout) {
          const startFromCenter = firstChildByParent.get(edge.from) === edge.to;
          return {
            path: routeCubicTailEdgePath({
              from: from2,
              to,
              anchors,
              startFromCenter,
              options: routeOptions?.["cubic-tail"]
            }),
            renderMode: "stroke"
          };
        }
        const fallbackRouteType = isFishboneLayout && (routeType === "center-quadratic" || routeType === "center-quadratic-tapered" || routeType === "edge-lead-quadratic" || routeType === "edge-lead-quadratic-tapered" || routeType === "cubic-tail") ? "cubic" : routeType;
        return {
          path: routeEdgePath(fallbackRouteType, from2, to, anchors, routeOptions),
          renderMode: "stroke"
        };
      })();
      return routed.renderMode === "fill" ? /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(
        "path",
        {
          d: routed.path,
          fill: stroke,
          opacity: 0.92
        },
        `ghost-edge-${edge.id}`
      ) : /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(
        "path",
        {
          d: routed.path,
          fill: "none",
          stroke,
          strokeDasharray: dasharray,
          strokeLinecap: cap,
          strokeLinejoin: join2,
          strokeWidth
        },
        `ghost-edge-${edge.id}`
      );
    }),
    hiddenSummaryIds ? Object.values(layout.summaries).map((summaryLayout) => {
      if (!hiddenSummaryIds.has(summaryLayout.id)) return null;
      const theme = summaryThemeById[summaryLayout.id];
      const stroke = theme?.paint.summaryStroke ?? "var(--km-summary-stroke)";
      return /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(
        "path",
        {
          d: translatePath3(summaryLayout.bracketPath, dx, dy),
          fill: "none",
          stroke,
          strokeWidth: 2
        },
        `ghost-bracket-${summaryLayout.id}`
      );
    }) : null,
    Object.entries(layout.nodes).map(([nodeId, nodeLayout]) => {
      if (!hiddenNodeIds.has(nodeId)) return null;
      const node = doc3.nodes[nodeId];
      if (!node) return null;
      const hasExclusiveEmbedNode = Boolean(resolveExclusiveMainEmbedBlock(node));
      const embedFrame = resolveExclusiveEmbedFrameProfile(node, embedRegistry);
      const effectiveNodeShape = embedFrame?.nodeShape ?? nodeThemeById[nodeId]?.nodeShape;
      const shouldMountEmbeds = renderRichGhost && (() => {
        const content = node.content;
        if (!content || content.schemaVersion !== 1 || content.kind !== "blocks") return false;
        return content.blocks.some((block) => block.type === "embed" && block.embed.type === "kmind:protyle");
      })();
      const bodyHtml = renderRichGhost ? buildNodeBodyHtml(doc3, nodeId, null, assetObjectUrlById, void 0, { nodeBodyLayout, embedRegistry }) : "";
      const theme = nodeThemeById[nodeId];
      const tokens = theme?.layout;
      const paint = theme?.paint;
      const effectivePaint = embedFrame?.paint && paint ? { ...paint, ...embedFrame.paint } : paint;
      const fill = effectivePaint?.nodeFill ?? "var(--km-node-fill)";
      const stroke = effectivePaint?.nodeStrokeSelected ?? "var(--km-node-stroke-selected)";
      const isBaselineBodyLayout = nodeBodyLayout === "baseline-v1";
      const baselineOptions = theme?.incomingEdge?.routeOptions?.["baseline-fork"] ?? theme?.edges?.routeOptions?.["baseline-fork"];
      const baselineStroke = theme?.incomingEdge?.strokeColor ?? effectivePaint?.edgeStroke ?? "var(--km-edge-stroke)";
      const baselineStrokeWidth = theme?.incomingEdge?.strokeWidth ?? theme?.edges?.strokeWidth ?? 2;
      const baselineDasharray = theme?.incomingEdge?.dasharray ?? theme?.edges?.dasharray;
      const baselineCap = theme?.incomingEdge?.cap ?? theme?.edges?.cap;
      const baselineJoin = theme?.incomingEdge?.join ?? theme?.edges?.join;
      const baselineY = resolveBaselineForkBaselineY(nodeLayout, baselineOptions) + dy;
      const isRootNode = !node.parentId && !node.parentSummaryId;
      const resolveLayoutNumber = (value, fallback) => {
        if (typeof value !== "number" || !Number.isFinite(value)) return fallback;
        return Math.max(0, Math.round(value));
      };
      const basePaddingX = resolveLayoutNumber(embedFrame?.layout?.paddingX, resolveLayoutNumber(tokens?.paddingX, nodePaddingX));
      const basePaddingY = resolveLayoutNumber(embedFrame?.layout?.paddingY, resolveLayoutNumber(tokens?.paddingY, nodePaddingY));
      const effectivePaddingX = hasExclusiveEmbedNode && !(typeof embedFrame?.layout?.paddingX === "number") ? Math.min(basePaddingX, exclusiveEmbedPaddingX) : basePaddingX;
      const effectivePaddingY = hasExclusiveEmbedNode && !(typeof embedFrame?.layout?.paddingY === "number") ? Math.min(basePaddingY, exclusiveEmbedPaddingY) : basePaddingY;
      const effectiveTextAlign = (() => {
        const align = embedFrame?.layout?.textAlign;
        if (typeof align === "string") return align;
        return hasExclusiveEmbedNode ? "left" : tokens?.textAlign ?? "left";
      })();
      const effectiveFontSize = (() => {
        const value = embedFrame?.layout?.fontSize;
        if (typeof value === "number" && Number.isFinite(value) && value > 0) return value;
        const themeValue = tokens?.fontSize;
        if (typeof themeValue === "number" && Number.isFinite(themeValue) && themeValue > 0) return themeValue;
        return nodeFontSize;
      })();
      const effectiveFontFamily = (() => {
        const value = embedFrame?.layout?.fontFamily;
        if (typeof value === "string" && value.trim()) return value;
        const themeValue = tokens?.fontFamily;
        if (typeof themeValue === "string" && themeValue.trim()) return themeValue;
        return nodeFontFamily;
      })();
      const effectiveFontWeight = (() => {
        const value = embedFrame?.layout?.fontWeight;
        if (typeof value === "number" && Number.isFinite(value)) return value;
        const themeValue = tokens?.fontWeight;
        if (typeof themeValue === "number" && Number.isFinite(themeValue)) return themeValue;
        return 400;
      })();
      const effectiveLineHeight = (() => {
        const value = embedFrame?.layout?.lineHeight;
        if (typeof value === "number" && Number.isFinite(value) && value > 0) return value;
        const themeValue = tokens?.lineHeight;
        if (typeof themeValue === "number" && Number.isFinite(themeValue) && themeValue > 0) return themeValue;
        return nodeLineHeight;
      })();
      const shapeSafeInsets = nodeBodyLayout === "card-v1" ? resolveCardV1NodeShapeSafeInsets(effectiveNodeShape, nodeLayout.width, nodeLayout.height) : { insetX: 0, insetY: 0 };
      const safePaddingX = effectivePaddingX + shapeSafeInsets.insetX;
      const safePaddingY = effectivePaddingY + shapeSafeInsets.insetY;
      return /* @__PURE__ */ (0, import_jsx_runtime7.jsxs)("g", { children: [
        isBaselineBodyLayout ? null : renderNodeShape({
          x: nodeLayout.x + dx,
          y: nodeLayout.y + dy,
          width: nodeLayout.width,
          height: nodeLayout.height,
          shape: effectiveNodeShape,
          fill,
          stroke,
          strokeWidth: resolveNodeStrokeWidth(effectiveNodeShape)
        }),
        isBaselineBodyLayout && !isRootNode ? /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(
          "path",
          {
            d: `M ${nodeLayout.x + dx} ${baselineY} H ${nodeLayout.x + dx + nodeLayout.width}`,
            fill: "none",
            pointerEvents: "none",
            stroke: baselineStroke,
            strokeDasharray: baselineDasharray,
            strokeLinecap: baselineCap,
            strokeLinejoin: baselineJoin,
            strokeWidth: baselineStrokeWidth,
            vectorEffect: "non-scaling-stroke"
          }
        ) : null,
        /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(
          "foreignObject",
          {
            height: nodeLayout.height,
            width: nodeLayout.width,
            x: nodeLayout.x + dx,
            y: nodeLayout.y + dy,
            children: /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(
              "div",
              {
                "data-node-id": nodeId,
                ...{ xmlns: "http://www.w3.org/1999/xhtml" },
                style: {
                  boxSizing: "border-box",
                  height: "100%",
                  width: "100%",
                  padding: `${safePaddingY}px ${safePaddingX}px`,
                  fontSize: effectiveFontSize,
                  fontFamily: effectiveFontFamily,
                  fontWeight: effectiveFontWeight,
                  lineHeight: String(effectiveLineHeight),
                  textAlign: effectiveTextAlign,
                  color: effectivePaint?.text ?? "var(--km-text)",
                  "--km-text": effectivePaint?.text ?? "var(--km-text)",
                  "--km-muted": effectivePaint?.muted ?? "var(--km-muted)",
                  "--km-border": effectivePaint?.border ?? "var(--km-border)",
                  whiteSpace: "pre-wrap",
                  wordBreak: "break-word",
                  overflow: "hidden",
                  pointerEvents: "none"
                },
                children: renderRichGhost ? /* @__PURE__ */ (0, import_jsx_runtime7.jsxs)(import_jsx_runtime7.Fragment, { children: [
                  /* @__PURE__ */ (0, import_jsx_runtime7.jsx)("style", { children: nodeRichTextCssText }),
                  shouldMountEmbeds ? /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(GhostNodeBodyHtml, { doc: doc3, embedRegistry, html: bodyHtml }) : /* @__PURE__ */ (0, import_jsx_runtime7.jsx)("div", { dangerouslySetInnerHTML: { __html: bodyHtml } })
                ] }) : node.text
              }
            )
          }
        )
      ] }, `ghost-node-${nodeId}`);
    }),
    hiddenSummaryIds ? Object.values(layout.summaries).map((summaryLayout) => {
      if (!hiddenSummaryIds.has(summaryLayout.id)) return null;
      const summary = summaryById.get(summaryLayout.id);
      if (!summary) return null;
      const theme = summaryThemeById[summaryLayout.id];
      const tokens = theme?.layout;
      const paint = theme?.paint;
      const fill = paint?.nodeFill ?? "var(--km-node-fill)";
      const stroke = paint?.nodeStrokeSelected ?? "var(--km-node-stroke-selected)";
      return /* @__PURE__ */ (0, import_jsx_runtime7.jsxs)("g", { children: [
        renderNodeShape({
          x: summaryLayout.x + dx,
          y: summaryLayout.y + dy,
          width: summaryLayout.width,
          height: summaryLayout.height,
          shape: theme?.nodeShape,
          fill,
          stroke,
          strokeWidth: resolveNodeStrokeWidth(theme?.nodeShape)
        }),
        /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(
          "foreignObject",
          {
            height: summaryLayout.height,
            width: summaryLayout.width,
            x: summaryLayout.x + dx,
            y: summaryLayout.y + dy,
            children: /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(
              "div",
              {
                ...{ xmlns: "http://www.w3.org/1999/xhtml" },
                style: {
                  boxSizing: "border-box",
                  height: "100%",
                  width: "100%",
                  padding: `${tokens?.paddingY ?? nodePaddingY}px ${tokens?.paddingX ?? nodePaddingX}px`,
                  fontSize: tokens?.fontSize ?? nodeFontSize,
                  fontFamily: tokens?.fontFamily ?? nodeFontFamily,
                  fontWeight: tokens?.fontWeight ?? 400,
                  lineHeight: String(tokens?.lineHeight ?? nodeLineHeight),
                  textAlign: tokens?.textAlign ?? "left",
                  color: paint?.text ?? "var(--km-text)",
                  "--km-text": paint?.text ?? "var(--km-text)",
                  "--km-muted": paint?.muted ?? "var(--km-muted)",
                  "--km-border": paint?.border ?? "var(--km-border)",
                  whiteSpace: "pre-wrap",
                  wordBreak: "break-word",
                  overflow: "hidden",
                  pointerEvents: "none"
                },
                children: summary.text
              }
            )
          }
        )
      ] }, `ghost-summary-${summaryLayout.id}`);
    }) : null
  ] });
}

// ../react/src/mindmap-editor/layers/nodes.tsx
var import_react4 = __toESM(require_react(), 1);
var import_react_dom = __toESM(require_react_dom(), 1);
init_src();

// ../react/src/mindmap-editor/overlay-portal.tsx
var import_react3 = __toESM(require_react(), 1);
var import_jsx_runtime8 = __toESM(require_jsx_runtime(), 1);
var OverlayPortalContainerContext = (0, import_react3.createContext)(null);
function OverlayPortalProvider(props) {
  return /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(OverlayPortalContainerContext.Provider, { value: props.container ?? null, children: props.children });
}
function useOverlayPortalContainer() {
  return (0, import_react3.useContext)(OverlayPortalContainerContext);
}
function resolveOverlayPortalTarget(container) {
  if (typeof document === "undefined") return null;
  if (container instanceof HTMLElement) return container;
  return document.body instanceof HTMLElement ? document.body : null;
}
function hasScopedOverlayPortal(container) {
  if (typeof document === "undefined") return false;
  return container instanceof HTMLElement && container !== document.body;
}
function toOverlayPortalPoint(container, point) {
  if (!hasScopedOverlayPortal(container)) return point;
  const rect = container.getBoundingClientRect();
  return {
    x: point.x - rect.left,
    y: point.y - rect.top
  };
}

// ../react/src/mindmap-editor/utils/node-width.ts
function resolveNodeWidthHandleSide(layoutType) {
  if (layoutType === "logical-left" || layoutType === "fishbone-right") return "left";
  return "right";
}
function resolveNodeWidthResizeDirection(layoutType) {
  return resolveNodeWidthHandleSide(layoutType) === "left" ? -1 : 1;
}
function resolveNodeWidthAutoSnap(args) {
  const autoWidth = typeof args.autoWidth === "number" && Number.isFinite(args.autoWidth) && args.autoWidth > 0 ? args.autoWidth : null;
  if (autoWidth !== null) {
    const threshold = Math.max(10, Math.min(24, Math.round(autoWidth * 0.06)));
    if (Math.abs(args.candidateWidth - autoWidth) <= threshold) {
      return { width: autoWidth, snappedToAuto: true };
    }
  }
  return { width: clampNodeMainWidth(args.candidateWidth), snappedToAuto: false };
}
function resolveNodeWidthDraftFromDrag(args) {
  const candidateWidth = clampNodeMainWidth(args.startWidth + args.deltaX * args.direction);
  const snapped = resolveNodeWidthAutoSnap({
    candidateWidth,
    autoWidth: args.autoWidth
  });
  if (snapped.snappedToAuto) {
    return {
      width: snapped.width,
      snappedToAuto: true,
      contentWidth: args.restoreContentWidth ?? { mode: "auto" }
    };
  }
  return {
    width: snapped.width,
    snappedToAuto: false,
    contentWidth: { mode: "fixed", width: snapped.width }
  };
}

// ../react/src/mindmap-editor/layers/nodes.tsx
var import_jsx_runtime9 = __toESM(require_jsx_runtime(), 1);
var BUILTIN_ICON_INNER_CACHE = /* @__PURE__ */ new Map();
var KMIND_AI_COWRITE_DATA_KEY = "kmindAiCoWrite";
function readKmindAiCoWriteNodeData(data) {
  if (!data || typeof data !== "object" || Array.isArray(data)) return null;
  const raw = data[KMIND_AI_COWRITE_DATA_KEY];
  if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null;
  const schemaVersion = raw.schemaVersion;
  const state = raw.state;
  const generationId = raw.generationId;
  if (schemaVersion !== 1) return null;
  if (state !== "generating" && state !== "suggested") return null;
  if (typeof generationId !== "string" || generationId.trim().length <= 0) return null;
  return { schemaVersion: 1, state, generationId: generationId.trim() };
}
function extractSvgInnerContent(svg) {
  const start = svg.indexOf(">");
  const end = svg.lastIndexOf("</svg>");
  if (start < 0 || end < 0 || end <= start) return svg;
  return svg.slice(start + 1, end);
}
function getBuiltinIconInner(iconId) {
  const normalized = normalizeBuiltinIconId(iconId.trim());
  const cached = BUILTIN_ICON_INNER_CACHE.get(normalized);
  if (cached !== void 0) return cached;
  const svg = getBuiltinIconSvg(normalized);
  if (!svg) {
    BUILTIN_ICON_INNER_CACHE.set(normalized, null);
    return null;
  }
  const inner2 = extractSvgInnerContent(svg).trim();
  BUILTIN_ICON_INNER_CACHE.set(normalized, inner2);
  return inner2;
}
function resolveExternalIconId(link, external) {
  const custom = typeof link.iconId === "string" ? normalizeBuiltinIconId(link.iconId.trim()) : "";
  if (custom.length > 0 && custom !== "auto") return custom;
  return external?.resolveUrlBehavior?.(link.url)?.autoIconId ?? "kmind-icon://builtin/ui/link";
}
function resolveNodeChromeDirection(layoutType) {
  if (layoutType === "tree-up") return "up";
  if (layoutType === "tree-down" || layoutType === "timeline-down" || layoutType === "mindmap-both" || layoutType === "mindmap-both-auto") return "down";
  if (layoutType === "logical-left" || layoutType === "fishbone-right") return "left";
  return "right";
}
function resolveNodeChromeVector(direction) {
  if (direction === "left") return { x: -1, y: 0 };
  if (direction === "up") return { x: 0, y: -1 };
  if (direction === "down") return { x: 0, y: 1 };
  return { x: 1, y: 0 };
}
function resolveNodeChromeAnchor(args, direction) {
  const pad2 = 10;
  if (direction === "up") return { cx: args.x + args.width / 2, cy: args.y - pad2 };
  if (direction === "down") return { cx: args.x + args.width / 2, cy: args.y + args.height + pad2 };
  if (direction === "left") return { cx: args.x - pad2, cy: args.y + args.height / 2 };
  return { cx: args.x + args.width + pad2, cy: args.y + args.height / 2 };
}
function resolveNodeEntryChevronPath(direction, cx, cy) {
  if (direction === "left") return `M ${cx + 3} ${cy - 4} L ${cx - 2.5} ${cy} L ${cx + 3} ${cy + 4}`;
  if (direction === "up") return `M ${cx - 4} ${cy + 3} L ${cx} ${cy - 2.5} L ${cx + 4} ${cy + 3}`;
  if (direction === "down") return `M ${cx - 4} ${cy - 3} L ${cx} ${cy + 2.5} L ${cx + 4} ${cy - 3}`;
  return `M ${cx - 3} ${cy - 4} L ${cx + 2.5} ${cy} L ${cx - 3} ${cy + 4}`;
}
function resolveNodeChromeScreenPoint(event) {
  const svg = event.currentTarget.ownerSVGElement;
  const rect = svg?.getBoundingClientRect() ?? null;
  if (!rect) return { x: event.clientX, y: event.clientY };
  return { x: event.clientX - rect.left, y: event.clientY - rect.top };
}
function Nodes(props) {
  const overlayPortalContainer = useOverlayPortalContainer();
  const overlayPortalTarget = resolveOverlayPortalTarget(overlayPortalContainer);
  const scopedOverlayPortal = hasScopedOverlayPortal(overlayPortalContainer);
  const {
    assetObjectUrlById,
    assetObjectUrlVersion,
    builtinIconSymbolPrefix,
    backlinksIndex,
    doc: doc3,
    external,
    layoutTypeById,
    collapseToggleVisibility,
    showNodeWidthResizeHandle,
    showAddChildButton,
    showNodeMenuTrigger,
    canRequestAddChild,
    externalLinkPlacement,
    blurViewState,
    nodeBodyLayout,
    nodeHtmlCache,
    optimizeEmbedMounting,
    progressByNodeId,
    embedRegistry,
    hiddenNodeIds,
    visibleNodeIds,
    highlightId,
    editing,
    forceCursor,
    layout,
    nodeThemeById,
    submap,
    onOpenLinksPanel,
    onRequestSelectionToolbarPopover,
    hoveredId,
    selectedNodeIds,
    selectedId,
    resizeDraft,
    onNodePointerDown,
    onNodePointerMove,
    onNodeDoubleClick,
    onNodeHoverChange,
    onToggleNodeCollapsed,
    onRequestAddChild,
    onRequestOpenNodeContextMenu,
    onNodeResizeHandlePointerDown,
    perfEnabled,
    perfStatsRef
  } = props;
  const resolvedCollapseToggleVisibility = collapseToggleVisibility ?? "always";
  const resolvedShowNodeWidthResizeHandle = showNodeWidthResizeHandle ?? false;
  const resolvedShowAddChildButton = showAddChildButton ?? true;
  const resolvedShowNodeMenuTrigger = showNodeMenuTrigger ?? true;
  const resolvedExternalLinkPlacement = externalLinkPlacement ?? "chrome";
  const hoverPreviewTimerRef = (0, import_react4.useRef)(null);
  const hoverPreviewArgsRef = (0, import_react4.useRef)(null);
  const hoverPreviewRafRef = (0, import_react4.useRef)(null);
  const [hoverPreviewRing, setHoverPreviewRing] = (0, import_react4.useState)(null);
  const cancelHoverPreview = () => {
    const timer = hoverPreviewTimerRef.current;
    if (timer !== null) {
      hoverPreviewTimerRef.current = null;
      try {
        window.clearTimeout(timer);
      } catch {
      }
    }
    const raf = hoverPreviewRafRef.current;
    if (raf !== null) {
      hoverPreviewRafRef.current = null;
      try {
        window.cancelAnimationFrame(raf);
      } catch {
      }
    }
    hoverPreviewArgsRef.current = null;
    setHoverPreviewRing(null);
  };
  const updateHoverPreviewPosition = (args) => {
    const current = hoverPreviewArgsRef.current;
    if (!current || current.url !== args.url) return;
    current.x = args.x;
    current.y = args.y;
    if (hoverPreviewRafRef.current !== null) return;
    hoverPreviewRafRef.current = window.requestAnimationFrame(() => {
      hoverPreviewRafRef.current = null;
      const latest = hoverPreviewArgsRef.current;
      if (!latest || latest.url !== args.url) return;
      setHoverPreviewRing((prev) => prev ? { ...prev, x: latest.x, y: latest.y } : prev);
    });
  };
  const scheduleHoverPreview = (args) => {
    if (!external?.previewUrl) return;
    const url = args.url.trim();
    if (!external.resolveUrlBehavior?.(url)?.canPreview) return;
    cancelHoverPreview();
    hoverPreviewArgsRef.current = { url, x: args.x, y: args.y };
    setHoverPreviewRing({ x: args.x, y: args.y, key: `${Date.now()}_${Math.random().toString(16).slice(2)}` });
    hoverPreviewTimerRef.current = window.setTimeout(() => {
      hoverPreviewTimerRef.current = null;
      const pending = hoverPreviewArgsRef.current;
      if (!pending || pending.url !== url) return;
      void external.previewUrl?.({ url: pending.url, x: pending.x, y: pending.y });
      cancelHoverPreview();
    }, 1e3);
  };
  (0, import_react4.useEffect)(() => cancelHoverPreview, []);
  const [collapseToggleHoverId, setCollapseToggleHoverId] = (0, import_react4.useState)(null);
  const collapseToggleHoverIdRef = (0, import_react4.useRef)(collapseToggleHoverId);
  (0, import_react4.useEffect)(() => {
    collapseToggleHoverIdRef.current = collapseToggleHoverId;
  }, [collapseToggleHoverId]);
  const collapseToggleHideTimerRef = (0, import_react4.useRef)(null);
  (0, import_react4.useEffect)(() => {
    if (resolvedCollapseToggleVisibility !== "hover") {
      const handle = collapseToggleHideTimerRef.current;
      if (handle !== null) {
        collapseToggleHideTimerRef.current = null;
        try {
          window.clearTimeout(handle);
        } catch {
        }
      }
      if (collapseToggleHoverIdRef.current !== null) setCollapseToggleHoverId(null);
      return;
    }
    if (hoveredId) {
      const handle = collapseToggleHideTimerRef.current;
      if (handle !== null) {
        collapseToggleHideTimerRef.current = null;
        try {
          window.clearTimeout(handle);
        } catch {
        }
      }
      if (collapseToggleHoverIdRef.current !== hoveredId) setCollapseToggleHoverId(hoveredId);
      return;
    }
    if (!collapseToggleHoverIdRef.current) return;
    if (collapseToggleHideTimerRef.current !== null) return;
    collapseToggleHideTimerRef.current = window.setTimeout(() => {
      collapseToggleHideTimerRef.current = null;
      setCollapseToggleHoverId(null);
    }, 3e3);
  }, [hoveredId, resolvedCollapseToggleVisibility]);
  (0, import_react4.useEffect)(() => {
    return () => {
      const handle = collapseToggleHideTimerRef.current;
      if (handle === null) return;
      collapseToggleHideTimerRef.current = null;
      try {
        window.clearTimeout(handle);
      } catch {
      }
    };
  }, []);
  const collapseToggleVisibleHoverId = resolvedCollapseToggleVisibility === "hover" ? collapseToggleHoverId : hoveredId;
  const htmlCacheRef = (0, import_react4.useRef)(/* @__PURE__ */ new Map());
  const htmlCacheCountersRef = (0, import_react4.useRef)({ hits: 0, misses: 0, builds: 0 });
  (0, import_react4.useEffect)(() => {
    const cache = htmlCacheRef.current;
    if (!nodeHtmlCache.enabled || nodeHtmlCache.maxEntries <= 0) {
      cache.clear();
      return;
    }
    while (cache.size > nodeHtmlCache.maxEntries) {
      const first2 = cache.keys().next().value;
      if (!first2) break;
      cache.delete(first2);
    }
  }, [nodeHtmlCache.enabled, nodeHtmlCache.maxEntries]);
  const objectIdMapRef = (0, import_react4.useRef)(/* @__PURE__ */ new WeakMap());
  const objectIdSeqRef = (0, import_react4.useRef)(1);
  const resolveObjectId = (value) => {
    if (!value || typeof value !== "object") return 0;
    const map2 = objectIdMapRef.current;
    const existing = map2.get(value);
    if (existing !== void 0) return existing;
    const next = objectIdSeqRef.current;
    objectIdSeqRef.current += 1;
    map2.set(value, next);
    return next;
  };
  const blurKey = `${blurViewState.defaultVisibility}:${resolveObjectId(blurViewState.nodeOverrides)}:${resolveObjectId(blurViewState.segmentOverrides)}`;
  const nodeIdsToRender = visibleNodeIds ? Array.from(visibleNodeIds) : Object.keys(layout.nodes);
  const measureKeyCacheRef = (0, import_react4.useRef)(/* @__PURE__ */ new WeakMap());
  if (perfEnabled && perfStatsRef) {
    const counters = htmlCacheCountersRef.current;
    perfStatsRef.current.nodeHtml.cacheEnabled = nodeHtmlCache.enabled;
    perfStatsRef.current.nodeHtml.cacheEntries = htmlCacheRef.current.size;
    perfStatsRef.current.nodeHtml.cacheHits = counters.hits;
    perfStatsRef.current.nodeHtml.cacheMisses = counters.misses;
    perfStatsRef.current.nodeHtml.buildCount = counters.builds;
  }
  const hoverPreviewRingPosition = hoverPreviewRing ? toOverlayPortalPoint(overlayPortalContainer, { x: hoverPreviewRing.x + 12, y: hoverPreviewRing.y + 12 }) : null;
  const hoverPreviewRingNode = hoverPreviewRing && hoverPreviewRingPosition && overlayPortalTarget ? (0, import_react_dom.createPortal)(
    /* @__PURE__ */ (0, import_jsx_runtime9.jsxs)(
      "div",
      {
        style: {
          position: scopedOverlayPortal ? "absolute" : "fixed",
          left: hoverPreviewRingPosition.x,
          top: hoverPreviewRingPosition.y,
          width: 18,
          height: 18,
          pointerEvents: "none",
          zIndex: 2147483647,
          opacity: 0.92
        },
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime9.jsx)("style", { children: `
@keyframes km-siyuan-hover-preview-progress {
  from { stroke-dashoffset: 62.832; }
  to { stroke-dashoffset: 0; }
}
` }),
          /* @__PURE__ */ (0, import_jsx_runtime9.jsxs)("svg", { width: "18", height: "18", viewBox: "0 0 24 24", fill: "none", "aria-hidden": "true", children: [
            /* @__PURE__ */ (0, import_jsx_runtime9.jsx)("circle", { cx: "12", cy: "12", r: "10", stroke: "rgba(148, 163, 184, 0.35)", strokeWidth: "2.5" }),
            /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(
              "circle",
              {
                cx: "12",
                cy: "12",
                r: "10",
                stroke: "rgba(148, 163, 184, 0.9)",
                strokeWidth: "2.5",
                strokeLinecap: "round",
                strokeDasharray: "62.832",
                strokeDashoffset: "62.832",
                style: { animation: "km-siyuan-hover-preview-progress 1s linear forwards" },
                transform: "rotate(-90 12 12)"
              }
            )
          ] })
        ]
      },
      hoverPreviewRing.key
    ),
    overlayPortalTarget
  ) : null;
  return /* @__PURE__ */ (0, import_jsx_runtime9.jsxs)(import_jsx_runtime9.Fragment, { children: [
    hoverPreviewRingNode,
    /* @__PURE__ */ (0, import_jsx_runtime9.jsx)("g", { children: nodeIdsToRender.map((nodeId) => {
      const nodeLayout = layout.nodes[nodeId];
      if (!nodeLayout) return null;
      const node = doc3.nodes[nodeId];
      if (!node) return null;
      if (hiddenNodeIds?.has(nodeId)) return null;
      if (perfEnabled && perfStatsRef) perfStatsRef.current.culling.renderedNodes += 1;
      const resolvedTheme = nodeThemeById[nodeId];
      const nodeLayoutTokens = resolvedTheme?.layout;
      const nodePaint = resolvedTheme?.paint;
      const embedFrame = resolveExclusiveEmbedFrameProfile(node, embedRegistry);
      const effectiveNodeShape = embedFrame?.nodeShape ?? resolvedTheme?.nodeShape;
      const effectivePaint = embedFrame?.paint && nodePaint ? { ...nodePaint, ...embedFrame.paint } : nodePaint;
      const isDark = resolvedTheme?.variantId === "dark";
      const isSelected = selectedNodeIds.has(nodeId);
      const isPrimary = selectedId === nodeId;
      const isHovered = hoveredId === nodeId;
      const isCollapseToggleHovered = collapseToggleVisibleHoverId === nodeId;
      const stroke = effectivePaint?.nodeStroke ?? "var(--km-node-stroke)";
      const fill = effectivePaint?.nodeFill ?? "var(--km-node-fill)";
      const resolvedStroke = highlightId === nodeId ? "#22c55e" : stroke;
      const aiCoWrite = readKmindAiCoWriteNodeData(node.data);
      const aiCoWriteState = aiCoWrite?.state ?? null;
      const isAiCoWritePending = Boolean(aiCoWriteState);
      const isAiCoWriteAnimating = aiCoWriteState === "generating";
      const aiNodeOpacity = isAiCoWritePending ? 0.62 : 1;
      const aiRainbowId = `km-ai-rainbow-${builtinIconSymbolPrefix}`;
      const blurVisibility = blurViewState.nodeOverrides?.[nodeId] ?? blurViewState.defaultVisibility;
      const isNodeBlurred = node.attrs?.blur?.kind === "node" && blurVisibility === "hidden";
      const nodeLinks = getNodeLinks(node);
      const leadingExternalLink = resolvedExternalLinkPlacement === "title-leading" && nodeBodyLayout === "card-v1" ? nodeLinks.find((link) => link.kind === "external") ?? null : null;
      const leadingExternalLinkHtml = leadingExternalLink ? {
        url: leadingExternalLink.url,
        label: typeof leadingExternalLink.label === "string" && leadingExternalLink.label.trim().length > 0 ? leadingExternalLink.label.trim() : leadingExternalLink.url,
        iconHtml: external?.resolveExternalLinkIconHtml?.({
          url: leadingExternalLink.url,
          link: leadingExternalLink,
          node
        }) ?? getBuiltinIconSvg(resolveExternalIconId(leadingExternalLink, external)) ?? void 0
      } : null;
      const { hasExclusiveEmbedNode, exclusiveResizableEmbedBlockId } = (() => {
        const content = node.content;
        if (!content || content.schemaVersion !== 1 || content.kind !== "blocks") {
          return { hasExclusiveEmbedNode: false, exclusiveResizableEmbedBlockId: null };
        }
        const blocks = content.blocks;
        const hasExclusiveEmbed = blocks.some((block) => {
          if (block.type !== "embed") return false;
          if (block.region !== "main") return false;
          const props2 = block.embed.props;
          if (!props2 || typeof props2 !== "object" || Array.isArray(props2)) return false;
          return props2.exclusive === true;
        });
        if (!hasExclusiveEmbed) {
          return { hasExclusiveEmbedNode: false, exclusiveResizableEmbedBlockId: null };
        }
        const candidate = blocks.find((block) => {
          if (block.type !== "embed") return false;
          if (block.region !== "main") return false;
          const props2 = block.embed.props;
          if (!props2 || typeof props2 !== "object" || Array.isArray(props2)) return false;
          return props2.exclusive === true && props2.resizable === true;
        });
        return { hasExclusiveEmbedNode: true, exclusiveResizableEmbedBlockId: candidate ? candidate.id : null };
      })();
      const hasChromeTop = (() => {
        if (nodeBodyLayout !== "card-v1") return false;
        const externalCount = nodeLinks.filter((link) => link.kind === "external").length;
        const hasExternal = resolvedExternalLinkPlacement === "title-leading" ? externalCount > 1 : externalCount > 0;
        const hasInternal = nodeLinks.some((link) => link.kind === "internal");
        const hasBacklinks = (backlinksIndex[nodeId] ?? []).length > 0;
        const backAnchorNodeId = submap?.backAnchorNodeId ?? doc3.roots[0];
        const showBack = Boolean(submap?.canGoBack && backAnchorNodeId === nodeId);
        const showLocked = Boolean(node.attrs?.locked);
        const showExternal = hasExternal;
        const showLinksPanel = hasInternal || hasBacklinks;
        const showSubmap = Boolean(node.subMapId && submap);
        return showBack || showLocked || showExternal || showLinksPanel || showSubmap;
      })();
      const resolveLayoutNumber = (value, fallback) => {
        if (typeof value !== "number" || !Number.isFinite(value)) return fallback;
        return Math.max(0, Math.round(value));
      };
      const basePaddingX = resolveLayoutNumber(embedFrame?.layout?.paddingX, resolveLayoutNumber(nodeLayoutTokens?.paddingX, nodePaddingX));
      const basePaddingY = resolveLayoutNumber(embedFrame?.layout?.paddingY, resolveLayoutNumber(nodeLayoutTokens?.paddingY, nodePaddingY));
      const effectivePaddingX = hasExclusiveEmbedNode && !(typeof embedFrame?.layout?.paddingX === "number") ? Math.min(basePaddingX, exclusiveEmbedPaddingX) : basePaddingX;
      const effectivePaddingY = hasExclusiveEmbedNode && !(typeof embedFrame?.layout?.paddingY === "number") ? Math.min(basePaddingY, exclusiveEmbedPaddingY) : basePaddingY;
      const effectiveTextAlign = (() => {
        const align = embedFrame?.layout?.textAlign;
        if (typeof align === "string") return align;
        return hasExclusiveEmbedNode ? "left" : nodeLayoutTokens?.textAlign ?? "left";
      })();
      const effectiveFontSize = (() => {
        const value = embedFrame?.layout?.fontSize;
        if (typeof value === "number" && Number.isFinite(value) && value > 0) return value;
        const themeValue = nodeLayoutTokens?.fontSize;
        if (typeof themeValue === "number" && Number.isFinite(themeValue) && themeValue > 0) return themeValue;
        return nodeFontSize;
      })();
      const effectiveFontFamily = (() => {
        const value = embedFrame?.layout?.fontFamily;
        if (typeof value === "string" && value.trim()) return value;
        const themeValue = nodeLayoutTokens?.fontFamily;
        if (typeof themeValue === "string" && themeValue.trim()) return themeValue;
        return nodeFontFamily;
      })();
      const effectiveFontWeight = (() => {
        const value = embedFrame?.layout?.fontWeight;
        if (typeof value === "number" && Number.isFinite(value)) return value;
        const themeValue = nodeLayoutTokens?.fontWeight;
        if (typeof themeValue === "number" && Number.isFinite(themeValue)) return themeValue;
        return 400;
      })();
      const effectiveLineHeight = (() => {
        const value = embedFrame?.layout?.lineHeight;
        if (typeof value === "number" && Number.isFinite(value) && value > 0) return value;
        const themeValue = nodeLayoutTokens?.lineHeight;
        if (typeof themeValue === "number" && Number.isFinite(themeValue) && themeValue > 0) return themeValue;
        return nodeLineHeight;
      })();
      const shapeSafeInsets = nodeBodyLayout === "card-v1" ? resolveCardV1NodeShapeSafeInsets(effectiveNodeShape, nodeLayout.width, nodeLayout.height) : { insetX: 0, insetY: 0 };
      const safePaddingX = effectivePaddingX + shapeSafeInsets.insetX;
      const safePaddingY = effectivePaddingY + shapeSafeInsets.insetY;
      const draft = resizeDraft?.nodeId === nodeId ? resizeDraft : null;
      const resolveBodyHtml = () => buildNodeBodyHtml(
        doc3,
        nodeId,
        blurViewState,
        assetObjectUrlById,
        draft ? { contentWidth: draft.contentWidth } : void 0,
        { nodeBodyLayout, hasChromeTop, embedRegistry, leadingExternalLink: leadingExternalLinkHtml }
      );
      const bodyHtml = (() => {
        if (!nodeHtmlCache.enabled || nodeHtmlCache.maxEntries <= 0) {
          if (perfEnabled) htmlCacheCountersRef.current.builds += 1;
          return resolveBodyHtml();
        }
        const keyParts = [
          (() => {
            const cache = measureKeyCacheRef.current;
            const cached2 = cache.get(node);
            if (cached2) return cached2;
            const built = buildNodeMeasureKey(node, doc3);
            cache.set(node, built);
            return built;
          })(),
          `body:${nodeBodyLayout}`,
          `chromeTop:${hasChromeTop ? "1" : "0"}`,
          `leadingExternal:${leadingExternalLinkHtml ? `${leadingExternalLinkHtml.url}:${leadingExternalLinkHtml.label}:${leadingExternalLinkHtml.iconHtml ?? ""}` : ""}`,
          `draft:${draft ? JSON.stringify(draft.contentWidth) : ""}`,
          `blur:${blurKey}`,
          `assetUrlV:${assetObjectUrlVersion}`
        ];
        const key = keyParts.join("|");
        const cached = htmlCacheRef.current.get(nodeId);
        if (cached?.key === key) {
          htmlCacheRef.current.delete(nodeId);
          htmlCacheRef.current.set(nodeId, cached);
          if (perfEnabled) htmlCacheCountersRef.current.hits += 1;
          return cached.html;
        }
        if (perfEnabled) htmlCacheCountersRef.current.misses += 1;
        if (perfEnabled) htmlCacheCountersRef.current.builds += 1;
        const html = resolveBodyHtml();
        htmlCacheRef.current.set(nodeId, { key, html });
        while (htmlCacheRef.current.size > nodeHtmlCache.maxEntries) {
          const first2 = htmlCacheRef.current.keys().next().value;
          if (!first2) break;
          htmlCacheRef.current.delete(first2);
        }
        return html;
      })();
      const progress = progressByNodeId[nodeId];
      const progressStats = progress && progress.total > 0 ? progress : null;
      const progressCx = nodeLayout.x + nodeLayout.width - 16 - shapeSafeInsets.insetX;
      const progressCy = nodeLayout.y + 16 + shapeSafeInsets.insetY;
      const progressRadius = 8;
      const progressCirc = Math.PI * 2 * progressRadius;
      const progressDash = progressStats ? progressCirc * Math.max(0, Math.min(1, progressStats.ratio)) : 0;
      const isBaselineBodyLayout = nodeBodyLayout === "baseline-v1";
      const baselineOptions = resolvedTheme?.incomingEdge?.routeOptions?.["baseline-fork"] ?? resolvedTheme?.edges?.routeOptions?.["baseline-fork"];
      const baselineStroke = resolvedTheme?.incomingEdge?.strokeColor ?? effectivePaint?.edgeStroke ?? "var(--km-edge-stroke)";
      const baselineStrokeWidth = resolvedTheme?.incomingEdge?.strokeWidth ?? resolvedTheme?.edges?.strokeWidth ?? 2;
      const baselineDasharray = resolvedTheme?.incomingEdge?.dasharray ?? resolvedTheme?.edges?.dasharray;
      const baselineCap = resolvedTheme?.incomingEdge?.cap ?? resolvedTheme?.edges?.cap;
      const baselineJoin = resolvedTheme?.incomingEdge?.join ?? resolvedTheme?.edges?.join;
      const baselineY = resolveBaselineForkBaselineY(nodeLayout, baselineOptions);
      const isRootNode = !node.parentId && !node.parentSummaryId;
      const baselineRouteType = resolvedTheme?.incomingEdge?.routeType ?? resolvedTheme?.edges?.routeType;
      const shouldRenderOwnBaseline = isBaselineBodyLayout && !isRootNode && baselineRouteType !== "baseline-fork";
      const childCount = node.children.reduce((count, id) => count + (doc3.nodes[id] ? 1 : 0), 0);
      const hasChildren = childCount > 0;
      const isCollapsed = Boolean(doc3.viewState?.collapsedNodeIds?.[nodeId]);
      const nodeLayoutType = layoutTypeById[nodeId] ?? "logical-right";
      const nodeChromeDirection = resolveNodeChromeDirection(nodeLayoutType);
      const nodeChromeVector = resolveNodeChromeVector(nodeChromeDirection);
      const collapseAnchor = resolveNodeChromeAnchor(nodeLayout, nodeChromeDirection);
      const showNodeEntryChrome = isPrimary && !editing;
      const showAddChildEntry = showNodeEntryChrome && Boolean(onRequestAddChild) && resolvedShowAddChildButton && (!hasChildren || !isCollapsed);
      const showNodeMenuEntry = showNodeEntryChrome && Boolean(onRequestOpenNodeContextMenu) && resolvedShowNodeMenuTrigger;
      const nodeEntryStepStart = hasChildren ? 1 : 0;
      const nodeEntrySpacing = 18;
      const resolveNodeEntryCenter = (step) => ({
        cx: collapseAnchor.cx + nodeChromeVector.x * nodeEntrySpacing * step,
        cy: collapseAnchor.cy + nodeChromeVector.y * nodeEntrySpacing * step
      });
      const addChildEntryCenter = showAddChildEntry ? resolveNodeEntryCenter(nodeEntryStepStart) : null;
      const nodeMenuEntryCenter = showNodeMenuEntry ? resolveNodeEntryCenter(nodeEntryStepStart + (showAddChildEntry ? 1 : 0)) : null;
      const nodeChromeFill = isDark ? "rgba(15, 23, 42, 0.78)" : "rgba(255, 255, 255, 0.92)";
      const nodeChromeStroke = isDark ? "rgba(226, 232, 240, 0.28)" : "rgba(15, 23, 42, 0.20)";
      const nodeChromeGlyph = isDark ? "rgba(226, 232, 240, 0.88)" : "rgba(15, 23, 42, 0.78)";
      const nodeChromeMutedGlyph = isDark ? "rgba(226, 232, 240, 0.56)" : "rgba(15, 23, 42, 0.48)";
      return /* @__PURE__ */ (0, import_jsx_runtime9.jsxs)(
        "g",
        {
          "data-node-id": nodeId,
          "data-km-ai-cowrite": aiCoWriteState ?? void 0,
          onDoubleClick: () => onNodeDoubleClick(nodeId),
          onPointerDown: (event) => onNodePointerDown(nodeId, event),
          onPointerMove: (event) => onNodePointerMove(nodeId, event),
          onPointerEnter: () => onNodeHoverChange(nodeId),
          onPointerLeave: () => onNodeHoverChange(null),
          style: { cursor: forceCursor ?? "pointer" },
          children: [
            isBaselineBodyLayout ? null : renderNodeShape({
              x: nodeLayout.x,
              y: nodeLayout.y,
              width: nodeLayout.width,
              height: nodeLayout.height,
              shape: effectiveNodeShape,
              fill,
              stroke: resolvedStroke,
              strokeWidth: resolveNodeStrokeWidth(effectiveNodeShape),
              svgProps: isAiCoWritePending ? { opacity: aiNodeOpacity } : void 0
            }),
            shouldRenderOwnBaseline ? /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(
              "path",
              {
                d: `M ${nodeLayout.x} ${baselineY} H ${nodeLayout.x + nodeLayout.width}`,
                fill: "none",
                opacity: aiNodeOpacity,
                pointerEvents: "none",
                stroke: baselineStroke,
                strokeDasharray: baselineDasharray,
                strokeLinecap: baselineCap,
                strokeLinejoin: baselineJoin,
                strokeWidth: baselineStrokeWidth,
                vectorEffect: "non-scaling-stroke"
              }
            ) : null,
            !isAiCoWritePending && isSelected ? /* @__PURE__ */ (0, import_jsx_runtime9.jsx)("g", { "data-export-exclude": "true", children: renderNodeShape({
              x: nodeLayout.x - 6,
              y: nodeLayout.y - 6,
              width: nodeLayout.width + 12,
              height: nodeLayout.height + 12,
              shape: effectiveNodeShape,
              fill: "none",
              stroke: effectivePaint?.nodeStrokeSelected ?? "var(--km-node-stroke-selected)",
              strokeWidth: isPrimary ? 2.5 : 2,
              svgProps: {
                opacity: isPrimary ? 1 : 0.85,
                pointerEvents: "none",
                vectorEffect: "non-scaling-stroke"
              }
            }) }) : !isAiCoWritePending && !isSelected && isHovered ? /* @__PURE__ */ (0, import_jsx_runtime9.jsx)("g", { "data-export-exclude": "true", children: renderNodeShape({
              x: nodeLayout.x - 6,
              y: nodeLayout.y - 6,
              width: nodeLayout.width + 12,
              height: nodeLayout.height + 12,
              shape: effectiveNodeShape,
              fill: "none",
              stroke: effectivePaint?.nodeStrokeSelected ?? "var(--km-node-stroke-selected)",
              strokeWidth: 2,
              svgProps: {
                opacity: 0.5,
                pointerEvents: "none",
                vectorEffect: "non-scaling-stroke"
              }
            }) }) : null,
            isAiCoWritePending ? /* @__PURE__ */ (0, import_jsx_runtime9.jsx)("g", { "data-export-exclude": "true", pointerEvents: "none", children: renderNodeShape({
              x: nodeLayout.x - 7,
              y: nodeLayout.y - 7,
              width: nodeLayout.width + 14,
              height: nodeLayout.height + 14,
              shape: (() => {
                const base2 = effectiveNodeShape ?? { type: "rounded-rect", radius: 10 };
                return { ...base2, dasharray: "10 7" };
              })(),
              fill: "none",
              stroke: `url(#${aiRainbowId})`,
              strokeWidth: 2.5,
              svgProps: {
                pointerEvents: "none",
                vectorEffect: "non-scaling-stroke",
                strokeLinejoin: "round",
                className: isAiCoWriteAnimating ? "kmind-ai-cowrite-dash-anim" : void 0
              }
            }) }) : null,
            editing?.type === "node" && editing.id === nodeId ? null : /* @__PURE__ */ (0, import_jsx_runtime9.jsx)("foreignObject", { height: nodeLayout.height, width: nodeLayout.width, x: nodeLayout.x, y: nodeLayout.y, children: /* @__PURE__ */ (0, import_jsx_runtime9.jsxs)(
              "div",
              {
                "data-node-id": nodeId,
                ...{ xmlns: "http://www.w3.org/1999/xhtml" },
                style: {
                  boxSizing: "border-box",
                  height: "100%",
                  width: "100%",
                  padding: `${safePaddingY}px ${safePaddingX}px`,
                  fontSize: effectiveFontSize,
                  fontFamily: effectiveFontFamily,
                  fontWeight: effectiveFontWeight,
                  lineHeight: String(effectiveLineHeight),
                  textAlign: effectiveTextAlign,
                  color: effectivePaint?.text ?? "var(--km-text)",
                  "--km-text": effectivePaint?.text ?? "var(--km-text)",
                  "--km-muted": effectivePaint?.muted ?? "var(--km-muted)",
                  "--km-border": effectivePaint?.border ?? "var(--km-border)",
                  "--km-panel": effectivePaint?.panel ?? "var(--km-panel)",
                  "--km-code-bg": isDark ? "rgba(0, 0, 0, 0.24)" : "rgba(15, 23, 42, 0.06)",
                  "--km-code-border": isDark ? "rgba(226, 232, 240, 0.14)" : "rgba(148, 163, 184, 0.35)",
                  "--km-code-token-keyword": isDark ? "rgba(196, 181, 253, 0.95)" : "rgba(124, 58, 237, 0.95)",
                  "--km-code-token-string": isDark ? "rgba(125, 211, 252, 0.95)" : "rgba(2, 132, 199, 0.95)",
                  "--km-code-token-number": isDark ? "rgba(253, 186, 116, 0.95)" : "rgba(234, 88, 12, 0.95)",
                  "--km-code-token-comment": isDark ? "rgba(148, 163, 184, 0.78)" : "rgba(100, 116, 139, 0.85)",
                  "--km-code-token-property": isDark ? "rgba(147, 197, 253, 0.95)" : "rgba(29, 78, 216, 0.95)",
                  "--km-code-token-punct": isDark ? "rgba(226, 232, 240, 0.92)" : "rgba(51, 65, 85, 0.88)",
                  overflow: "hidden",
                  pointerEvents: "auto",
                  opacity: aiNodeOpacity
                },
                children: [
                  /* @__PURE__ */ (0, import_jsx_runtime9.jsx)("style", { children: nodeRichTextCssText }),
                  /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(
                    NodeBodyHtml,
                    {
                      doc: doc3,
                      embedRegistry,
                      html: bodyHtml,
                      isBlurHidden: isNodeBlurred,
                      optimizeEmbedMounting,
                      perfEnabled,
                      perfStatsRef,
                      onExternalLinkActivate: (url) => {
                        cancelHoverPreview();
                        if (!external) return;
                        void external.openUrl(url);
                      },
                      onExternalLinkPointerEnter: (url, event) => {
                        const hoverPreviewEnabled = Boolean(external?.previewUrl) && Boolean(external?.resolveUrlBehavior?.(url)?.canPreview);
                        if (hoverPreviewEnabled) scheduleHoverPreview({ url, x: event.clientX, y: event.clientY });
                      },
                      onExternalLinkPointerMove: (url, event) => {
                        const hoverPreviewEnabled = Boolean(external?.previewUrl) && Boolean(external?.resolveUrlBehavior?.(url)?.canPreview);
                        if (hoverPreviewEnabled) updateHoverPreviewPosition({ url: url.trim(), x: event.clientX, y: event.clientY });
                      },
                      onExternalLinkPointerLeave: () => cancelHoverPreview()
                    }
                  )
                ]
              }
            ) }),
            (() => {
              if (!exclusiveResizableEmbedBlockId) return null;
              if (!isPrimary) return null;
              if (editing) return null;
              if (node.attrs?.locked || node.attrs?.readonly) return null;
              const cornerX = nodeLayout.x + nodeLayout.width;
              const cornerY = nodeLayout.y + nodeLayout.height;
              const hitSize = 28;
              const size = 16;
              const x5 = cornerX - size / 2;
              const y = cornerY - size / 2;
              const hitX = cornerX - hitSize / 2;
              const hitY = cornerY - hitSize / 2;
              const fillColor = isDark ? "rgba(15, 23, 42, 0.65)" : "rgba(255, 255, 255, 0.75)";
              const strokeColor = isDark ? "rgba(226, 232, 240, 0.22)" : "rgba(15, 23, 42, 0.16)";
              const gripColor = isDark ? "rgba(226, 232, 240, 0.68)" : "rgba(15, 23, 42, 0.48)";
              return /* @__PURE__ */ (0, import_jsx_runtime9.jsxs)(
                "g",
                {
                  "data-export-exclude": "true",
                  "data-km-action": "embed.resize",
                  "data-km-embed-block-id": exclusiveResizableEmbedBlockId,
                  style: { cursor: "nwse-resize" },
                  children: [
                    /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(
                      "rect",
                      {
                        height: hitSize,
                        width: hitSize,
                        x: hitX,
                        y: hitY,
                        fill: "transparent",
                        stroke: "none",
                        vectorEffect: "non-scaling-stroke"
                      }
                    ),
                    /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(
                      "rect",
                      {
                        height: size,
                        rx: 6,
                        ry: 6,
                        width: size,
                        x: x5,
                        y,
                        fill: fillColor,
                        stroke: strokeColor,
                        strokeWidth: 1,
                        vectorEffect: "non-scaling-stroke"
                      }
                    ),
                    /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(
                      "path",
                      {
                        d: `M ${x5 + 6} ${y + size - 6} L ${x5 + size - 6} ${y + 6}`,
                        stroke: gripColor,
                        strokeLinecap: "round",
                        strokeWidth: 1.8,
                        vectorEffect: "non-scaling-stroke",
                        pointerEvents: "none"
                      }
                    ),
                    /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(
                      "path",
                      {
                        d: `M ${x5 + 9} ${y + size - 6} L ${x5 + size - 6} ${y + 9}`,
                        stroke: gripColor,
                        strokeLinecap: "round",
                        strokeWidth: 1.8,
                        vectorEffect: "non-scaling-stroke",
                        pointerEvents: "none"
                      }
                    )
                  ]
                }
              );
            })(),
            (() => {
              if (!isPrimary) return null;
              if (editing) return null;
              if (nodeBodyLayout !== "card-v1") return null;
              if (hasExclusiveEmbedNode) return null;
              if (node.attrs?.locked || node.attrs?.readonly) return null;
              if (!resolvedShowNodeWidthResizeHandle) return null;
              const handleSide = resolveNodeWidthHandleSide(layoutTypeById[nodeId] ?? node.layout);
              const width = 12;
              const height = Math.max(24, Math.min(32, nodeLayout.height - 10));
              const x5 = handleSide === "left" ? nodeLayout.x - width / 2 : nodeLayout.x + nodeLayout.width - width / 2;
              const y = nodeLayout.y + nodeLayout.height / 2 - height / 2;
              const fillColor = isDark ? "rgba(15, 23, 42, 0.65)" : "rgba(255, 255, 255, 0.75)";
              const strokeColor = isDark ? "rgba(226, 232, 240, 0.22)" : "rgba(15, 23, 42, 0.16)";
              const gripColor = isDark ? "rgba(226, 232, 240, 0.68)" : "rgba(15, 23, 42, 0.48)";
              return /* @__PURE__ */ (0, import_jsx_runtime9.jsxs)(
                "g",
                {
                  "data-km-node-resize-handle": "true",
                  "data-export-exclude": "true",
                  onDoubleClick: (event) => {
                    event.preventDefault();
                    event.stopPropagation();
                  },
                  onPointerDown: (event) => onNodeResizeHandlePointerDown(nodeId, event),
                  style: { cursor: "ew-resize" },
                  children: [
                    /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(
                      "rect",
                      {
                        height,
                        rx: 6,
                        ry: 6,
                        width,
                        x: x5,
                        y,
                        fill: fillColor,
                        stroke: strokeColor,
                        strokeWidth: 1,
                        vectorEffect: "non-scaling-stroke"
                      }
                    ),
                    /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(
                      "path",
                      {
                        d: `M ${x5 + width / 2} ${y + height / 2 - 7} L ${x5 + width / 2} ${y + height / 2 + 7}`,
                        stroke: gripColor,
                        strokeLinecap: "round",
                        strokeWidth: 2,
                        vectorEffect: "non-scaling-stroke",
                        pointerEvents: "none"
                      }
                    )
                  ]
                }
              );
            })(),
            hasChildren ? resolvedCollapseToggleVisibility === "always" || isCollapsed || isCollapseToggleHovered || isSelected ? /* @__PURE__ */ (0, import_jsx_runtime9.jsxs)(
              "g",
              {
                "data-export-exclude": "true",
                "data-km-node-chrome": "collapse-toggle",
                onPointerDown: (event) => {
                  event.preventDefault();
                  event.stopPropagation();
                  onToggleNodeCollapsed(nodeId);
                },
                style: { cursor: "pointer" },
                children: [
                  /* @__PURE__ */ (0, import_jsx_runtime9.jsx)("title", { children: isCollapsed ? `\u5C55\u5F00 ${childCount} \u4E2A\u5B50\u8282\u70B9` : "\u6298\u53E0\u5B50\u8282\u70B9" }),
                  isCollapsed ? (() => {
                    const label = childCount > 99 ? "99+" : String(childCount);
                    const width = Math.max(16, label.length * 6 + 10);
                    const height = 16;
                    const x5 = collapseAnchor.cx - width / 2;
                    const y = collapseAnchor.cy - height / 2;
                    return /* @__PURE__ */ (0, import_jsx_runtime9.jsxs)(import_jsx_runtime9.Fragment, { children: [
                      /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(
                        "rect",
                        {
                          fill: nodeChromeFill,
                          height,
                          rx: height / 2,
                          ry: height / 2,
                          stroke: nodeChromeStroke,
                          strokeWidth: 1,
                          vectorEffect: "non-scaling-stroke",
                          width,
                          x: x5,
                          y
                        }
                      ),
                      /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(
                        "text",
                        {
                          dominantBaseline: "central",
                          fill: nodeChromeGlyph,
                          fontSize: 8.5,
                          fontWeight: 650,
                          pointerEvents: "none",
                          textAnchor: "middle",
                          x: collapseAnchor.cx,
                          y: collapseAnchor.cy + 0.2,
                          children: label
                        }
                      )
                    ] });
                  })() : /* @__PURE__ */ (0, import_jsx_runtime9.jsxs)(import_jsx_runtime9.Fragment, { children: [
                    /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(
                      "circle",
                      {
                        cx: collapseAnchor.cx,
                        cy: collapseAnchor.cy,
                        fill: nodeChromeFill,
                        r: 7,
                        stroke: nodeChromeStroke,
                        strokeWidth: 1,
                        vectorEffect: "non-scaling-stroke"
                      }
                    ),
                    /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(
                      "path",
                      {
                        d: `M ${collapseAnchor.cx - 3.5} ${collapseAnchor.cy} L ${collapseAnchor.cx + 3.5} ${collapseAnchor.cy}`,
                        pointerEvents: "none",
                        stroke: nodeChromeGlyph,
                        strokeLinecap: "round",
                        strokeWidth: 1.5,
                        vectorEffect: "non-scaling-stroke"
                      }
                    )
                  ] })
                ]
              }
            ) : null : null,
            addChildEntryCenter ? /* @__PURE__ */ (0, import_jsx_runtime9.jsxs)(
              "g",
              {
                "data-export-exclude": "true",
                "data-km-node-chrome": "add-child",
                onPointerDown: (event) => {
                  event.preventDefault();
                  event.stopPropagation();
                  if (canRequestAddChild === false) return;
                  onRequestAddChild?.(nodeId);
                },
                style: { cursor: canRequestAddChild === false ? "not-allowed" : "pointer", opacity: canRequestAddChild === false ? 0.55 : 1 },
                children: [
                  /* @__PURE__ */ (0, import_jsx_runtime9.jsx)("title", { children: "\u6DFB\u52A0\u5B50\u8282\u70B9" }),
                  /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(
                    "circle",
                    {
                      cx: addChildEntryCenter.cx,
                      cy: addChildEntryCenter.cy,
                      fill: nodeChromeFill,
                      r: 7,
                      stroke: nodeChromeStroke,
                      strokeWidth: 1,
                      vectorEffect: "non-scaling-stroke"
                    }
                  ),
                  /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(
                    "path",
                    {
                      d: `M ${addChildEntryCenter.cx} ${addChildEntryCenter.cy - 3.5} L ${addChildEntryCenter.cx} ${addChildEntryCenter.cy + 3.5}`,
                      pointerEvents: "none",
                      stroke: nodeChromeGlyph,
                      strokeLinecap: "round",
                      strokeWidth: 1.5,
                      vectorEffect: "non-scaling-stroke"
                    }
                  ),
                  /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(
                    "path",
                    {
                      d: `M ${addChildEntryCenter.cx - 3.5} ${addChildEntryCenter.cy} L ${addChildEntryCenter.cx + 3.5} ${addChildEntryCenter.cy}`,
                      pointerEvents: "none",
                      stroke: nodeChromeGlyph,
                      strokeLinecap: "round",
                      strokeWidth: 1.5,
                      vectorEffect: "non-scaling-stroke"
                    }
                  )
                ]
              }
            ) : null,
            nodeMenuEntryCenter ? /* @__PURE__ */ (0, import_jsx_runtime9.jsxs)(
              "g",
              {
                "data-export-exclude": "true",
                "data-km-node-chrome": "node-menu",
                onPointerDown: (event) => {
                  event.preventDefault();
                  event.stopPropagation();
                  const point = resolveNodeChromeScreenPoint(event);
                  onRequestOpenNodeContextMenu?.({ ...point, nodeId });
                },
                style: { cursor: "pointer" },
                children: [
                  /* @__PURE__ */ (0, import_jsx_runtime9.jsx)("title", { children: "\u8282\u70B9\u83DC\u5355" }),
                  /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(
                    "circle",
                    {
                      cx: nodeMenuEntryCenter.cx,
                      cy: nodeMenuEntryCenter.cy,
                      fill: "transparent",
                      r: 8,
                      stroke: "none"
                    }
                  ),
                  /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(
                    "path",
                    {
                      d: resolveNodeEntryChevronPath(nodeChromeDirection, nodeMenuEntryCenter.cx, nodeMenuEntryCenter.cy),
                      fill: "none",
                      pointerEvents: "none",
                      stroke: nodeChromeMutedGlyph,
                      strokeLinecap: "round",
                      strokeLinejoin: "round",
                      strokeWidth: 1.8,
                      vectorEffect: "non-scaling-stroke"
                    }
                  )
                ]
              }
            ) : null,
            progressStats && progressStats.variant === "ring" ? /* @__PURE__ */ (0, import_jsx_runtime9.jsxs)("g", { children: [
              /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(
                "circle",
                {
                  cx: progressCx,
                  cy: progressCy,
                  fill: "none",
                  opacity: 0.55,
                  stroke: isDark ? "rgba(148, 163, 184, 0.55)" : "rgba(100, 116, 139, 0.45)",
                  strokeWidth: 2,
                  r: progressRadius
                }
              ),
              /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(
                "circle",
                {
                  cx: progressCx,
                  cy: progressCy,
                  fill: "none",
                  stroke: progressStats.done >= progressStats.total ? "#22c55e" : "#3b82f6",
                  strokeDasharray: `${progressDash} ${progressCirc}`,
                  strokeLinecap: "round",
                  strokeWidth: 2.5,
                  r: progressRadius,
                  transform: `rotate(-90 ${progressCx} ${progressCy})`
                }
              )
            ] }) : null,
            progressStats && progressStats.variant === "bar" ? /* @__PURE__ */ (0, import_jsx_runtime9.jsxs)("g", { children: [
              /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(
                "rect",
                {
                  fill: isDark ? "rgba(148, 163, 184, 0.35)" : "rgba(100, 116, 139, 0.25)",
                  height: 4,
                  rx: 2,
                  width: Math.max(16, nodeLayout.width - 24),
                  x: nodeLayout.x + 12,
                  y: nodeLayout.y + nodeLayout.height - 8
                }
              ),
              /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(
                "rect",
                {
                  fill: progressStats.done >= progressStats.total ? "#22c55e" : "#3b82f6",
                  height: 4,
                  rx: 2,
                  width: Math.max(0, Math.max(16, nodeLayout.width - 24) * Math.max(0, Math.min(1, progressStats.ratio))),
                  x: nodeLayout.x + 12,
                  y: nodeLayout.y + nodeLayout.height - 8
                }
              )
            ] }) : null,
            (() => {
              const chromeStroke = typeof nodePaint?.text === "string" && nodePaint.text.trim().length > 0 ? nodePaint.text : typeof nodePaint?.muted === "string" && nodePaint.muted.trim().length > 0 ? nodePaint.muted : isDark ? "rgba(226, 232, 240, 0.82)" : "rgba(15, 23, 42, 0.68)";
              const iconSize = 14;
              const iconGap = 6;
              const scale = iconSize / 24;
              const inset = 6;
              const leftX = nodeLayout.x + inset + shapeSafeInsets.insetX;
              const topY = nodeLayout.y + inset + shapeSafeInsets.insetY;
              const rightStart = nodeLayout.x + nodeLayout.width - inset - iconSize - shapeSafeInsets.insetX;
              const links = getNodeLinks(node);
              const exclusiveEmbedBlock = resolveExclusiveMainEmbedBlock(node);
              const isSiyuanDocEmbedNode = exclusiveEmbedBlock?.embed.type === "kmind:siyuan-doc";
              const hasOutgoingInternal = links.some((link) => link.kind === "internal");
              const hasBacklinks = (backlinksIndex[nodeId] ?? []).length > 0;
              const externalLinks = isSiyuanDocEmbedNode ? [] : links.filter((link) => link.kind === "external");
              const chromeExternalLinks = resolvedExternalLinkPlacement === "title-leading" && nodeBodyLayout === "card-v1" ? externalLinks.slice(1) : externalLinks;
              const backAnchorNodeId = submap?.backAnchorNodeId ?? doc3.roots[0];
              const showBack = Boolean(submap?.canGoBack && backAnchorNodeId === nodeId);
              const showLocked = Boolean(node.attrs?.locked);
              const showLinksPanel = !isSiyuanDocEmbedNode && (hasOutgoingInternal || hasBacklinks);
              const showSubmap = Boolean(node.subMapId && submap);
              const internalCount = links.filter((link) => link.kind === "internal").length;
              const backlinksCount = (backlinksIndex[nodeId] ?? []).length;
              const titleById = {
                back: "Back",
                submap: node.subMapId ? `Enter sub map: ${node.subMapId}` : "Enter sub map",
                links: `Links / Backlinks (${internalCount}/${backlinksCount})`
              };
              const iconSymbolIdByName = {
                back: `${builtinIconSymbolPrefix}-ui-back`,
                backlinks: `${builtinIconSymbolPrefix}-ui-backlinks`,
                enterSubmap: `${builtinIconSymbolPrefix}-ui-enter-submap`
              };
              const renderButton = (args) => {
                return /* @__PURE__ */ (0, import_jsx_runtime9.jsxs)(
                  "g",
                  {
                    "data-km-action": args.action,
                    onPointerEnter: (event) => {
                      args.onHoverChange?.(true);
                      args.onPointerEnter?.(event);
                    },
                    onPointerMove: (event) => args.onPointerMove?.(event),
                    onPointerLeave: (event) => {
                      args.onHoverChange?.(false);
                      args.onPointerLeave?.(event);
                    },
                    onPointerDown: (event) => {
                      event.preventDefault();
                      event.stopPropagation();
                      args.onActivate(event);
                    },
                    style: { cursor: "pointer", color: chromeStroke },
                    transform: `translate(${args.x} ${args.y}) scale(${scale})`,
                    children: [
                      /* @__PURE__ */ (0, import_jsx_runtime9.jsx)("title", { children: args.title ?? titleById[args.id] ?? args.id }),
                      /* @__PURE__ */ (0, import_jsx_runtime9.jsx)("rect", { fill: "transparent", height: 24, width: 24, x: 0, y: 0 }),
                      args.children
                    ]
                  },
                  `chrome:${nodeId}:${args.id}`
                );
              };
              const renderIcon = (args) => renderButton(args);
              const rightIcons = [];
              const displaySlots = [];
              const requestLinksPopover = (args) => {
                const rect = args.event.currentTarget.getBoundingClientRect();
                const anchor = rect ? { left: rect.left, top: rect.top, width: rect.width, height: rect.height } : null;
                if (onRequestSelectionToolbarPopover) {
                  onRequestSelectionToolbarPopover({
                    popoverId: "builtin.links",
                    nodeId: args.nodeId,
                    anchorClientRect: anchor,
                    mode: args.mode
                  });
                  return;
                }
                onOpenLinksPanel?.(args.nodeId, args.mode);
              };
              const visibleExternal = chromeExternalLinks.slice(0, 3);
              for (const link of visibleExternal) {
                const resolvedIconId = resolveExternalIconId(link, external);
                const label = typeof link.label === "string" && link.label.trim().length > 0 ? link.label.trim() : link.url;
                const inner2 = getBuiltinIconInner(resolvedIconId);
                const hoverPreviewEnabled = Boolean(external?.previewUrl) && Boolean(external?.resolveUrlBehavior?.(link.url)?.canPreview);
                displaySlots.push({
                  id: `external:${link.id}`,
                  title: label,
                  onActivate: () => {
                    if (hoverPreviewEnabled) cancelHoverPreview();
                    if (!external) return;
                    void external.openUrl(link.url);
                  },
                  onPointerEnter: hoverPreviewEnabled ? (event) => scheduleHoverPreview({ url: link.url, x: event.clientX, y: event.clientY }) : void 0,
                  onPointerMove: hoverPreviewEnabled ? (event) => updateHoverPreviewPosition({ url: link.url.trim(), x: event.clientX, y: event.clientY }) : void 0,
                  onPointerLeave: hoverPreviewEnabled ? () => cancelHoverPreview() : void 0,
                  children: inner2 ? /* @__PURE__ */ (0, import_jsx_runtime9.jsx)("g", { dangerouslySetInnerHTML: { __html: inner2 } }) : /* @__PURE__ */ (0, import_jsx_runtime9.jsx)("path", { d: "M6 12h12", fill: "none", stroke: chromeStroke, strokeLinecap: "round", strokeWidth: 2 })
                });
              }
              const hiddenExternalCount = Math.max(0, chromeExternalLinks.length - visibleExternal.length);
              if (hiddenExternalCount > 0) {
                displaySlots.push({
                  id: "external:more",
                  title: `+${hiddenExternalCount} more`,
                  action: "links.open",
                  onActivate: (event) => requestLinksPopover({ nodeId, event, mode: "edit" }),
                  children: /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(
                    "text",
                    {
                      fill: "currentColor",
                      fontFamily: 'ui-sans-serif, system-ui, -apple-system, Segoe UI, Roboto, Helvetica, Arial, "Apple Color Emoji", "Segoe UI Emoji"',
                      fontSize: 11,
                      fontWeight: 700,
                      textAnchor: "middle",
                      x: 12,
                      y: 16,
                      children: `+${hiddenExternalCount}`
                    }
                  )
                });
              }
              if (showLinksPanel) {
                displaySlots.push({
                  id: "links",
                  action: "links.open",
                  onActivate: (event) => requestLinksPopover({ nodeId, event, mode: "edit" }),
                  children: /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(
                    "use",
                    {
                      height: 24,
                      href: `#${iconSymbolIdByName.backlinks}`,
                      width: 24,
                      x: 0,
                      xlinkHref: `#${iconSymbolIdByName.backlinks}`,
                      y: 0
                    }
                  )
                });
              }
              if (showSubmap) {
                displaySlots.push({
                  id: "submap",
                  onActivate: () => submap?.enterSubmap(nodeId),
                  children: /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(
                    "use",
                    {
                      height: 24,
                      href: `#${iconSymbolIdByName.enterSubmap}`,
                      width: 24,
                      x: 0,
                      xlinkHref: `#${iconSymbolIdByName.enterSubmap}`,
                      y: 0
                    }
                  )
                });
              }
              const rightSlots = displaySlots.slice().reverse();
              for (const [index, icon] of rightSlots.entries()) {
                const x5 = rightStart - index * (iconSize + iconGap);
                rightIcons.push(
                  renderIcon({
                    id: icon.id,
                    title: icon.title,
                    action: icon.action,
                    x: x5,
                    y: topY,
                    onActivate: icon.onActivate,
                    onPointerEnter: icon.onPointerEnter,
                    onPointerMove: icon.onPointerMove,
                    onPointerLeave: icon.onPointerLeave,
                    children: icon.children
                  })
                );
              }
              const leftIcons = [];
              if (showBack) {
                leftIcons.push(
                  renderIcon({
                    id: "back",
                    x: leftX,
                    y: topY,
                    onActivate: () => submap?.backToParentMap(),
                    children: /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(
                      "use",
                      {
                        height: 24,
                        href: `#${iconSymbolIdByName.back}`,
                        width: 24,
                        x: 0,
                        xlinkHref: `#${iconSymbolIdByName.back}`,
                        y: 0
                      }
                    )
                  })
                );
              }
              if (showLocked) {
                const x5 = leftX + (showBack ? iconSize + iconGap : 0);
                leftIcons.push(
                  /* @__PURE__ */ (0, import_jsx_runtime9.jsxs)(
                    "g",
                    {
                      "data-export-exclude": "true",
                      style: { pointerEvents: "none" },
                      transform: `translate(${x5} ${topY}) scale(${scale})`,
                      children: [
                        /* @__PURE__ */ (0, import_jsx_runtime9.jsx)("title", { children: "Locked" }),
                        /* @__PURE__ */ (0, import_jsx_runtime9.jsx)("rect", { x: 5, y: 11, width: 14, height: 10, rx: 2, fill: "none", stroke: chromeStroke, strokeWidth: 2 }),
                        /* @__PURE__ */ (0, import_jsx_runtime9.jsx)("path", { d: "M8 11V8a4 4 0 0 1 8 0v3", fill: "none", stroke: chromeStroke, strokeLinecap: "round", strokeLinejoin: "round", strokeWidth: 2 })
                      ]
                    },
                    `chrome:${nodeId}:locked`
                  )
                );
              }
              if (leftIcons.length === 0 && rightIcons.length === 0) return null;
              return /* @__PURE__ */ (0, import_jsx_runtime9.jsxs)(import_jsx_runtime9.Fragment, { children: [
                leftIcons,
                rightIcons
              ] });
            })()
          ]
        },
        nodeId
      );
    }) })
  ] });
}
function NodeBodyHtml(props) {
  const {
    doc: doc3,
    embedRegistry,
    html,
    isBlurHidden,
    optimizeEmbedMounting,
    perfEnabled,
    perfStatsRef,
    onExternalLinkActivate,
    onExternalLinkPointerEnter,
    onExternalLinkPointerMove,
    onExternalLinkPointerLeave
  } = props;
  const rootRef = (0, import_react4.useRef)(null);
  const innerHtml = (0, import_react4.useMemo)(() => ({ __html: html }), [html]);
  const docRef = (0, import_react4.useRef)(doc3);
  (0, import_react4.useEffect)(() => {
    docRef.current = doc3;
  }, [doc3]);
  const embedMountDeps = optimizeEmbedMounting ? [embedRegistry, html, doc3.assets] : [doc3, embedRegistry, html];
  (0, import_react4.useEffect)(() => {
    const root = rootRef.current;
    if (!root) return;
    if (perfEnabled && perfStatsRef) perfStatsRef.current.embeds.mounts += 1;
    const resolvedDoc = optimizeEmbedMounting ? docRef.current : doc3;
    return mountEmbeds(root, { doc: resolvedDoc, embedRegistry });
  }, [...embedMountDeps, optimizeEmbedMounting, perfEnabled, perfStatsRef]);
  (0, import_react4.useEffect)(() => {
    const root = rootRef.current;
    if (!root) return;
    let hoveredEl = null;
    const findExternalLink = (target2) => {
      return target2 instanceof Element ? target2.closest('[data-km-action="external.open"][data-km-external-url]') : null;
    };
    const getUrl = (element) => String(element?.getAttribute("data-km-external-url") ?? "").trim();
    const handlePointerOver = (event) => {
      const linkEl = findExternalLink(event.target);
      if (!linkEl || hoveredEl === linkEl) return;
      hoveredEl = linkEl;
      const url = getUrl(linkEl);
      if (url) onExternalLinkPointerEnter?.(url, event);
    };
    const handlePointerMove = (event) => {
      const linkEl = findExternalLink(event.target);
      const url = getUrl(linkEl);
      if (url) onExternalLinkPointerMove?.(url, event);
    };
    const handlePointerOut = (event) => {
      if (!hoveredEl) return;
      const nextTarget = event.relatedTarget;
      if (nextTarget instanceof Node && hoveredEl.contains(nextTarget)) return;
      hoveredEl = null;
      onExternalLinkPointerLeave?.(event);
    };
    const handlePointerDown = (event) => {
      const linkEl = findExternalLink(event.target);
      const url = getUrl(linkEl);
      if (!url) return;
      event.preventDefault();
      event.stopPropagation();
      onExternalLinkActivate?.(url, event);
    };
    root.addEventListener("pointerover", handlePointerOver);
    root.addEventListener("pointermove", handlePointerMove);
    root.addEventListener("pointerout", handlePointerOut);
    root.addEventListener("pointerdown", handlePointerDown);
    return () => {
      root.removeEventListener("pointerover", handlePointerOver);
      root.removeEventListener("pointermove", handlePointerMove);
      root.removeEventListener("pointerout", handlePointerOut);
      root.removeEventListener("pointerdown", handlePointerDown);
    };
  }, [onExternalLinkActivate, onExternalLinkPointerEnter, onExternalLinkPointerLeave, onExternalLinkPointerMove]);
  return /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(
    "div",
    {
      ref: rootRef,
      className: isBlurHidden ? "km-node-blur-hidden" : void 0,
      dangerouslySetInnerHTML: innerHtml
    }
  );
}

// ../react/src/mindmap-editor/layers/relations.tsx
init_src();

// ../react/src/mindmap-editor/utils/relation-geometry.ts
function normalizePortRatio(value) {
  const next = Number(value);
  if (!Number.isFinite(next)) return 0.5;
  return Math.max(0, Math.min(1, next));
}
function resolvePortPoint3(layout, port, portRatio) {
  const ratio = normalizePortRatio(portRatio);
  switch (port) {
    case "top":
      return { x: layout.x + layout.width * ratio, y: layout.y };
    case "bottom":
      return { x: layout.x + layout.width * ratio, y: layout.y + layout.height };
    case "left":
      return { x: layout.x, y: layout.y + layout.height * ratio };
    case "right":
    default:
      return { x: layout.x + layout.width, y: layout.y + layout.height * ratio };
  }
}
function resolvePortAndRatioFromRay(layout, point) {
  const { x: x5, y, width, height } = layout;
  if (!Number.isFinite(x5) || !Number.isFinite(y) || !Number.isFinite(width) || !Number.isFinite(height)) return null;
  if (width <= 0 || height <= 0) return null;
  const cx = x5 + width / 2;
  const cy = y + height / 2;
  const dx = point.x - cx;
  const dy = point.y - cy;
  if (!Number.isFinite(dx) || !Number.isFinite(dy)) return null;
  if (dx === 0 && dy === 0) {
    return { port: "right", portRatio: 0.5 };
  }
  const halfW = width / 2;
  const halfH = height / 2;
  const absDx = Math.abs(dx);
  const absDy = Math.abs(dy);
  const nx = absDx / halfW;
  const ny = absDy / halfH;
  if (nx >= ny) {
    if (absDx === 0) return { port: dy >= 0 ? "bottom" : "top", portRatio: 0.5 };
    const port2 = dx >= 0 ? "right" : "left";
    const t2 = halfW / absDx;
    const iy = cy + dy * t2;
    const ratio2 = (iy - y) / height;
    return { port: port2, portRatio: Math.max(0, Math.min(1, ratio2)) };
  }
  if (absDy === 0) return { port: dx >= 0 ? "right" : "left", portRatio: 0.5 };
  const port = dy >= 0 ? "bottom" : "top";
  const t = halfH / absDy;
  const ix = cx + dx * t;
  const ratio = (ix - x5) / width;
  return { port, portRatio: Math.max(0, Math.min(1, ratio)) };
}
function computeDefaultCubicControlDeltas(start, end) {
  const dx = end.x - start.x;
  const curve = Math.max(40, Math.min(220, Math.abs(dx) / 2));
  const s = Math.sign(dx || 1);
  return { control1: { x: s * curve, y: 0 }, control2: { x: -s * curve, y: 0 } };
}
function cubicAtHalf3(p0, p1, p2, p3) {
  return {
    x: (p0.x + 3 * p1.x + 3 * p2.x + p3.x) / 8,
    y: (p0.y + 3 * p1.y + 3 * p2.y + p3.y) / 8
  };
}

// ../react/src/mindmap-editor/layers/relations.tsx
var import_jsx_runtime10 = __toESM(require_jsx_runtime(), 1);
function Relations(props) {
  const { doc: doc3, excludedNodeIds, layout, nodeThemeById, selectedRelationId, onRelationSelect, visibleNodeIds, visibleSummaryIds, perfEnabled, perfStatsRef } = props;
  return /* @__PURE__ */ (0, import_jsx_runtime10.jsx)("g", { children: doc3.relations.map((rel2) => {
    if (isEndpointExcluded(rel2.from, excludedNodeIds) || isEndpointExcluded(rel2.to, excludedNodeIds)) return null;
    if ((visibleNodeIds || visibleSummaryIds) && !isEndpointVisible(rel2.from, visibleNodeIds, visibleSummaryIds) && !isEndpointVisible(rel2.to, visibleNodeIds, visibleSummaryIds)) return null;
    const from2 = resolveRelationEndpointLayout(layout, rel2.from);
    const to = resolveRelationEndpointLayout(layout, rel2.to);
    if (!from2 || !to) return null;
    if (perfEnabled && perfStatsRef) perfStatsRef.current.culling.renderedRelations += 1;
    const endpointsDraft = rel2.id === props.endpointsDraft?.relationId ? props.endpointsDraft : null;
    const resolvedFromPort = endpointsDraft?.fromPort ?? (relationEndpointPort(rel2.from) ?? "right");
    const resolvedFromPortRatio = endpointsDraft?.fromPortRatio ?? relationEndpointPortRatio(rel2.from);
    const resolvedToPort = endpointsDraft?.toPort ?? (relationEndpointPort(rel2.to) ?? "left");
    const resolvedToPortRatio = endpointsDraft?.toPortRatio ?? relationEndpointPortRatio(rel2.to);
    const start = resolvePortPoint3(from2, resolvedFromPort, resolvedFromPortRatio);
    const end = resolvePortPoint3(to, resolvedToPort, resolvedToPortRatio);
    const { control1: defaultControl1, control2: defaultControl2 } = computeDefaultCubicControlDeltas(start, end);
    const resolvedCurve = rel2.id === props.curveDraft?.relationId ? props.curveDraft.curve : rel2.curve;
    const curveV1 = resolvedCurve?.schemaVersion === 1 && resolvedCurve.kind === "cubic" ? resolvedCurve : null;
    const control1 = curveV1?.control1 ?? defaultControl1;
    const control2 = curveV1?.control2 ?? defaultControl2;
    const c1 = { x: start.x + control1.x, y: start.y + control1.y };
    const c2 = { x: end.x + control2.x, y: end.y + control2.y };
    const path2 = `M ${start.x} ${start.y} C ${c1.x} ${c1.y}, ${c2.x} ${c2.y}, ${end.x} ${end.y}`;
    const labelAnchor = cubicAtHalf3(start, c1, c2, end);
    const labelText = rel2.label?.schemaVersion === 1 && rel2.label.kind === "plain-text" ? rel2.label.text : "";
    const label = (() => {
      const text5 = labelText.trim();
      if (text5.length === 0) return void 0;
      return { text: text5, x: labelAnchor.x, y: labelAnchor.y };
    })();
    const isSelected = selectedRelationId === rel2.id;
    const baseTheme = resolveEndpointTheme(rel2.from, nodeThemeById, props.summaryThemeById) ?? resolveEndpointTheme(rel2.to, nodeThemeById, props.summaryThemeById);
    const paint = baseTheme?.paint;
    const override = doc3.theme?.overrides?.relations?.[rel2.id];
    const sharedRootId = relationEndpointsShareRoot(doc3, rel2);
    const rootStyle = sharedRootId ? doc3.theme?.rootRelationStyles?.[sharedRootId] : void 0;
    const projectStyle = doc3.theme?.relationStyle;
    const baseStroke = isSelected ? paint?.relationStrokeSelected ?? "var(--km-relation-stroke-selected)" : paint?.relationStroke ?? "var(--km-relation-stroke)";
    const baseStrokeWidth = baseTheme?.relations?.strokeWidth ?? 2;
    const baseStrokeDasharray = baseTheme?.relations?.dasharray;
    const cap = baseTheme?.relations?.cap;
    const join2 = baseTheme?.relations?.join;
    const stroke = rel2.style?.strokeColor ?? override?.strokeColor ?? rootStyle?.strokeColor ?? projectStyle?.strokeColor ?? baseStroke;
    const strokeWidth = rel2.style?.strokeWidth ?? override?.strokeWidth ?? rootStyle?.strokeWidth ?? projectStyle?.strokeWidth ?? baseStrokeWidth;
    const strokeDasharray = rel2.style?.strokeDasharray ?? override?.dasharray ?? rootStyle?.dasharray ?? projectStyle?.dasharray ?? baseStrokeDasharray;
    const direction = resolveRelationDirection(rel2, override, rootStyle, projectStyle);
    const hitStrokeWidth = Math.max(12, strokeWidth + 10);
    const markerStartId = `${props.markerIdPrefix}-${sanitizeRelationMarkerId(rel2.id)}-start`;
    const markerEndId = `${props.markerIdPrefix}-${sanitizeRelationMarkerId(rel2.id)}-end`;
    return /* @__PURE__ */ (0, import_jsx_runtime10.jsxs)("g", { "data-relation-id": rel2.id, children: [
      /* @__PURE__ */ (0, import_jsx_runtime10.jsxs)("defs", { children: [
        direction === "backward" || direction === "both" ? relationArrowMarker(markerStartId, stroke, strokeWidth, "start") : null,
        direction === "forward" || direction === "both" ? relationArrowMarker(markerEndId, stroke, strokeWidth, "end") : null
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(
        "path",
        {
          d: path2,
          "data-export-exclude": "true",
          fill: "none",
          onPointerDown: () => onRelationSelect(rel2.id),
          onDoubleClick: (event) => {
            event.preventDefault();
            event.stopPropagation();
            props.onRelationLabelDoubleClick({ relationId: rel2.id, anchor: labelAnchor });
          },
          pointerEvents: "stroke",
          stroke: "transparent",
          strokeWidth: hitStrokeWidth,
          style: { cursor: "pointer" }
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(
        "path",
        {
          d: path2,
          fill: "none",
          pointerEvents: "none",
          stroke,
          strokeDasharray,
          strokeLinecap: cap,
          strokeLinejoin: join2,
          strokeWidth,
          markerStart: direction === "backward" || direction === "both" ? `url(#${markerStartId})` : void 0,
          markerEnd: direction === "forward" || direction === "both" ? `url(#${markerEndId})` : void 0
        }
      ),
      label && label.text ? /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(
        "text",
        {
          fill: stroke,
          fontFamily: baseTheme?.layout.fontFamily ?? nodeFontFamily,
          fontSize: 12,
          onPointerDown: () => onRelationSelect(rel2.id),
          onDoubleClick: (event) => {
            event.preventDefault();
            event.stopPropagation();
            props.onRelationLabelDoubleClick({ relationId: rel2.id, anchor: labelAnchor });
          },
          textAnchor: "middle",
          dominantBaseline: "middle",
          x: label.x,
          y: label.y,
          children: label.text
        }
      ) : null
    ] }, rel2.id);
  }) });
}
function RelationControls(props) {
  if (props.hidden) return null;
  if (!props.selectedRelationId) return null;
  const rel2 = props.doc.relations.find((item) => item.id === props.selectedRelationId);
  if (!rel2) return null;
  if (isEndpointExcluded(rel2.from, props.excludedNodeIds) || isEndpointExcluded(rel2.to, props.excludedNodeIds)) return null;
  const from2 = resolveRelationEndpointLayout(props.layout, rel2.from);
  const to = resolveRelationEndpointLayout(props.layout, rel2.to);
  if (!from2 || !to) return null;
  const endpointsDraft = rel2.id === props.endpointsDraft?.relationId ? props.endpointsDraft : null;
  const resolvedFromPort = endpointsDraft?.fromPort ?? (relationEndpointPort(rel2.from) ?? "right");
  const resolvedFromPortRatio = endpointsDraft?.fromPortRatio ?? relationEndpointPortRatio(rel2.from);
  const resolvedToPort = endpointsDraft?.toPort ?? (relationEndpointPort(rel2.to) ?? "left");
  const resolvedToPortRatio = endpointsDraft?.toPortRatio ?? relationEndpointPortRatio(rel2.to);
  const start = resolvePortPoint3(from2, resolvedFromPort, resolvedFromPortRatio);
  const end = resolvePortPoint3(to, resolvedToPort, resolvedToPortRatio);
  const resolvedCurve = rel2.id === props.curveDraft?.relationId ? props.curveDraft.curve : rel2.curve;
  const curveV1 = resolvedCurve?.schemaVersion === 1 && resolvedCurve.kind === "cubic" ? resolvedCurve : null;
  const { control1: defaultControl1, control2: defaultControl2 } = computeDefaultCubicControlDeltas(start, end);
  const control1 = curveV1?.control1 ?? defaultControl1;
  const control2 = curveV1?.control2 ?? defaultControl2;
  const c1 = { x: start.x + control1.x, y: start.y + control1.y };
  const c2 = { x: end.x + control2.x, y: end.y + control2.y };
  const baseTheme = resolveEndpointTheme(rel2.from, props.nodeThemeById, props.summaryThemeById) ?? resolveEndpointTheme(rel2.to, props.nodeThemeById, props.summaryThemeById);
  const paint = baseTheme?.paint;
  const override = props.doc.theme?.overrides?.relations?.[rel2.id];
  const baseStroke = paint?.relationStrokeSelected ?? "var(--km-relation-stroke-selected)";
  const stroke = rel2.style?.strokeColor ?? override?.strokeColor ?? baseStroke;
  return /* @__PURE__ */ (0, import_jsx_runtime10.jsxs)("g", { "data-export-exclude": "true", "data-relation-id": rel2.id, children: [
    /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(
      "line",
      {
        x1: start.x,
        y1: start.y,
        x2: c1.x,
        y2: c1.y,
        pointerEvents: "none",
        stroke,
        strokeDasharray: "4 4",
        strokeWidth: 1.5,
        opacity: 0.75,
        vectorEffect: "non-scaling-stroke"
      }
    ),
    /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(
      "line",
      {
        x1: end.x,
        y1: end.y,
        x2: c2.x,
        y2: c2.y,
        pointerEvents: "none",
        stroke,
        strokeDasharray: "4 4",
        strokeWidth: 1.5,
        opacity: 0.75,
        vectorEffect: "non-scaling-stroke"
      }
    ),
    /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(
      "circle",
      {
        cx: c1.x,
        cy: c1.y,
        fill: "rgba(255,255,255,0.95)",
        onPointerDown: (event) => {
          props.onRelationControlHandlePointerDown({ relationId: rel2.id, handle: "control1", control1, control2 }, event);
        },
        r: 6,
        stroke,
        strokeWidth: 2,
        style: { cursor: "grab" },
        vectorEffect: "non-scaling-stroke"
      }
    ),
    /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(
      "circle",
      {
        cx: c2.x,
        cy: c2.y,
        fill: "rgba(255,255,255,0.95)",
        onPointerDown: (event) => {
          props.onRelationControlHandlePointerDown({ relationId: rel2.id, handle: "control2", control1, control2 }, event);
        },
        r: 6,
        stroke,
        strokeWidth: 2,
        style: { cursor: "grab" },
        vectorEffect: "non-scaling-stroke"
      }
    )
  ] });
}
function resolveRelationEndpointLayout(layout, endpoint) {
  return endpoint.kind === "summary" ? layout.summaries[endpoint.summaryId] : layout.nodes[endpoint.nodeId];
}
function resolveEndpointTheme(endpoint, nodeThemeById, summaryThemeById) {
  return endpoint.kind === "summary" ? summaryThemeById[endpoint.summaryId] : nodeThemeById[endpoint.nodeId];
}
function isEndpointExcluded(endpoint, excludedNodeIds) {
  if (!excludedNodeIds) return false;
  return endpoint.kind !== "summary" && excludedNodeIds.has(endpoint.nodeId);
}
function isEndpointVisible(endpoint, visibleNodeIds, visibleSummaryIds) {
  if (endpoint.kind === "summary") return visibleSummaryIds ? visibleSummaryIds.has(endpoint.summaryId) : true;
  return visibleNodeIds ? visibleNodeIds.has(endpoint.nodeId) : true;
}
function resolveRelationDirection(relation, override, rootStyle, projectStyle) {
  return relation.direction ?? override?.direction ?? rootStyle?.direction ?? projectStyle?.direction ?? "none";
}
function sanitizeRelationMarkerId(value) {
  return value.replace(/[^a-zA-Z0-9_-]/g, "-");
}
function relationArrowMarker(id, stroke, strokeWidth, orient) {
  const size = Math.max(5.5, Math.min(9, strokeWidth * 2.8));
  const refX = size;
  return /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(
    "marker",
    {
      id,
      markerHeight: size,
      markerUnits: "userSpaceOnUse",
      markerWidth: size,
      orient: orient === "start" ? "auto-start-reverse" : "auto",
      refX,
      refY: size / 2,
      viewBox: `0 0 ${size} ${size}`,
      children: /* @__PURE__ */ (0, import_jsx_runtime10.jsx)("path", { d: `M 0 0 L ${size} ${size / 2} L 0 ${size} z`, fill: stroke, stroke: "none" })
    }
  );
}

// ../react/src/mindmap-editor/layers/summaries.tsx
var import_react5 = __toESM(require_react(), 1);
var import_jsx_runtime11 = __toESM(require_jsx_runtime(), 1);
function resolveSummaryContextMenuPoint(event) {
  const svg = event.currentTarget.ownerSVGElement;
  const rect = svg?.getBoundingClientRect() ?? null;
  if (!rect) return { x: event.clientX, y: event.clientY };
  return { x: event.clientX - rect.left, y: event.clientY - rect.top };
}
function SummaryBrackets(props) {
  return /* @__PURE__ */ (0, import_jsx_runtime11.jsx)("g", { children: Object.values(props.layout.summaries).map((summary) => {
    if (props.visibleSummaryIds && !props.visibleSummaryIds.has(summary.id)) return null;
    if (props.hiddenSummaryIds?.has(summary.id)) return null;
    const isDropTarget = props.highlightId === summary.id;
    const theme = props.summaryThemeById[summary.id];
    const overrideStroke = props.doc.theme?.overrides?.summaries?.[summary.id]?.strokeColor;
    const strokeColor = overrideStroke ?? theme?.paint.summaryStroke ?? "var(--km-summary-stroke)";
    return /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(
      "path",
      {
        d: summary.bracketPath,
        "data-summary-id": summary.id,
        fill: "none",
        stroke: isDropTarget ? "#22c55e" : strokeColor,
        strokeWidth: 2
      },
      `${summary.id}-bracket`
    );
  }) });
}
function Summaries(props) {
  const {
    doc: doc3,
    blurViewState,
    hiddenSummaryIds,
    visibleSummaryIds,
    highlightId,
    editingSummaryId,
    forceCursor,
    layout,
    summaryThemeById,
    selectedSummaryId,
    onSummaryPointerDown,
    onRequestOpenSummaryContextMenu,
    perfEnabled,
    perfStatsRef
  } = props;
  const summaryById = (0, import_react5.useMemo)(() => new Map(doc3.summaries.map((summary) => [summary.id, summary])), [doc3.summaries]);
  return /* @__PURE__ */ (0, import_jsx_runtime11.jsx)("g", { children: Object.values(layout.summaries).map((summaryLayout) => {
    if (visibleSummaryIds && !visibleSummaryIds.has(summaryLayout.id)) return null;
    if (hiddenSummaryIds?.has(summaryLayout.id)) return null;
    const summary = summaryById.get(summaryLayout.id);
    if (!summary) return null;
    if (perfEnabled && perfStatsRef) perfStatsRef.current.culling.renderedSummaries += 1;
    const theme = summaryThemeById[summaryLayout.id];
    const layoutTokens = theme?.layout;
    const paint = theme?.paint;
    const override = doc3.theme?.overrides?.summaries?.[summaryLayout.id];
    const isSelected = selectedSummaryId === summaryLayout.id;
    const baseStroke = isSelected ? paint?.nodeStrokeSelected ?? "var(--km-node-stroke-selected)" : paint?.nodeStroke ?? "var(--km-node-stroke)";
    const stroke = override?.strokeColor ?? baseStroke;
    const resolvedStroke = highlightId === summaryLayout.id ? "#22c55e" : stroke;
    const baseFill = isSelected ? paint?.nodeFillSelected ?? "var(--km-node-fill-selected)" : paint?.nodeFill ?? "var(--km-node-fill)";
    const fill = override?.fill ?? baseFill;
    const textColor = override?.textColor ?? paint?.text ?? "var(--km-text)";
    const isDark = theme?.variantId === "dark";
    const html = buildSummaryBodyHtml(doc3, summaryLayout.id, blurViewState);
    return /* @__PURE__ */ (0, import_jsx_runtime11.jsxs)(
      "g",
      {
        "data-summary-id": summaryLayout.id,
        onContextMenu: (event) => {
          if (!onRequestOpenSummaryContextMenu) return;
          event.preventDefault();
          event.stopPropagation();
          const point = resolveSummaryContextMenuPoint(event);
          onRequestOpenSummaryContextMenu({
            ...point,
            summaryId: summaryLayout.id
          });
        },
        onPointerDown: (event) => onSummaryPointerDown(summaryLayout.id, event),
        style: { cursor: forceCursor ?? "pointer" },
        children: [
          renderNodeShape({
            x: summaryLayout.x,
            y: summaryLayout.y,
            width: summaryLayout.width,
            height: summaryLayout.height,
            shape: theme?.nodeShape,
            fill,
            stroke: resolvedStroke,
            strokeWidth: resolveNodeStrokeWidth(theme?.nodeShape)
          }),
          editingSummaryId === summaryLayout.id ? null : /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(
            "foreignObject",
            {
              height: summaryLayout.height,
              width: summaryLayout.width,
              x: summaryLayout.x,
              y: summaryLayout.y,
              children: /* @__PURE__ */ (0, import_jsx_runtime11.jsxs)(
                "div",
                {
                  ...{ xmlns: "http://www.w3.org/1999/xhtml" },
                  style: {
                    boxSizing: "border-box",
                    height: "100%",
                    width: "100%",
                    padding: `${layoutTokens?.paddingY ?? nodePaddingY}px ${layoutTokens?.paddingX ?? nodePaddingX}px`,
                    fontSize: layoutTokens?.fontSize ?? nodeFontSize,
                    fontFamily: layoutTokens?.fontFamily ?? nodeFontFamily,
                    fontWeight: layoutTokens?.fontWeight ?? 400,
                    lineHeight: String(layoutTokens?.lineHeight ?? nodeLineHeight),
                    textAlign: layoutTokens?.textAlign ?? "left",
                    color: textColor,
                    "--km-text": textColor,
                    "--km-muted": paint?.muted ?? "var(--km-muted)",
                    "--km-border": paint?.border ?? "var(--km-border)",
                    "--km-code-bg": isDark ? "rgba(0, 0, 0, 0.24)" : "rgba(15, 23, 42, 0.06)",
                    "--km-code-border": isDark ? "rgba(226, 232, 240, 0.14)" : "rgba(148, 163, 184, 0.35)",
                    "--km-code-token-keyword": isDark ? "rgba(196, 181, 253, 0.95)" : "rgba(124, 58, 237, 0.95)",
                    "--km-code-token-string": isDark ? "rgba(125, 211, 252, 0.95)" : "rgba(2, 132, 199, 0.95)",
                    "--km-code-token-number": isDark ? "rgba(253, 186, 116, 0.95)" : "rgba(234, 88, 12, 0.95)",
                    "--km-code-token-comment": isDark ? "rgba(148, 163, 184, 0.78)" : "rgba(100, 116, 139, 0.85)",
                    "--km-code-token-property": isDark ? "rgba(147, 197, 253, 0.95)" : "rgba(29, 78, 216, 0.95)",
                    "--km-code-token-punct": isDark ? "rgba(226, 232, 240, 0.92)" : "rgba(51, 65, 85, 0.88)",
                    overflow: "hidden",
                    pointerEvents: "auto"
                  },
                  children: [
                    /* @__PURE__ */ (0, import_jsx_runtime11.jsx)("style", { children: nodeRichTextCssText }),
                    /* @__PURE__ */ (0, import_jsx_runtime11.jsx)("div", { dangerouslySetInnerHTML: { __html: html } })
                  ]
                }
              )
            }
          )
        ]
      },
      summaryLayout.id
    );
  }) });
}

// ../react/src/mindmap-editor/utils/container-layout.ts
function resolveContainerLayout(doc3, containerId) {
  const summaryById = new Map(doc3.summaries.map((summary) => [summary.id, summary]));
  const memo2 = /* @__PURE__ */ new Map();
  const resolve = (id, visited) => {
    const cached = memo2.get(id);
    if (cached) return cached;
    if (visited.has(id)) return "logical-right";
    visited.add(id);
    const node = doc3.nodes[id];
    if (node) {
      let inherited = "logical-right";
      if (node.parentId) inherited = resolve(node.parentId, visited);
      else if (node.parentSummaryId) inherited = resolve(node.parentSummaryId, visited);
      const resolved = node.layout ?? inherited;
      memo2.set(id, resolved);
      return resolved;
    }
    const summary = summaryById.get(id);
    if (summary) {
      let inherited = "logical-right";
      if (doc3.nodes[summary.parentId]) inherited = resolve(summary.parentId, visited);
      else inherited = resolve(summary.parentId, visited);
      const resolved = summary.layout ?? inherited;
      memo2.set(id, resolved);
      return resolved;
    }
    return "logical-right";
  };
  return resolve(containerId, /* @__PURE__ */ new Set());
}

// ../react/src/mindmap-editor/overlays/drag-overlay.tsx
var import_jsx_runtime12 = __toESM(require_jsx_runtime(), 1);
function DragOverlay(props) {
  const { doc: doc3, layout, drag } = props;
  const t = useT();
  if (!drag) return null;
  const baseline = layout.nodes[drag.nodeId];
  if (!baseline) return null;
  const ghostRect = {
    x: drag.ghost.x,
    y: drag.ghost.y,
    width: baseline.width,
    height: baseline.height
  };
  const dashed = !drag.detached ? resolveDashedConnector(doc3, layout, drag, ghostRect) : null;
  const rubberBand = !drag.detached && drag.intent.kind === "none" && drag.originParent ? resolveRubberBand(doc3, layout, drag.originParent, ghostRect) : null;
  const showDetachedHint = (props.showDetachedHint ?? true) && drag.detached && drag.intent.kind === "none";
  const showGroupHint = drag.groupBounds && drag.groupNodeIds.length > 1;
  return /* @__PURE__ */ (0, import_jsx_runtime12.jsxs)("g", { "data-export-exclude": "true", style: { pointerEvents: "none" }, children: [
    showGroupHint ? /* @__PURE__ */ (0, import_jsx_runtime12.jsx)(GroupDragHint, { rect: drag.groupBounds, text: t("editor.drag.groupHint.nodes", { count: drag.groupNodeIds.length }) }) : null,
    dashed ? /* @__PURE__ */ (0, import_jsx_runtime12.jsx)(
      "path",
      {
        d: dashed.path,
        fill: "none",
        stroke: "rgba(34, 197, 94, 0.9)",
        strokeDasharray: "6 6",
        strokeLinecap: "round",
        strokeWidth: 2.5
      }
    ) : null,
    rubberBand ? /* @__PURE__ */ (0, import_jsx_runtime12.jsx)(
      "path",
      {
        d: rubberBand.path,
        fill: "none",
        stroke: rubberBand.stroke,
        strokeDasharray: "3 6",
        strokeLinecap: "round",
        strokeWidth: rubberBand.strokeWidth
      }
    ) : null,
    showDetachedHint ? /* @__PURE__ */ (0, import_jsx_runtime12.jsx)("g", { children: /* @__PURE__ */ (0, import_jsx_runtime12.jsx)(DetachedHint, { rect: ghostRect }) }) : null,
    drag.breakRipple ? /* @__PURE__ */ (0, import_jsx_runtime12.jsx)(
      "circle",
      {
        className: "kmind-ripple",
        cx: drag.breakRipple.x,
        cy: drag.breakRipple.y,
        fill: "none",
        r: 10,
        stroke: "rgba(239, 68, 68, 0.75)",
        strokeWidth: 2
      },
      drag.breakRipple.key
    ) : null
  ] });
}
function GroupDragHint(props) {
  const text5 = props.text;
  const width = Math.max(54, text5.length * 8 + 18);
  const height = 24;
  const x5 = props.rect.x + props.rect.width - width;
  const y = props.rect.y - height - 8;
  return /* @__PURE__ */ (0, import_jsx_runtime12.jsxs)("g", { children: [
    /* @__PURE__ */ (0, import_jsx_runtime12.jsx)(
      "rect",
      {
        fill: "none",
        height: props.rect.height,
        rx: 10,
        stroke: "rgba(37, 99, 235, 0.72)",
        strokeDasharray: "7 6",
        strokeWidth: 2,
        width: props.rect.width,
        x: props.rect.x,
        y: props.rect.y
      }
    ),
    /* @__PURE__ */ (0, import_jsx_runtime12.jsx)(
      "rect",
      {
        fill: "rgba(37, 99, 235, 0.92)",
        height,
        rx: 10,
        width,
        x: x5,
        y
      }
    ),
    /* @__PURE__ */ (0, import_jsx_runtime12.jsx)(
      "text",
      {
        fill: "#ffffff",
        fontFamily: nodeFontFamily,
        fontSize: 12,
        fontWeight: 700,
        textAnchor: "middle",
        x: x5 + width / 2,
        y: y + height / 2 + 4,
        children: text5
      }
    )
  ] });
}
function DetachedHint(props) {
  const text5 = "\u677E\u624B\u521B\u5EFA\u4E3A\u65B0\u6839\u8282\u70B9";
  const paddingX = 10;
  const paddingY = 6;
  const approxCharWidth = 7;
  const width = paddingX * 2 + text5.length * approxCharWidth;
  const height = 24;
  const x5 = props.rect.x + props.rect.width / 2 - width / 2;
  const y = props.rect.y - height - 10;
  return /* @__PURE__ */ (0, import_jsx_runtime12.jsxs)("g", { children: [
    /* @__PURE__ */ (0, import_jsx_runtime12.jsx)(
      "rect",
      {
        fill: "rgba(15, 23, 42, 0.85)",
        height,
        rx: 10,
        width,
        x: x5,
        y
      }
    ),
    /* @__PURE__ */ (0, import_jsx_runtime12.jsx)(
      "text",
      {
        fill: "#ffffff",
        fontFamily: nodeFontFamily,
        fontSize: 12,
        textAnchor: "middle",
        x: x5 + width / 2,
        y: y + height / 2 + 4,
        children: text5
      }
    )
  ] });
}
function resolveDashedConnector(doc3, layout, drag, ghostRect) {
  if (drag.intent.kind === "as-child") {
    const layoutType = resolveContainerLayout(doc3, drag.intent.target.id);
    const from2 = drag.intent.target.type === "node" ? layout.nodes[drag.intent.target.id] : layout.summaries[drag.intent.target.id];
    if (!from2) return null;
    return { path: layoutType === "tree-down" ? cubicPathVertical(from2, ghostRect) : cubicPathHorizontal(from2, ghostRect) };
  }
  if (drag.intent.kind === "as-sibling" && drag.intent.parent.type !== "root") {
    const layoutType = resolveContainerLayout(doc3, drag.intent.parent.id);
    const from2 = drag.intent.parent.type === "node" ? layout.nodes[drag.intent.parent.id] : layout.summaries[drag.intent.parent.id];
    if (!from2) return null;
    return { path: layoutType === "tree-down" ? cubicPathVertical(from2, ghostRect) : cubicPathHorizontal(from2, ghostRect) };
  }
  return null;
}
function resolveRubberBand(doc3, layout, originParent, ghostRect) {
  const from2 = originParent.type === "node" ? layout.nodes[originParent.id] : layout.summaries[originParent.id];
  if (!from2) return null;
  const layoutType = resolveContainerLayout(doc3, originParent.id);
  const path2 = layoutType === "tree-down" ? cubicPathVertical(from2, ghostRect) : cubicPathHorizontal(from2, ghostRect);
  const start = layoutType === "tree-down" ? { x: from2.x + from2.width / 2, y: from2.y + from2.height } : { x: from2.x + from2.width, y: from2.y + from2.height / 2 };
  const end = layoutType === "tree-down" ? { x: ghostRect.x + ghostRect.width / 2, y: ghostRect.y } : { x: ghostRect.x, y: ghostRect.y + ghostRect.height / 2 };
  const distance = Math.hypot(end.x - start.x, end.y - start.y);
  const t = Math.max(0, Math.min(1, distance / 140));
  const strokeWidth = 2 - 1.1 * t;
  const alpha2 = 0.3 + 0.6 * t;
  const stroke = `rgba(239, 68, 68, ${alpha2.toFixed(3)})`;
  return { path: path2, stroke, strokeWidth };
}
function cubicPathHorizontal(from2, to) {
  const startX = from2.x + from2.width;
  const startY = from2.y + from2.height / 2;
  const endX = to.x;
  const endY = to.y + to.height / 2;
  const c1X = startX + 40;
  const c1Y = startY;
  const c2X = endX - 40;
  const c2Y = endY;
  return `M ${startX} ${startY} C ${c1X} ${c1Y}, ${c2X} ${c2Y}, ${endX} ${endY}`;
}
function cubicPathVertical(from2, to) {
  const startX = from2.x + from2.width / 2;
  const startY = from2.y + from2.height;
  const endX = to.x + to.width / 2;
  const endY = to.y;
  const c1X = startX;
  const c1Y = startY + 40;
  const c2X = endX;
  const c2Y = endY - 40;
  return `M ${startX} ${startY} C ${c1X} ${c1Y}, ${c2X} ${c2Y}, ${endX} ${endY}`;
}

// ../react/src/mindmap-editor/overlays/context-menu-overlay.tsx
var import_react6 = __toESM(require_react(), 1);

// ../react/src/dom-utils.ts
function isNodeLike(target2) {
  return typeof target2 === "object" && target2 !== null && typeof target2.nodeType === "number";
}
function isElementLike(target2) {
  return isNodeLike(target2) && target2.nodeType === 1;
}
function resolveOwnerDocument(target2) {
  if (!target2) return null;
  const nodeType = target2.nodeType;
  if (nodeType === 9) return target2;
  return target2.ownerDocument ?? null;
}
function resolveOwnerWindow(target2) {
  const doc3 = resolveOwnerDocument(target2);
  return doc3?.defaultView ?? null;
}

// ../react/src/mindmap-editor/ui/builtin-icon.tsx
var import_jsx_runtime13 = __toESM(require_jsx_runtime(), 1);
function Icon(props) {
  const svg = getBuiltinIconSvg(props.iconId);
  if (!svg) return null;
  const size = props.size ?? 18;
  const normalized = normalizeBuiltinIconId(props.iconId);
  return /* @__PURE__ */ (0, import_jsx_runtime13.jsx)(
    "span",
    {
      "aria-hidden": "true",
      className: props.className,
      "data-km-icon-id": normalized,
      style: {
        width: size,
        height: size,
        display: "inline-flex",
        alignItems: "center",
        justifyContent: "center",
        lineHeight: 0,
        flexShrink: 0,
        pointerEvents: "none",
        ...props.style
      },
      dangerouslySetInnerHTML: { __html: svg }
    }
  );
}

// ../react/src/mindmap-editor/utils/view-box.ts
function clampCameraZoom(zoom) {
  return Math.min(4, Math.max(0.1, zoom));
}
function resolveViewBoxFromCamera(camera, viewport) {
  const zoom = camera.zoom || 1;
  const width = viewport.width > 0 ? viewport.width / zoom : 1;
  const height = viewport.height > 0 ? viewport.height / zoom : 1;
  return { x: camera.x, y: camera.y, width, height };
}
function resolveAnchoredCamera(args) {
  const safeZoom = clampCameraZoom(args.nextZoom);
  const safeRatio = {
    x: Math.max(0, Math.min(1, args.anchorRatio.x)),
    y: Math.max(0, Math.min(1, args.anchorRatio.y))
  };
  const worldX = args.anchorWorld?.x ?? args.currentView.x + safeRatio.x * args.currentView.width;
  const worldY = args.anchorWorld?.y ?? args.currentView.y + safeRatio.y * args.currentView.height;
  const nextViewWidth = args.viewport.width > 0 ? args.viewport.width / safeZoom : 1;
  const nextViewHeight = args.viewport.height > 0 ? args.viewport.height / safeZoom : 1;
  return {
    ...args.current,
    zoom: safeZoom,
    x: Math.round(worldX - safeRatio.x * nextViewWidth),
    y: Math.round(worldY - safeRatio.y * nextViewHeight)
  };
}
function formatViewBox(viewBox) {
  return `${viewBox.x} ${viewBox.y} ${viewBox.width} ${viewBox.height}`;
}
function worldRectToViewportRect(args) {
  const scaleX = args.viewport.width > 0 && Number.isFinite(args.viewport.width) && args.viewBox.width > 0 && Number.isFinite(args.viewBox.width) ? args.viewport.width / args.viewBox.width : 1;
  const scaleY = args.viewport.height > 0 && Number.isFinite(args.viewport.height) && args.viewBox.height > 0 && Number.isFinite(args.viewBox.height) ? args.viewport.height / args.viewBox.height : 1;
  return {
    x: (args.rect.x - args.viewBox.x) * scaleX,
    y: (args.rect.y - args.viewBox.y) * scaleY,
    width: args.rect.width * scaleX,
    height: args.rect.height * scaleY
  };
}

// ../react/src/mindmap-editor/overlays/node-selection-actions.ts
function isSelectionPopoverDisabled(popover, snapshot) {
  if (popover.requiredSelection === "node") return snapshot.editor.selection?.type !== "node";
  if (popover.requiredSelection === "relation") return snapshot.editor.selection?.type !== "relation";
  if (popover.requiredSelection === "summary") return snapshot.editor.selection?.type !== "summary";
  return false;
}
function resolveSelectionToolbarMenuItems(items, snapshot) {
  if (typeof items === "function") return items({ snapshot });
  return items;
}
function filterSelectionToolbarItems(items, args) {
  return items.filter((item) => {
    if (item.area !== args.area) return false;
    const scope = item.scope ?? "any";
    if (scope === "any") return true;
    if (scope === "root") return args.isRoot;
    if (scope === "child") return !args.isRoot;
    return true;
  });
}
function estimateActionWidth(args) {
  return args.showChevron ? 56 : 36;
}
function buildSelectionQuickActions(args) {
  const areas = ["A", "C"];
  const registryActions = [];
  for (const area of areas) {
    const items = filterSelectionToolbarItems(args.selectionToolbar, { area, isRoot: args.isRoot });
    for (const item of items) {
      const showChevron = item.kind !== "button";
      registryActions.push({
        id: item.id,
        title: item.title,
        iconId: item.icon ?? null,
        estimatedWidth: estimateActionWidth({ showChevron }),
        showChevron,
        source: "registry",
        item
      });
    }
  }
  const builtins = [
    {
      id: "builtin.links",
      title: args.labels["builtin.links"],
      iconId: "kmind-icon://builtin/ui/link",
      estimatedWidth: estimateActionWidth({ showChevron: false }),
      showChevron: false,
      source: "builtin",
      builtinId: "builtin.links"
    },
    {
      id: "builtin.image",
      title: args.labels["builtin.image"],
      iconId: "kmind-icon://builtin/ui/image",
      estimatedWidth: estimateActionWidth({ showChevron: true }),
      showChevron: true,
      source: "builtin",
      builtinId: "builtin.image"
    },
    {
      id: "builtin.icons",
      title: args.labels["builtin.icons"],
      iconId: "kmind-icon://builtin/ui/icons",
      estimatedWidth: estimateActionWidth({ showChevron: true }),
      showChevron: true,
      source: "builtin",
      builtinId: "builtin.icons"
    },
    {
      id: "builtin.tags",
      title: args.labels["builtin.tags"],
      iconId: "kmind-icon://builtin/ui/tags",
      estimatedWidth: estimateActionWidth({ showChevron: true }),
      showChevron: true,
      source: "builtin",
      builtinId: "builtin.tags"
    },
    {
      id: "builtin.brush",
      title: args.labels["builtin.brush"],
      iconId: "kmind-icon://builtin/ui/brush",
      estimatedWidth: estimateActionWidth({ showChevron: false }),
      showChevron: false,
      source: "builtin",
      builtinId: "builtin.brush"
    },
    {
      id: "builtin.notes",
      title: args.labels["builtin.notes"],
      iconId: "kmind-icon://builtin/ui/notes",
      estimatedWidth: estimateActionWidth({ showChevron: false }),
      showChevron: false,
      source: "builtin",
      builtinId: "builtin.notes"
    },
    {
      id: "builtin.comments",
      title: args.labels["builtin.comments"],
      iconId: "kmind-icon://builtin/ui/comments",
      estimatedWidth: estimateActionWidth({ showChevron: false }),
      showChevron: false,
      source: "builtin",
      builtinId: "builtin.comments"
    }
  ];
  return [...registryActions, ...builtins];
}
function buildSummaryContextQuickActions(args) {
  const relationItem = args.selectionToolbar.find((item) => item.id === "selection.relation.start" && item.kind === "button");
  if (!relationItem || relationItem.kind !== "button") return [];
  return [
    {
      id: relationItem.id,
      title: relationItem.title,
      iconId: relationItem.icon ?? "kmind-icon://builtin/ui/relation",
      estimatedWidth: estimateActionWidth({ showChevron: false }),
      showChevron: false,
      source: "registry",
      item: relationItem
    }
  ];
}
function partitionSelectionQuickActions(args) {
  const gap = Math.max(0, args.gap ?? 8);
  const moreButtonWidth = Math.max(0, args.moreButtonWidth ?? 34);
  const visible = [];
  const overflow = [];
  let usedWidth = 0;
  for (let index = 0; index < args.actions.length; index += 1) {
    const action = args.actions[index];
    if (!action) continue;
    const actionWidth = action.estimatedWidth;
    const nextUsed = usedWidth + (visible.length > 0 ? gap : 0) + actionWidth;
    const reservedForMore = (visible.length > 0 || nextUsed > 0 ? gap : 0) + moreButtonWidth;
    if (nextUsed + reservedForMore <= args.availableWidth) {
      visible.push(action);
      usedWidth = nextUsed;
    } else {
      overflow.push(action);
    }
  }
  return { visible, overflow };
}

// ../react/src/mindmap-editor/overlays/context-menu-overlay.tsx
var import_jsx_runtime14 = __toESM(require_jsx_runtime(), 1);
var contextMenuWidth = 320;
var nodeMenuPadding = 12;
var submenuOverlap = 18;
var submenuSwitchDelayMs = 140;
var submenuCloseDelayMs = 220;
function isImageCopySubmenu(id) {
  return id === "node.copy-image" || id === "canvas.copy-image";
}
function isImageCopyPreviewCommand(item, parentSubmenuId) {
  return item.kind === "command" && Boolean(parentSubmenuId && isImageCopySubmenu(parentSubmenuId));
}
function estimateMenuItemHeight(item, parentSubmenuId) {
  if (item.kind === "separator") return 13;
  if (isImageCopyPreviewCommand(item, parentSubmenuId)) return 94;
  return 36;
}
function estimateMenuContentHeight(items, parentSubmenuId) {
  return items.reduce((sum, item) => sum + estimateMenuItemHeight(item, parentSubmenuId), 16);
}
function clamp2(value, min, max) {
  return Math.max(min, Math.min(value, max));
}
function resolveContributionItems(contribution, ctx) {
  const items = contribution.items;
  if (typeof items === "function") return items(ctx);
  return items;
}
function resolveSubmenuItems(item, ctx) {
  const items = item.items;
  if (typeof items === "function") return items(ctx);
  return items;
}
function flattenMenu(args) {
  const items = [];
  for (const contribution of args.contributions) {
    if (contribution.scope !== args.scope) continue;
    items.push(...resolveContributionItems(contribution, { snapshot: args.snapshot, target: args.target, anchor: args.anchor }));
  }
  return items;
}
function resolveContextMenuTarget(state) {
  if (state.scope === "canvas") return { kind: "canvas" };
  if (state.scope === "summary") return { kind: "summary", summaryId: state.summaryId };
  if (!state.nodeId) return void 0;
  return { kind: "node", nodeId: state.nodeId };
}
function ImageCopyPreviewThumbnail(props) {
  const isWindow = props.variant === "window";
  return /* @__PURE__ */ (0, import_jsx_runtime14.jsxs)(
    "span",
    {
      "aria-hidden": "true",
      style: {
        position: "relative",
        display: "block",
        width: 82,
        height: 52,
        flex: "0 0 auto",
        overflow: "hidden",
        borderRadius: 10,
        border: "1px solid color-mix(in srgb, var(--km-border) 82%, transparent)",
        background: isWindow ? "linear-gradient(180deg, rgba(248,250,252,0.98), rgba(241,245,249,0.92))" : "var(--km-panel)",
        boxShadow: isWindow ? "0 10px 22px rgba(15,23,42,0.14)" : "inset 0 0 0 1px rgba(148,163,184,0.08)"
      },
      children: [
        isWindow ? /* @__PURE__ */ (0, import_jsx_runtime14.jsxs)(
          "span",
          {
            style: {
              position: "absolute",
              inset: "0 0 auto 0",
              height: 12,
              borderBottom: "1px solid rgba(148,163,184,0.34)",
              background: "linear-gradient(180deg, rgba(255,255,255,0.95), rgba(226,232,240,0.8))"
            },
            children: [
              /* @__PURE__ */ (0, import_jsx_runtime14.jsx)("span", { style: { position: "absolute", left: 7, top: 4, width: 4, height: 4, borderRadius: 999, background: "#ef4444" } }),
              /* @__PURE__ */ (0, import_jsx_runtime14.jsx)("span", { style: { position: "absolute", left: 14, top: 4, width: 4, height: 4, borderRadius: 999, background: "#f59e0b" } }),
              /* @__PURE__ */ (0, import_jsx_runtime14.jsx)("span", { style: { position: "absolute", left: 21, top: 4, width: 4, height: 4, borderRadius: 999, background: "#22c55e" } })
            ]
          }
        ) : null,
        /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(
          "span",
          {
            style: {
              position: "absolute",
              left: 15,
              top: isWindow ? 29 : 24,
              width: 22,
              height: 12,
              borderRadius: 4,
              background: "#2563eb"
            }
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(
          "span",
          {
            style: {
              position: "absolute",
              left: 36,
              top: isWindow ? 35 : 30,
              width: 24,
              height: 2,
              background: "rgba(15,23,42,0.74)"
            }
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(
          "span",
          {
            style: {
              position: "absolute",
              left: 60,
              top: isWindow ? 30 : 25,
              width: 13,
              height: 10,
              borderRadius: 4,
              border: "2px solid rgba(15,23,42,0.72)",
              background: "rgba(248,250,252,0.9)"
            }
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(
          "span",
          {
            style: {
              position: "absolute",
              left: 38,
              top: isWindow ? 18 : 13,
              width: 16,
              height: 10,
              borderRadius: 4,
              background: "rgba(226,232,240,0.95)"
            }
          }
        )
      ]
    }
  );
}
function ContextMenuOverlay(props) {
  const rootRef = (0, import_react6.useRef)(null);
  const openSubmenuTimerRef = (0, import_react6.useRef)(null);
  const closeSubmenuTimerRef = (0, import_react6.useRef)(null);
  const [openSubmenu, setOpenSubmenu] = (0, import_react6.useState)(null);
  const clearSubmenuOpenTimer = () => {
    if (!openSubmenuTimerRef.current) return;
    clearTimeout(openSubmenuTimerRef.current);
    openSubmenuTimerRef.current = null;
  };
  const clearSubmenuCloseTimer = () => {
    if (!closeSubmenuTimerRef.current) return;
    clearTimeout(closeSubmenuTimerRef.current);
    closeSubmenuTimerRef.current = null;
  };
  const cancelPendingSubmenuChanges = () => {
    clearSubmenuOpenTimer();
    clearSubmenuCloseTimer();
  };
  const requestOpenSubmenu = (next) => {
    clearSubmenuCloseTimer();
    clearSubmenuOpenTimer();
    const delay = openSubmenu && openSubmenu.id !== next.id ? submenuSwitchDelayMs : 0;
    if (delay === 0) {
      setOpenSubmenu(next);
      return;
    }
    openSubmenuTimerRef.current = setTimeout(() => {
      openSubmenuTimerRef.current = null;
      setOpenSubmenu(next);
    }, delay);
  };
  const requestCloseSubmenu = () => {
    clearSubmenuOpenTimer();
    clearSubmenuCloseTimer();
    closeSubmenuTimerRef.current = setTimeout(() => {
      closeSubmenuTimerRef.current = null;
      setOpenSubmenu(null);
    }, submenuCloseDelayMs);
  };
  (0, import_react6.useEffect)(() => {
    return () => {
      clearSubmenuOpenTimer();
      clearSubmenuCloseTimer();
    };
  }, []);
  const anchorPosition = (0, import_react6.useMemo)(() => {
    const state2 = props.state;
    if (!state2) return null;
    if (state2.scope !== "node" || !state2.nodeId) return { x: state2.x, y: state2.y };
    const nodeRect = props.nodeRects[state2.nodeId];
    if (!nodeRect) return { x: state2.x, y: state2.y };
    const viewportRect = worldRectToViewportRect({
      rect: nodeRect,
      viewBox: props.viewBox,
      viewport: props.viewportSize
    });
    const preferRight = viewportRect.x + viewportRect.width + 10 + contextMenuWidth + nodeMenuPadding <= props.viewportSize.width;
    return {
      x: preferRight ? viewportRect.x + viewportRect.width + 10 : viewportRect.x - contextMenuWidth - 10,
      y: viewportRect.y
    };
  }, [props.nodeRects, props.state, props.viewBox, props.viewportSize]);
  const items = (0, import_react6.useMemo)(() => {
    if (!props.state) return [];
    return flattenMenu({
      scope: props.state.scope,
      snapshot: props.snapshot,
      target: resolveContextMenuTarget(props.state),
      anchor: anchorPosition ? { x: anchorPosition.x, y: anchorPosition.y, world: props.state.world } : void 0,
      contributions: props.contributions
    });
  }, [anchorPosition, props.contributions, props.snapshot, props.state]);
  (0, import_react6.useEffect)(() => {
    if (!props.state) return;
    const win = resolveOwnerWindow(rootRef.current ?? props.containerRef.current) ?? (typeof window !== "undefined" ? window : null);
    if (!win) return;
    const onPointerDown = (event) => {
      const target3 = event.target;
      if (!isNodeLike(target3)) return;
      if (rootRef.current?.contains(target3)) return;
      props.onRequestClose();
    };
    win.addEventListener("pointerdown", onPointerDown, true);
    return () => win.removeEventListener("pointerdown", onPointerDown, true);
  }, [props.onRequestClose, props.state]);
  (0, import_react6.useEffect)(() => {
    if (!props.state) return;
    const win = resolveOwnerWindow(rootRef.current ?? props.containerRef.current) ?? (typeof window !== "undefined" ? window : null);
    if (!win) return;
    const onKeyDown = (event) => {
      if (event.key !== "Escape") return;
      event.preventDefault();
      props.onRequestClose();
    };
    win.addEventListener("keydown", onKeyDown, true);
    return () => win.removeEventListener("keydown", onKeyDown, true);
  }, [props.onRequestClose, props.state]);
  if (!props.state) return null;
  const state = props.state;
  const container = props.containerRef.current;
  const maxWidth = container ? Math.max(0, container.clientWidth) : Math.max(0, props.viewportSize.width);
  const maxHeight = container ? Math.max(0, container.clientHeight) : Math.max(0, props.viewportSize.height);
  const quickActionBarVisible = (state.scope === "node" || state.scope === "summary") && props.quickActions.length > 0;
  const compactQuickActionMenu = state.scope === "summary" && quickActionBarVisible && items.length === 0;
  const menuWidth = compactQuickActionMenu ? Math.max(58, 24 + props.quickActions.length * 34 + Math.max(0, props.quickActions.length - 1) * 8) : contextMenuWidth;
  const menuHeight = Math.min(420, estimateMenuContentHeight(items) + (quickActionBarVisible ? compactQuickActionMenu ? 58 : 92 : 0));
  const padding = state.scope === "node" || state.scope === "summary" ? nodeMenuPadding : 8;
  const left = clamp2(anchorPosition?.x ?? state.x, padding, Math.max(padding, maxWidth - menuWidth - padding));
  const top = clamp2(anchorPosition?.y ?? state.y, padding, Math.max(padding, maxHeight - menuHeight - padding));
  const anchor = { x: anchorPosition?.x ?? state.x, y: anchorPosition?.y ?? state.y, world: state.world };
  const target2 = resolveContextMenuTarget(state);
  const resolveShortcutLabel = (item) => resolveCommandKeymapLabel({
    bindings: props.snapshot.registry.keymap,
    overrides: props.keymapOverrides,
    commandId: item.commandId,
    commandArgs: item.args
  }) ?? item.shortcut ?? null;
  const renderItem = (item, level, parentSubmenuId) => {
    if (item.kind === "separator") {
      return /* @__PURE__ */ (0, import_jsx_runtime14.jsx)("div", { style: { height: 1, margin: "6px 8px", background: "var(--km-border)" } }, item.id);
    }
    if (item.kind === "submenu") {
      const isOpen = openSubmenu?.id === item.id;
      const submenuItems = resolveSubmenuItems(item, { snapshot: props.snapshot, target: target2, anchor });
      return /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(
        "div",
        {
          onPointerEnter: (event) => {
            const root = rootRef.current;
            if (!root) return;
            const rootRect = root.getBoundingClientRect();
            const rect = event.currentTarget.getBoundingClientRect();
            requestOpenSubmenu({ id: item.id, y: rect.top - rootRect.top });
          },
          style: { position: "relative" },
          children: /* @__PURE__ */ (0, import_jsx_runtime14.jsxs)(
            "button",
            {
              onClick: (event) => {
                const root = rootRef.current;
                if (!root) return;
                const rootRect = root.getBoundingClientRect();
                const rect = event.currentTarget.getBoundingClientRect();
                cancelPendingSubmenuChanges();
                setOpenSubmenu((prev) => prev?.id === item.id ? null : { id: item.id, y: rect.top - rootRect.top });
              },
              style: {
                display: "flex",
                width: "100%",
                alignItems: "center",
                justifyContent: "space-between",
                gap: 10,
                padding: "8px 10px",
                borderRadius: 10,
                border: 0,
                background: isOpen ? "rgba(148,163,184,0.16)" : "transparent",
                color: "var(--km-text)",
                fontSize: 13,
                cursor: "default",
                outline: "none",
                boxShadow: "none",
                appearance: "none"
              },
              type: "button",
              children: [
                /* @__PURE__ */ (0, import_jsx_runtime14.jsx)("span", { style: { minWidth: 0, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }, children: item.title }),
                /* @__PURE__ */ (0, import_jsx_runtime14.jsx)("span", { style: { color: "var(--km-muted)", fontSize: 12 }, children: "\u203A" })
              ]
            }
          )
        },
        item.id
      );
    }
    const disabled = !props.isCommandEnabled(item.commandId, item.args);
    const premiumBlockedKey = (() => {
      if (props.snapshot.editor.viewModes.readOnly.value) return null;
      if (item.commandId === "node.todo.add" && !props.snapshot.capabilities.premium.canAddTodo) return "todo";
      return null;
    })();
    const effectiveDisabled = Boolean(disabled && !premiumBlockedKey);
    const shortcutLabel = resolveShortcutLabel(item);
    const handleCommandClick = () => {
      if (disabled) {
        if (premiumBlockedKey) {
          props.onPremiumFeatureBlocked?.(premiumBlockedKey);
          props.onRequestClose();
        }
        return;
      }
      void props.dispatchCommand(item.commandId, item.args);
      props.onRequestClose();
    };
    if (isImageCopyPreviewCommand(item, parentSubmenuId)) {
      const variant = item.id.endsWith(".window") ? "window" : "original";
      return /* @__PURE__ */ (0, import_jsx_runtime14.jsxs)(
        "button",
        {
          disabled: effectiveDisabled,
          onClick: handleCommandClick,
          style: {
            display: "flex",
            width: "100%",
            alignItems: "center",
            gap: 12,
            padding: "9px",
            borderRadius: 12,
            border: "1px solid transparent",
            background: "transparent",
            color: disabled ? "rgba(100,116,139,0.7)" : "var(--km-text)",
            fontSize: 13,
            cursor: effectiveDisabled ? "not-allowed" : "pointer",
            outline: "none",
            boxShadow: "none",
            appearance: "none",
            textAlign: "left"
          },
          type: "button",
          children: [
            /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(ImageCopyPreviewThumbnail, { variant }),
            /* @__PURE__ */ (0, import_jsx_runtime14.jsxs)("span", { style: { minWidth: 0, display: "flex", flexDirection: "column", gap: 4 }, children: [
              /* @__PURE__ */ (0, import_jsx_runtime14.jsx)("span", { style: { overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap", fontWeight: 700 }, children: item.title }),
              item.description ? /* @__PURE__ */ (0, import_jsx_runtime14.jsx)("span", { style: { color: "var(--km-muted)", fontSize: 12, lineHeight: 1.35, whiteSpace: "normal" }, children: item.description }) : null
            ] })
          ]
        },
        item.id
      );
    }
    return /* @__PURE__ */ (0, import_jsx_runtime14.jsxs)(
      "button",
      {
        disabled: effectiveDisabled,
        onPointerEnter: level === 0 ? requestCloseSubmenu : void 0,
        onClick: handleCommandClick,
        style: {
          display: "flex",
          width: "100%",
          alignItems: "center",
          justifyContent: "space-between",
          gap: 10,
          padding: "8px 10px",
          borderRadius: 10,
          border: 0,
          background: "transparent",
          color: disabled ? "rgba(100,116,139,0.7)" : "var(--km-text)",
          fontSize: 13,
          cursor: effectiveDisabled ? "not-allowed" : "pointer",
          outline: "none",
          boxShadow: "none",
          appearance: "none"
        },
        type: "button",
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime14.jsx)("span", { style: { minWidth: 0, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }, children: item.title }),
          shortcutLabel ? /* @__PURE__ */ (0, import_jsx_runtime14.jsx)("span", { style: { color: "var(--km-muted)", fontSize: 11, fontFamily: "ui-monospace, SFMono-Regular, Menlo, monospace" }, children: shortcutLabel }) : null
        ]
      },
      item.id
    );
  };
  const isQuickActionDisabled = (action) => {
    if (action.source === "registry") {
      const item = action.item;
      if (item.kind === "button") return !props.isCommandEnabled(item.commandId, item.args);
      if (item.kind === "popover") return isSelectionPopoverDisabled(item.popover, props.snapshot);
      if (item.kind === "menu") {
        const menuItems = resolveSelectionToolbarMenuItems(item.items, props.snapshot);
        return menuItems.length === 0;
      }
    }
    if (action.source === "builtin" && action.builtinId === "builtin.brush") {
      return Boolean(props.snapshot.editor.viewModes.readOnly.value);
    }
    return false;
  };
  return /* @__PURE__ */ (0, import_jsx_runtime14.jsxs)(
    "div",
    {
      ref: rootRef,
      onPointerEnter: cancelPendingSubmenuChanges,
      onPointerLeave: requestCloseSubmenu,
      style: {
        position: "absolute",
        left,
        top,
        width: menuWidth,
        pointerEvents: "auto",
        zIndex: 80
      },
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime14.jsxs)(
          "div",
          {
            style: {
              maxHeight: 420,
              overflowY: "auto",
              overflowX: "hidden",
              padding: compactQuickActionMenu ? 6 : 8,
              borderRadius: compactQuickActionMenu ? 14 : 16,
              border: "1px solid var(--km-border)",
              background: "var(--km-panel)",
              boxShadow: "0 20px 40px rgba(15, 23, 42, 0.18)"
            },
            children: [
              quickActionBarVisible ? /* @__PURE__ */ (0, import_jsx_runtime14.jsxs)(import_jsx_runtime14.Fragment, { children: [
                /* @__PURE__ */ (0, import_jsx_runtime14.jsx)("div", { style: { padding: compactQuickActionMenu ? 0 : "4px 4px 10px 4px" }, children: /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(
                  "div",
                  {
                    style: {
                      display: "flex",
                      flexWrap: "wrap",
                      gap: 8,
                      padding: 4,
                      borderRadius: 14,
                      background: "color-mix(in srgb, var(--km-panel) 94%, rgba(148,163,184,0.08))"
                    },
                    children: props.quickActions.map((action) => {
                      const disabled = isQuickActionDisabled(action);
                      return /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(
                        "button",
                        {
                          disabled,
                          onPointerDown: (event) => {
                            if (disabled) return;
                            props.onQuickActionPointerDown?.(action.id, { clientX: event.clientX, clientY: event.clientY });
                          },
                          onClick: () => {
                            if (disabled) return;
                            if (action.source === "registry" && action.item.kind === "button") {
                              void props.dispatchCommand(action.item.commandId, action.item.args);
                              props.onRequestClose();
                              return;
                            }
                            props.onQuickActionRequest(action.id);
                            props.onRequestClose();
                          },
                          style: {
                            width: 34,
                            height: 34,
                            borderRadius: 11,
                            border: "1px solid var(--km-border)",
                            background: disabled ? "rgba(148,163,184,0.08)" : "var(--km-panel)",
                            color: disabled ? "rgba(100,116,139,0.6)" : "var(--km-text)",
                            cursor: disabled ? "not-allowed" : "pointer",
                            display: "inline-flex",
                            alignItems: "center",
                            justifyContent: "center",
                            transition: "background 160ms ease, color 160ms ease, border-color 160ms ease"
                          },
                          title: action.title,
                          type: "button",
                          children: action.iconId ? /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(Icon, { iconId: action.iconId, size: 16 }) : /* @__PURE__ */ (0, import_jsx_runtime14.jsx)("span", { style: { fontSize: 13, fontWeight: 700 }, children: action.title.slice(0, 1) })
                        },
                        action.id
                      );
                    })
                  }
                ) }),
                items.length > 0 ? /* @__PURE__ */ (0, import_jsx_runtime14.jsx)("div", { style: { height: 1, margin: "0 6px 8px 6px", background: "color-mix(in srgb, var(--km-border) 78%, transparent)" } }) : null
              ] }) : null,
              items.length === 0 ? quickActionBarVisible ? null : /* @__PURE__ */ (0, import_jsx_runtime14.jsx)("div", { style: { padding: "10px 10px", color: "var(--km-muted)", fontSize: 12 }, children: "No actions" }) : items.map((item) => renderItem(item, 0))
            ]
          }
        ),
        openSubmenu ? (() => {
          const submenuItem = items.find((it) => it.kind === "submenu" && it.id === openSubmenu.id);
          if (!submenuItem) return null;
          const submenuItems = resolveSubmenuItems(submenuItem, { snapshot: props.snapshot, anchor });
          const submenuHeight = Math.min(360, estimateMenuContentHeight(submenuItems, submenuItem.id));
          const preferRight = left + contextMenuWidth + 12 + contextMenuWidth + 8 <= maxWidth;
          const submenuLeft = preferRight ? contextMenuWidth - submenuOverlap : -contextMenuWidth + submenuOverlap;
          const submenuTop = Math.max(8, Math.min(openSubmenu.y, Math.max(8, 360 - submenuHeight - 8)));
          return /* @__PURE__ */ (0, import_jsx_runtime14.jsx)(
            "div",
            {
              onPointerEnter: cancelPendingSubmenuChanges,
              style: {
                position: "absolute",
                left: submenuLeft,
                top: submenuTop,
                width: contextMenuWidth,
                maxHeight: 360,
                overflowY: "auto",
                overflowX: "hidden",
                padding: 6,
                borderRadius: 14,
                border: "1px solid var(--km-border)",
                background: "var(--km-panel)",
                boxShadow: "0 18px 36px rgba(15, 23, 42, 0.18)",
                zIndex: 85
              },
              children: submenuItems.map((item) => renderItem(item, 1, submenuItem.id))
            }
          );
        })() : null
      ]
    }
  );
}

// ../react/src/mindmap-editor/overlays/links-panel.tsx
var import_react7 = __toESM(require_react(), 1);
init_src();
var import_jsx_runtime15 = __toESM(require_jsx_runtime(), 1);
var noopNodeRefResolveStore = {
  subscribe(_listener) {
    return () => {
    };
  },
  getSnapshot() {
    return 0;
  }
};
var linksPanelCssText = `
  .km-links-panel .km-popover-scroll {
    scrollbar-width: thin;
    scrollbar-color: rgba(148, 163, 184, 0.65) transparent;
  }
  .km-links-panel .km-popover-scroll::-webkit-scrollbar {
    width: 10px;
  }
  .km-links-panel .km-popover-scroll::-webkit-scrollbar-track {
    background: transparent;
  }
  .km-links-panel .km-popover-scroll::-webkit-scrollbar-thumb {
    background-color: rgba(148, 163, 184, 0.50);
    border-radius: 999px;
    border: 3px solid transparent;
    background-clip: content-box;
  }
  .km-links-panel .km-popover-scroll:hover::-webkit-scrollbar-thumb {
    background-color: rgba(148, 163, 184, 0.72);
  }
`;
function IconPreview(props) {
  const normalized = normalizeBuiltinIconId(props.iconId);
  const svg = getBuiltinIconSvg(normalized);
  if (!svg) {
    return /* @__PURE__ */ (0, import_jsx_runtime15.jsx)("span", { style: { fontSize: 10, color: "var(--km-muted)" }, children: normalized.replace("kmind-icon://builtin/", "") });
  }
  return /* @__PURE__ */ (0, import_jsx_runtime15.jsx)("span", { style: { width: 18, height: 18 }, dangerouslySetInnerHTML: { __html: svg } });
}
function resolveExternalIconId2(link, external) {
  const custom = typeof link.iconId === "string" ? normalizeBuiltinIconId(link.iconId.trim()) : "";
  if (custom.length > 0 && custom !== "auto") return custom;
  return external?.resolveUrlBehavior?.(link.url)?.autoIconId ?? "kmind-icon://builtin/ui/link";
}
function LinksPanel(props) {
  const t = useT();
  const nodeRefResolveStore = props.nodeRefResolveStore ?? noopNodeRefResolveStore;
  const nodeRefResolveVersion = (0, import_react7.useSyncExternalStore)(
    nodeRefResolveStore.subscribe,
    nodeRefResolveStore.getSnapshot,
    nodeRefResolveStore.getSnapshot
  );
  const node = props.doc.nodes[props.nodeId] ?? null;
  const currentDocId = typeof props.documentId === "string" && props.documentId.trim().length > 0 ? props.documentId.trim() : null;
  const readOnly = Boolean(props.readOnly);
  const mode = readOnly ? "preview" : props.mode ?? "preview";
  const canEdit = Boolean(!readOnly && mode === "edit" && props.dispatchCommand && node && !node.attrs?.locked && !node.attrs?.readonly);
  const canEnterEdit = Boolean(!readOnly && props.dispatchCommand && node && !node.attrs?.locked && !node.attrs?.readonly);
  const variant = props.variant ?? "floating";
  const effectivePremium = props.premiumCapabilities ?? {
    canCreateBacklinks: true,
    canInsertFormula: true,
    canInsertCloze: true,
    canCreateComments: true,
    canInsertSiyuanDocLink: true
  };
  const canCreateBacklinks = props.isCommandEnabled ? props.isCommandEnabled("node.link.addInternal", { nodeId: props.nodeId }) : effectivePremium.canCreateBacklinks;
  const rootRef = (0, import_react7.useRef)(null);
  const dispatch = (0, import_react7.useCallback)(async (commandId, args) => {
    if (!props.dispatchCommand) return;
    await props.dispatchCommand(commandId, args);
  }, [props.dispatchCommand]);
  const commitPendingExternalLinkEdits = (0, import_react7.useCallback)(async () => {
    if (!canEdit || !node) return;
    const root = rootRef.current;
    if (!root) return;
    const inputs = Array.from(root.querySelectorAll("input[data-km-link-edit-id][data-km-link-edit-field]"));
    if (inputs.length === 0) return;
    const inputByKey = /* @__PURE__ */ new Map();
    for (const input of inputs) {
      const id = input.dataset.kmLinkEditId;
      const field = input.dataset.kmLinkEditField;
      if (!id || !field) continue;
      inputByKey.set(`${id}:${field}`, input);
    }
    const currentExternal = getNodeLinks(node).filter((link) => link.kind === "external");
    for (const link of currentExternal) {
      const urlInput = inputByKey.get(`${link.id}:url`);
      const labelInput = inputByKey.get(`${link.id}:label`);
      const nextUrl = urlInput?.value.trim() ?? "";
      const nextLabel = labelInput?.value.trim() ?? "";
      const currentLabel = link.label?.trim() ?? "";
      if (nextUrl && nextUrl !== link.url) {
        await dispatch("node.link.updateExternal", { nodeId: props.nodeId, linkId: link.id, url: nextUrl });
      }
      if (labelInput && nextLabel !== currentLabel) {
        await dispatch("node.link.updateExternal", { nodeId: props.nodeId, linkId: link.id, label: nextLabel });
      }
    }
  }, [canEdit, dispatch, node, props.nodeId]);
  const closePanel = (0, import_react7.useCallback)(async () => {
    try {
      await commitPendingExternalLinkEdits();
    } finally {
      props.onClose();
    }
  }, [commitPendingExternalLinkEdits, props.onClose]);
  (0, import_react7.useEffect)(() => {
    const win = resolveOwnerWindow(rootRef.current) ?? (typeof window !== "undefined" ? window : null);
    if (!win) return;
    const onPointerDown = (event) => {
      const target2 = event.target;
      if (!isNodeLike(target2)) return;
      const root = rootRef.current;
      if (root && root.contains(target2)) return;
      void closePanel();
    };
    win.addEventListener("pointerdown", onPointerDown, true);
    return () => win.removeEventListener("pointerdown", onPointerDown, true);
  }, [closePanel]);
  const links = node ? getNodeLinks(node) : [];
  const outgoingInternal = links.filter((link) => link.kind === "internal");
  const outgoingExternal = links.filter((link) => link.kind === "external");
  const incoming = props.backlinksIndex[props.nodeId] ?? [];
  const resolveNodeTitle = (nodeId) => {
    const text5 = props.doc.nodes[nodeId]?.text ?? "";
    const trimmed = text5.trim();
    return trimmed.length > 0 ? trimmed : `#${nodeId}`;
  };
  const normalizeDocId = (value) => {
    if (typeof value !== "string") return null;
    const trimmed = value.trim();
    return trimmed.length > 0 ? trimmed : null;
  };
  const normalizeNodeRef = (ref) => ({
    docId: normalizeDocId(ref.docId),
    nodeId: ref.nodeId
  });
  const makeNodeRefKey = (ref) => `${ref.docId ?? ""}#${ref.nodeId}`;
  const uniqueIncoming = (() => {
    const result = [];
    const visited = /* @__PURE__ */ new Set();
    for (const ref of incoming) {
      const normalized = normalizeNodeRef(ref);
      const key = makeNodeRefKey(normalized);
      if (visited.has(key)) continue;
      visited.add(key);
      result.push(normalized);
    }
    return result;
  })();
  const resolveNodeRefExists = (ref) => {
    if (!ref.docId || currentDocId && ref.docId === currentDocId) return Boolean(props.doc.nodes[ref.nodeId]);
    if (!props.resolveNodeRefExists) return null;
    return props.resolveNodeRefExists({ docId: ref.docId, nodeId: ref.nodeId });
  };
  const outgoingInternalItems = outgoingInternal.map((link) => {
    const ref = normalizeNodeRef({ docId: link.docId, nodeId: link.nodeId });
    const exists = resolveNodeRefExists(ref);
    const status = exists === null ? "unknown" : exists ? "ok" : "broken";
    return { link, ref, status };
  });
  const brokenOutgoingInternal = outgoingInternalItems.filter((item) => item.status === "broken");
  const [copyState, setCopyState] = (0, import_react7.useState)("idle");
  (0, import_react7.useEffect)(() => {
    if (copyState === "idle") return;
    const id = window.setTimeout(() => setCopyState("idle"), 1e3);
    return () => window.clearTimeout(id);
  }, [copyState]);
  const [newInternalTarget, setNewInternalTarget] = (0, import_react7.useState)("");
  const [newInternalLabel, setNewInternalLabel] = (0, import_react7.useState)("");
  const [newExternalUrl, setNewExternalUrl] = (0, import_react7.useState)("");
  const [newExternalLabel, setNewExternalLabel] = (0, import_react7.useState)("");
  const [newExternalIconId, setNewExternalIconId] = (0, import_react7.useState)(null);
  const [iconPickerFor, setIconPickerFor] = (0, import_react7.useState)(null);
  (0, import_react7.useEffect)(() => {
    setIconPickerFor(null);
  }, [props.nodeId]);
  const iconGroups = (0, import_react7.useMemo)(() => listBuiltinIconPickerGroups({ surface: "external-link" }), []);
  const notifyBlocked = (feature) => {
    props.onPremiumFeatureBlocked?.(feature);
  };
  const copyNodeId = async () => {
    if (!props.clipboard) {
      await props.dialog.alert(t("editor.links.alert.clipboardUnavailable"));
      return;
    }
    try {
      await props.clipboard.writeText(props.nodeId);
      setCopyState("copied-id");
    } catch {
      await props.dialog.alert(t("editor.links.alert.copyFailed"));
    }
  };
  const copyNodeLink = async () => {
    if (!props.clipboard) {
      await props.dialog.alert(t("editor.links.alert.clipboardUnavailable"));
      return;
    }
    if (!currentDocId) {
      await copyNodeId();
      return;
    }
    try {
      await props.clipboard.writeText(`kmind-node://${currentDocId}/${props.nodeId}`);
      setCopyState("copied-link");
    } catch {
      await props.dialog.alert(t("editor.links.alert.copyFailed"));
    }
  };
  const navigateToNodeRef = async (ref) => {
    const targetDocId = ref.docId;
    if (!targetDocId || targetDocId === currentDocId) {
      props.onSelectNode(ref.nodeId);
      return;
    }
    if (!props.onOpenNodeRef) {
      await props.dialog.alert(t("editor.links.alert.crossDocUnavailable"));
      return;
    }
    props.onOpenNodeRef({ docId: targetDocId, nodeId: ref.nodeId });
    await closePanel();
  };
  const resolveNodeRefTitle = (ref) => {
    if (typeof ref.label === "string" && ref.label.trim().length > 0) return ref.label.trim();
    if (!ref.docId || ref.docId === currentDocId) return resolveNodeTitle(ref.nodeId);
    const resolved = props.resolveNodeRefTitle?.({ docId: ref.docId, nodeId: ref.nodeId }) ?? null;
    if (resolved && resolved.trim().length > 0) return resolved.trim();
    return `#${ref.nodeId}`;
  };
  const resolveNodeRefSubtitle = (ref) => {
    if (!ref.docId || ref.docId === currentDocId) return `#${ref.nodeId}`;
    return `${ref.docId}#${ref.nodeId}`;
  };
  const sectionBodyStyle = { display: "flex", flexDirection: "column", gap: 8 };
  const cardStyle = variant === "embedded" ? {
    position: "relative",
    left: 0,
    top: 0,
    width: "100%",
    maxHeight: "none",
    overflow: "hidden",
    display: "flex",
    flexDirection: "column",
    borderRadius: 0,
    border: "none",
    background: "transparent",
    boxShadow: "none",
    pointerEvents: "auto"
  } : {
    position: "absolute",
    left: props.x,
    top: props.y,
    width: props.width,
    maxHeight: props.maxHeight,
    overflow: "hidden",
    display: "flex",
    flexDirection: "column",
    borderRadius: 14,
    border: "1px solid var(--km-border)",
    background: "var(--km-panel)",
    boxShadow: "0 18px 36px rgba(15, 23, 42, 0.18)",
    pointerEvents: "auto",
    zIndex: 70
  };
  const headerStyle = {
    display: "flex",
    alignItems: "center",
    justifyContent: "space-between",
    gap: 12,
    padding: "10px 12px",
    borderBottom: "1px solid var(--km-border)",
    background: "rgba(255,255,255,0.04)"
  };
  const sectionTitleStyle = {
    marginTop: 10,
    marginBottom: 6,
    fontSize: 11,
    fontWeight: 700,
    color: "var(--km-muted)",
    letterSpacing: "0.04em",
    textTransform: "uppercase"
  };
  const listStyle = { display: "flex", flexDirection: "column", gap: 6 };
  const itemButtonStyle = {
    width: "100%",
    textAlign: "left",
    borderRadius: 10,
    border: "1px solid var(--km-border)",
    padding: "8px 10px",
    background: "transparent",
    color: "var(--km-text)",
    cursor: "pointer",
    fontSize: 12,
    lineHeight: "16px"
  };
  const mutedCodeStyle = {
    fontFamily: 'ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace',
    fontSize: 11,
    color: "var(--km-muted)",
    marginTop: 2
  };
  const linkTitleStyle = { fontWeight: 600, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" };
  const linkSubtitleStyle = { ...mutedCodeStyle, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" };
  const renderSection = (title, children) => /* @__PURE__ */ (0, import_jsx_runtime15.jsxs)("div", { children: [
    /* @__PURE__ */ (0, import_jsx_runtime15.jsx)("div", { style: sectionTitleStyle, children: title }),
    children
  ] });
  const renderIconPicker = (args) => {
    const border = "1px solid var(--km-border)";
    const buttonBase = {
      border,
      background: "transparent",
      borderRadius: 10,
      padding: "6px 10px",
      fontSize: 12,
      color: "var(--km-text)",
      cursor: "pointer"
    };
    return /* @__PURE__ */ (0, import_jsx_runtime15.jsxs)("div", { style: { border, borderRadius: 12, padding: 10, background: "rgba(255,255,255,0.02)" }, children: [
      /* @__PURE__ */ (0, import_jsx_runtime15.jsxs)("div", { style: { display: "flex", alignItems: "center", justifyContent: "space-between", gap: 8 }, children: [
        /* @__PURE__ */ (0, import_jsx_runtime15.jsx)("div", { style: { fontSize: 12, fontWeight: 700, color: "var(--km-text)" }, children: t("editor.links.iconPicker.title") }),
        /* @__PURE__ */ (0, import_jsx_runtime15.jsx)("button", { onClick: args.onClose, style: { ...buttonBase, padding: "4px 8px" }, type: "button", children: t("editor.links.iconPicker.action.close") })
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime15.jsxs)("div", { style: { display: "flex", flexWrap: "wrap", gap: 8, marginTop: 10 }, children: [
        /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(
          "button",
          {
            onClick: () => args.onChange(null),
            style: {
              ...buttonBase,
              padding: "6px 10px",
              opacity: args.value === null ? 1 : 0.85,
              background: args.value === null ? "rgba(59, 130, 246, 0.12)" : "transparent"
            },
            type: "button",
            children: t("editor.links.iconPicker.action.auto")
          }
        ),
        args.value ? /* @__PURE__ */ (0, import_jsx_runtime15.jsx)("button", { onClick: () => args.onChange(null), style: { ...buttonBase, padding: "6px 10px" }, type: "button", children: t("editor.links.iconPicker.action.clear") }) : null
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime15.jsx)("div", { className: "km-popover-scroll", style: { marginTop: 10, maxHeight: 220, overflow: "auto", paddingRight: 4 }, children: iconGroups.map((group) => /* @__PURE__ */ (0, import_jsx_runtime15.jsxs)("div", { style: { marginBottom: 10 }, children: [
        /* @__PURE__ */ (0, import_jsx_runtime15.jsx)("div", { style: { fontSize: 11, fontWeight: 700, color: "var(--km-muted)", marginBottom: 6 }, children: group.label }),
        /* @__PURE__ */ (0, import_jsx_runtime15.jsx)("div", { style: { display: "grid", gridTemplateColumns: "repeat(6, 1fr)", gap: 6 }, children: group.icons.map((icon) => {
          const selected = args.value === icon.id;
          return /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(
            "button",
            {
              onClick: () => args.onChange(icon.id),
              style: {
                border,
                background: selected ? "rgba(59, 130, 246, 0.12)" : "transparent",
                borderRadius: 10,
                height: 36,
                width: 36,
                display: "flex",
                alignItems: "center",
                justifyContent: "center",
                cursor: "pointer",
                color: "var(--km-text)"
              },
              title: icon.label,
              type: "button",
              children: /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(IconPreview, { iconId: icon.id })
            },
            icon.id
          );
        }) })
      ] }, group.id)) })
    ] });
  };
  if (!node) return null;
  return /* @__PURE__ */ (0, import_jsx_runtime15.jsxs)(
    "div",
    {
      "data-export-exclude": "true",
      "data-node-ref-resolve-version": nodeRefResolveVersion,
      className: "km-links-panel",
      ref: rootRef,
      onPointerEnter: () => props.onHoverChange(true),
      onPointerLeave: () => props.onHoverChange(false),
      style: cardStyle,
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime15.jsx)("style", { children: linksPanelCssText }),
        /* @__PURE__ */ (0, import_jsx_runtime15.jsxs)("div", { style: headerStyle, children: [
          /* @__PURE__ */ (0, import_jsx_runtime15.jsxs)("div", { style: { minWidth: 0 }, children: [
            /* @__PURE__ */ (0, import_jsx_runtime15.jsx)("div", { style: { fontSize: 12, fontWeight: 700, color: "var(--km-text)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }, children: t("editor.links.title") }),
            /* @__PURE__ */ (0, import_jsx_runtime15.jsx)("div", { style: { fontSize: 11, color: "var(--km-muted)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }, children: resolveNodeTitle(props.nodeId) })
          ] }),
          /* @__PURE__ */ (0, import_jsx_runtime15.jsxs)("div", { style: { display: "flex", alignItems: "center", gap: 8 }, children: [
            mode === "preview" && canEnterEdit && props.onRequestModeChange ? /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(
              "button",
              {
                onClick: () => props.onRequestModeChange?.("edit"),
                style: {
                  borderRadius: 10,
                  border: "1px solid var(--km-border)",
                  background: "transparent",
                  color: "var(--km-text)",
                  fontSize: 12,
                  padding: "6px 10px",
                  cursor: "pointer"
                },
                type: "button",
                children: t("editor.links.action.edit")
              }
            ) : null,
            mode === "edit" && props.onRequestModeChange ? /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(
              "button",
              {
                onClick: () => {
                  void commitPendingExternalLinkEdits().finally(() => props.onRequestModeChange?.("preview"));
                },
                style: {
                  borderRadius: 10,
                  border: "1px solid var(--km-border)",
                  background: "transparent",
                  color: "var(--km-text)",
                  fontSize: 12,
                  padding: "6px 10px",
                  cursor: "pointer"
                },
                type: "button",
                children: t("editor.links.action.done")
              }
            ) : null,
            currentDocId ? /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(
              "button",
              {
                onClick: () => void copyNodeLink(),
                style: {
                  borderRadius: 10,
                  border: "1px solid var(--km-border)",
                  background: "transparent",
                  color: "var(--km-text)",
                  fontSize: 12,
                  padding: "6px 10px",
                  cursor: "pointer"
                },
                title: `kmind-node://${currentDocId}/${props.nodeId}`,
                type: "button",
                children: copyState === "copied-link" ? t("editor.links.action.copied") : t("editor.links.action.copyLink")
              }
            ) : null,
            /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(
              "button",
              {
                onClick: () => void copyNodeId(),
                style: {
                  borderRadius: 10,
                  border: "1px solid var(--km-border)",
                  background: "transparent",
                  color: "var(--km-text)",
                  fontSize: 12,
                  padding: "6px 10px",
                  cursor: "pointer"
                },
                title: props.nodeId,
                type: "button",
                children: copyState === "copied-id" ? t("editor.links.action.copied") : t("editor.links.action.copyId")
              }
            ),
            /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(
              "button",
              {
                onClick: () => {
                  void closePanel();
                },
                style: {
                  borderRadius: 10,
                  border: "1px solid var(--km-border)",
                  background: "transparent",
                  color: "var(--km-text)",
                  fontSize: 12,
                  padding: "6px 10px",
                  cursor: "pointer"
                },
                type: "button",
                children: t("editor.links.action.close")
              }
            )
          ] })
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime15.jsxs)("div", { className: "km-popover-scroll", style: { padding: 12, overflow: "auto", flex: 1, minHeight: 0 }, children: [
          canEdit ? /* @__PURE__ */ (0, import_jsx_runtime15.jsx)("div", { style: { marginBottom: 12 }, children: renderSection(
            t("editor.links.section.add"),
            /* @__PURE__ */ (0, import_jsx_runtime15.jsxs)("div", { style: sectionBodyStyle, children: [
              /* @__PURE__ */ (0, import_jsx_runtime15.jsxs)("div", { style: { display: "flex", gap: 8, alignItems: "center" }, children: [
                /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(
                  "input",
                  {
                    onChange: (event) => setNewExternalUrl(event.target.value),
                    placeholder: t("editor.links.add.external.url.placeholder"),
                    style: {
                      flex: 1,
                      borderRadius: 10,
                      border: "1px solid var(--km-border)",
                      background: "transparent",
                      color: "var(--km-text)",
                      fontSize: 12,
                      padding: "6px 10px",
                      outline: "none"
                    },
                    value: newExternalUrl
                  }
                ),
                /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(
                  "button",
                  {
                    onClick: () => {
                      if (!newExternalUrl.trim()) return;
                      void dispatch("node.link.addExternal", {
                        nodeId: props.nodeId,
                        url: newExternalUrl.trim(),
                        label: newExternalLabel.trim() ? newExternalLabel.trim() : void 0,
                        iconId: newExternalIconId ?? void 0
                      }).then(() => {
                        setNewExternalUrl("");
                        setNewExternalLabel("");
                        setNewExternalIconId(null);
                        setIconPickerFor(null);
                      });
                    },
                    style: {
                      borderRadius: 10,
                      border: "1px solid var(--km-border)",
                      background: "transparent",
                      color: "var(--km-text)",
                      fontSize: 12,
                      padding: "6px 10px",
                      cursor: "pointer"
                    },
                    type: "button",
                    children: t("editor.links.add.external.action")
                  }
                )
              ] }),
              /* @__PURE__ */ (0, import_jsx_runtime15.jsxs)("div", { style: { display: "flex", gap: 8, alignItems: "center" }, children: [
                /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(
                  "input",
                  {
                    onChange: (event) => setNewExternalLabel(event.target.value),
                    placeholder: t("editor.links.add.external.label.placeholder"),
                    style: {
                      flex: 1,
                      borderRadius: 10,
                      border: "1px solid var(--km-border)",
                      background: "transparent",
                      color: "var(--km-text)",
                      fontSize: 12,
                      padding: "6px 10px",
                      outline: "none"
                    },
                    value: newExternalLabel
                  }
                ),
                /* @__PURE__ */ (0, import_jsx_runtime15.jsxs)(
                  "button",
                  {
                    onClick: () => setIconPickerFor((prev) => prev === "new-external" ? null : "new-external"),
                    style: {
                      borderRadius: 10,
                      border: "1px solid var(--km-border)",
                      background: "transparent",
                      color: "var(--km-text)",
                      fontSize: 12,
                      padding: "6px 10px",
                      cursor: "pointer",
                      display: "inline-flex",
                      alignItems: "center",
                      gap: 8
                    },
                    type: "button",
                    children: [
                      /* @__PURE__ */ (0, import_jsx_runtime15.jsx)("span", { children: t("editor.links.add.icon") }),
                      /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(IconPreview, { iconId: newExternalIconId ?? resolveExternalIconId2({ url: newExternalUrl, iconId: void 0 }, props.external) })
                    ]
                  }
                )
              ] }),
              iconPickerFor === "new-external" ? renderIconPicker({
                value: newExternalIconId,
                onChange: (next) => {
                  setNewExternalIconId(next ? normalizeBuiltinIconId(next) : null);
                  setIconPickerFor(null);
                },
                onClose: () => setIconPickerFor(null)
              }) : null,
              /* @__PURE__ */ (0, import_jsx_runtime15.jsxs)("div", { style: { display: "flex", gap: 8, alignItems: "center", marginTop: 8 }, children: [
                /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(
                  "input",
                  {
                    onChange: (event) => setNewInternalTarget(event.target.value),
                    placeholder: t("editor.links.add.internal.target.placeholder"),
                    style: {
                      flex: 1,
                      borderRadius: 10,
                      border: "1px solid var(--km-border)",
                      background: "transparent",
                      color: "var(--km-text)",
                      fontSize: 12,
                      padding: "6px 10px",
                      outline: "none"
                    },
                    value: newInternalTarget
                  }
                ),
                /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(
                  "button",
                  {
                    onClick: () => {
                      if (!newInternalTarget.trim()) return;
                      if (!canCreateBacklinks) {
                        notifyBlocked("backlinks");
                        return;
                      }
                      void dispatch("node.link.addInternal", {
                        nodeId: props.nodeId,
                        targetNodeId: newInternalTarget.trim(),
                        label: newInternalLabel.trim() ? newInternalLabel.trim() : void 0
                      }).then(() => {
                        setNewInternalTarget("");
                        setNewInternalLabel("");
                      });
                    },
                    style: {
                      borderRadius: 10,
                      border: "1px solid var(--km-border)",
                      background: "transparent",
                      color: "var(--km-text)",
                      fontSize: 12,
                      padding: "6px 10px",
                      cursor: "pointer"
                    },
                    type: "button",
                    children: t("editor.links.add.internal.action")
                  }
                )
              ] }),
              /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(
                "input",
                {
                  onChange: (event) => setNewInternalLabel(event.target.value),
                  placeholder: t("editor.links.add.internal.label.placeholder"),
                  style: {
                    width: "100%",
                    borderRadius: 10,
                    border: "1px solid var(--km-border)",
                    background: "transparent",
                    color: "var(--km-text)",
                    fontSize: 12,
                    padding: "6px 10px",
                    outline: "none"
                  },
                  value: newInternalLabel
                }
              )
            ] })
          ) }) : null,
          outgoingInternalItems.length > 0 ? renderSection(
            t("editor.links.section.outgoing", { count: outgoingInternalItems.length }),
            /* @__PURE__ */ (0, import_jsx_runtime15.jsxs)("div", { style: listStyle, children: [
              canEdit && brokenOutgoingInternal.length > 0 ? /* @__PURE__ */ (0, import_jsx_runtime15.jsx)("div", { style: { display: "flex", justifyContent: "flex-end" }, children: /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(
                "button",
                {
                  onClick: () => {
                    const linkIds = brokenOutgoingInternal.map((item) => item.link.id).filter((id) => typeof id === "string" && id.trim().length > 0);
                    if (linkIds.length === 0) return;
                    void dispatch("node.link.removeMany", { nodeId: props.nodeId, linkIds });
                  },
                  style: {
                    borderRadius: 10,
                    border: "1px solid var(--km-border)",
                    background: "transparent",
                    color: "var(--km-text)",
                    fontSize: 12,
                    padding: "4px 8px",
                    cursor: "pointer"
                  },
                  type: "button",
                  children: t("editor.links.action.cleanBroken")
                }
              ) }) : null,
              outgoingInternalItems.map((item) => {
                const ref = item.ref;
                const statusLabel = item.status === "broken" ? t("editor.links.status.broken") : item.status === "unknown" ? t("editor.links.status.unknown") : null;
                const canNavigate = item.status !== "broken";
                const isBroken = item.status === "broken";
                return /* @__PURE__ */ (0, import_jsx_runtime15.jsxs)(
                  "div",
                  {
                    style: { display: "flex", gap: 8, alignItems: "center", justifyContent: "space-between", ...itemButtonStyle, cursor: "default" },
                    children: [
                      /* @__PURE__ */ (0, import_jsx_runtime15.jsxs)(
                        "button",
                        {
                          onClick: () => {
                            if (!canNavigate) return;
                            void navigateToNodeRef(ref);
                          },
                          style: { all: "unset", cursor: canNavigate ? "pointer" : "not-allowed", flex: 1, minWidth: 0, opacity: canNavigate ? 1 : 0.65 },
                          type: "button",
                          children: [
                            /* @__PURE__ */ (0, import_jsx_runtime15.jsx)("div", { style: linkTitleStyle, children: resolveNodeRefTitle({ ...ref, label: item.link.label }) }),
                            /* @__PURE__ */ (0, import_jsx_runtime15.jsx)("div", { style: linkSubtitleStyle, children: resolveNodeRefSubtitle(ref) })
                          ]
                        }
                      ),
                      statusLabel ? /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(
                        "span",
                        {
                          style: {
                            fontSize: 11,
                            fontWeight: 700,
                            padding: "2px 8px",
                            borderRadius: 999,
                            border: "1px solid var(--km-border)",
                            color: isBroken ? "rgba(239, 68, 68, 0.9)" : "var(--km-muted)",
                            background: isBroken ? "rgba(239, 68, 68, 0.12)" : "rgba(148, 163, 184, 0.10)",
                            flex: "0 0 auto"
                          },
                          children: statusLabel
                        }
                      ) : null,
                      canEdit ? /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(
                        "button",
                        {
                          onClick: () => void dispatch("node.link.remove", { nodeId: props.nodeId, linkId: item.link.id }),
                          style: {
                            borderRadius: 10,
                            border: "1px solid var(--km-border)",
                            background: "transparent",
                            color: "var(--km-text)",
                            fontSize: 12,
                            padding: "4px 8px",
                            cursor: "pointer"
                          },
                          type: "button",
                          children: "\xD7"
                        }
                      ) : null
                    ]
                  },
                  `out:${item.link.id}`
                );
              })
            ] })
          ) : null,
          uniqueIncoming.length > 0 ? renderSection(
            t("editor.links.section.backlinks", { count: uniqueIncoming.length }),
            /* @__PURE__ */ (0, import_jsx_runtime15.jsx)("div", { style: listStyle, children: uniqueIncoming.map((ref) => /* @__PURE__ */ (0, import_jsx_runtime15.jsxs)(
              "button",
              {
                onClick: () => void navigateToNodeRef(ref),
                style: itemButtonStyle,
                type: "button",
                children: [
                  /* @__PURE__ */ (0, import_jsx_runtime15.jsx)("div", { style: linkTitleStyle, children: resolveNodeRefTitle(ref) }),
                  /* @__PURE__ */ (0, import_jsx_runtime15.jsx)("div", { style: linkSubtitleStyle, children: resolveNodeRefSubtitle(ref) })
                ]
              },
              `in:${makeNodeRefKey(ref)}`
            )) })
          ) : null,
          outgoingExternal.length > 0 ? renderSection(
            t("editor.links.section.external", { count: outgoingExternal.length }),
            /* @__PURE__ */ (0, import_jsx_runtime15.jsx)("div", { style: listStyle, children: outgoingExternal.map((link, index) => {
              const resolvedIconId = resolveExternalIconId2(link, props.external);
              const resolvedLabel = typeof link.label === "string" && link.label.trim().length > 0 ? link.label.trim() : link.url;
              const canOpenInHost = Boolean(props.external?.openUrlInHost) && Boolean(props.external?.resolveUrlBehavior?.(link.url)?.canOpenInHost);
              const canMoveUp = index > 0;
              const canMoveDown = index < outgoingExternal.length - 1;
              return /* @__PURE__ */ (0, import_jsx_runtime15.jsxs)(
                "div",
                {
                  style: { ...itemButtonStyle, cursor: "default", display: "flex", flexDirection: "column", gap: 8 },
                  children: [
                    /* @__PURE__ */ (0, import_jsx_runtime15.jsxs)("div", { style: { display: "flex", gap: 8, alignItems: "center", justifyContent: "space-between" }, children: [
                      /* @__PURE__ */ (0, import_jsx_runtime15.jsxs)("div", { style: { display: "flex", gap: 10, alignItems: "center", minWidth: 0 }, children: [
                        /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(
                          "span",
                          {
                            style: {
                              width: 24,
                              height: 24,
                              borderRadius: 10,
                              border: "1px solid var(--km-border)",
                              display: "flex",
                              alignItems: "center",
                              justifyContent: "center",
                              color: "var(--km-text)",
                              flex: "0 0 auto"
                            },
                            title: resolvedIconId.replace("kmind-icon://builtin/", ""),
                            children: /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(IconPreview, { iconId: resolvedIconId })
                          }
                        ),
                        /* @__PURE__ */ (0, import_jsx_runtime15.jsxs)("div", { style: { minWidth: 0 }, children: [
                          /* @__PURE__ */ (0, import_jsx_runtime15.jsx)("div", { style: { fontWeight: 600, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }, children: resolvedLabel }),
                          /* @__PURE__ */ (0, import_jsx_runtime15.jsx)("div", { style: { ...mutedCodeStyle, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }, children: link.url })
                        ] })
                      ] }),
                      /* @__PURE__ */ (0, import_jsx_runtime15.jsxs)("div", { style: { display: "flex", gap: 6, alignItems: "center", flex: "0 0 auto" }, children: [
                        /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(
                          "button",
                          {
                            onClick: () => {
                              if (!props.external) return;
                              if (canOpenInHost && props.external.openUrlInHost) {
                                void props.external.openUrlInHost({ url: link.url, position: "current" });
                              } else {
                                void props.external.openUrl(link.url);
                              }
                            },
                            style: {
                              borderRadius: 10,
                              border: "1px solid var(--km-border)",
                              background: "transparent",
                              color: "var(--km-text)",
                              fontSize: 12,
                              padding: "4px 8px",
                              cursor: props.external ? "pointer" : "not-allowed",
                              opacity: props.external ? 1 : 0.55
                            },
                            type: "button",
                            children: t("editor.links.external.action.open")
                          }
                        ),
                        canOpenInHost ? /* @__PURE__ */ (0, import_jsx_runtime15.jsxs)(import_jsx_runtime15.Fragment, { children: [
                          /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(
                            "button",
                            {
                              onClick: () => {
                                if (!props.external?.openUrlInHost) return;
                                void props.external.openUrlInHost({ url: link.url, position: "right" });
                              },
                              style: {
                                borderRadius: 10,
                                border: "1px solid var(--km-border)",
                                background: "transparent",
                                color: "var(--km-text)",
                                padding: 0,
                                width: 32,
                                height: 28,
                                display: "inline-flex",
                                alignItems: "center",
                                justifyContent: "center",
                                cursor: "pointer"
                              },
                              title: t("editor.links.external.action.openRight"),
                              type: "button",
                              children: /* @__PURE__ */ (0, import_jsx_runtime15.jsx)("span", { style: { width: 16, height: 16, display: "inline-flex" }, children: /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(IconPreview, { iconId: "kmind-icon://builtin/ui/open-right" }) })
                            }
                          ),
                          /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(
                            "button",
                            {
                              onClick: () => {
                                if (!props.external?.openUrlInHost) return;
                                void props.external.openUrlInHost({ url: link.url, position: "bottom" });
                              },
                              style: {
                                borderRadius: 10,
                                border: "1px solid var(--km-border)",
                                background: "transparent",
                                color: "var(--km-text)",
                                padding: 0,
                                width: 32,
                                height: 28,
                                display: "inline-flex",
                                alignItems: "center",
                                justifyContent: "center",
                                cursor: "pointer"
                              },
                              title: t("editor.links.external.action.openBottom"),
                              type: "button",
                              children: /* @__PURE__ */ (0, import_jsx_runtime15.jsx)("span", { style: { width: 16, height: 16, display: "inline-flex" }, children: /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(IconPreview, { iconId: "kmind-icon://builtin/ui/open-bottom" }) })
                            }
                          )
                        ] }) : null,
                        canEdit ? /* @__PURE__ */ (0, import_jsx_runtime15.jsxs)(import_jsx_runtime15.Fragment, { children: [
                          /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(
                            "button",
                            {
                              onClick: () => void dispatch("node.link.moveExternal", { nodeId: props.nodeId, linkId: link.id, direction: -1 }),
                              disabled: !canMoveUp,
                              style: {
                                borderRadius: 10,
                                border: "1px solid var(--km-border)",
                                background: "transparent",
                                color: "var(--km-text)",
                                fontSize: 12,
                                padding: "4px 8px",
                                cursor: canMoveUp ? "pointer" : "not-allowed",
                                opacity: canMoveUp ? 1 : 0.45
                              },
                              type: "button",
                              children: "\u2191"
                            }
                          ),
                          /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(
                            "button",
                            {
                              onClick: () => void dispatch("node.link.moveExternal", { nodeId: props.nodeId, linkId: link.id, direction: 1 }),
                              disabled: !canMoveDown,
                              style: {
                                borderRadius: 10,
                                border: "1px solid var(--km-border)",
                                background: "transparent",
                                color: "var(--km-text)",
                                fontSize: 12,
                                padding: "4px 8px",
                                cursor: canMoveDown ? "pointer" : "not-allowed",
                                opacity: canMoveDown ? 1 : 0.45
                              },
                              type: "button",
                              children: "\u2193"
                            }
                          ),
                          /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(
                            "button",
                            {
                              onClick: () => setIconPickerFor((prev) => prev === link.id ? null : link.id),
                              style: {
                                borderRadius: 10,
                                border: "1px solid var(--km-border)",
                                background: "transparent",
                                color: "var(--km-text)",
                                fontSize: 12,
                                padding: "4px 8px",
                                cursor: "pointer"
                              },
                              type: "button",
                              children: t("editor.links.add.icon")
                            }
                          ),
                          /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(
                            "button",
                            {
                              onClick: () => void dispatch("node.link.remove", { nodeId: props.nodeId, linkId: link.id }),
                              style: {
                                borderRadius: 10,
                                border: "1px solid var(--km-border)",
                                background: "transparent",
                                color: "var(--km-text)",
                                fontSize: 12,
                                padding: "4px 8px",
                                cursor: "pointer"
                              },
                              type: "button",
                              children: "\xD7"
                            }
                          )
                        ] }) : null
                      ] })
                    ] }),
                    canEdit ? /* @__PURE__ */ (0, import_jsx_runtime15.jsxs)(import_jsx_runtime15.Fragment, { children: [
                      /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(
                        "input",
                        {
                          "data-km-link-edit-field": "url",
                          "data-km-link-edit-id": link.id,
                          defaultValue: link.url,
                          onBlur: (event) => {
                            const nextUrl = event.target.value.trim();
                            if (!nextUrl || nextUrl === link.url) return;
                            void dispatch("node.link.updateExternal", { nodeId: props.nodeId, linkId: link.id, url: nextUrl });
                          },
                          placeholder: t("editor.links.external.edit.url.placeholder"),
                          style: {
                            width: "100%",
                            borderRadius: 10,
                            border: "1px solid var(--km-border)",
                            background: "transparent",
                            color: "var(--km-text)",
                            fontSize: 12,
                            padding: "6px 10px",
                            outline: "none"
                          }
                        },
                        `url:${link.id}:${link.url}`
                      ),
                      /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(
                        "input",
                        {
                          "data-km-link-edit-field": "label",
                          "data-km-link-edit-id": link.id,
                          defaultValue: link.label ?? "",
                          onBlur: (event) => {
                            const nextLabel = event.target.value;
                            const normalized = nextLabel.trim();
                            const current = link.label?.trim() ?? "";
                            if (normalized === current) return;
                            void dispatch("node.link.updateExternal", { nodeId: props.nodeId, linkId: link.id, label: normalized });
                          },
                          placeholder: t("editor.links.external.edit.label.placeholder"),
                          style: {
                            width: "100%",
                            borderRadius: 10,
                            border: "1px solid var(--km-border)",
                            background: "transparent",
                            color: "var(--km-text)",
                            fontSize: 12,
                            padding: "6px 10px",
                            outline: "none"
                          }
                        },
                        `label:${link.id}:${link.label ?? ""}`
                      ),
                      iconPickerFor === link.id ? renderIconPicker({
                        value: typeof link.iconId === "string" && link.iconId.trim().length > 0 ? normalizeBuiltinIconId(link.iconId.trim()) : null,
                        onChange: (next) => {
                          void dispatch("node.link.updateExternal", { nodeId: props.nodeId, linkId: link.id, iconId: next });
                          setIconPickerFor(null);
                        },
                        onClose: () => setIconPickerFor(null)
                      }) : null
                    ] }) : null
                  ]
                },
                `ext:${link.id}`
              );
            }) })
          ) : null,
          outgoingInternalItems.length === 0 && uniqueIncoming.length === 0 && outgoingExternal.length === 0 ? /* @__PURE__ */ (0, import_jsx_runtime15.jsx)("div", { style: { fontSize: 12, color: "var(--km-muted)" }, children: t("editor.links.empty") }) : null
        ] })
      ]
    }
  );
}

// ../react/src/mindmap-editor/overlays/node-meta-popover.tsx
var import_react20 = __toESM(require_react(), 1);
var import_react_dom4 = __toESM(require_react_dom(), 1);

// ../../node_modules/.pnpm/@tiptap+react@3.15.3_@floating-ui+dom@1.7.6_@tiptap+core@3.15.3_@tiptap+pm@3.15.3__@tip_af6d6602d31160262f55f8503ac5bcc6/node_modules/@tiptap/react/dist/index.js
var import_react8 = __toESM(require_react(), 1);
var import_react9 = __toESM(require_react(), 1);
var import_react_dom2 = __toESM(require_react_dom(), 1);
var import_shim = __toESM(require_shim(), 1);
var import_jsx_runtime16 = __toESM(require_jsx_runtime(), 1);
var import_react10 = __toESM(require_react(), 1);
var import_shim2 = __toESM(require_shim(), 1);

// ../../node_modules/.pnpm/fast-equals@5.4.0/node_modules/fast-equals/dist/es/index.mjs
var { getOwnPropertyNames, getOwnPropertySymbols } = Object;
var { hasOwnProperty } = Object.prototype;
function combineComparators(comparatorA, comparatorB) {
  return function isEqual(a2, b2, state) {
    return comparatorA(a2, b2, state) && comparatorB(a2, b2, state);
  };
}
function createIsCircular(areItemsEqual) {
  return function isCircular(a2, b2, state) {
    if (!a2 || !b2 || typeof a2 !== "object" || typeof b2 !== "object") {
      return areItemsEqual(a2, b2, state);
    }
    const { cache } = state;
    const cachedA = cache.get(a2);
    const cachedB = cache.get(b2);
    if (cachedA && cachedB) {
      return cachedA === b2 && cachedB === a2;
    }
    cache.set(a2, b2);
    cache.set(b2, a2);
    const result = areItemsEqual(a2, b2, state);
    cache.delete(a2);
    cache.delete(b2);
    return result;
  };
}
function getShortTag(value) {
  return value != null ? value[Symbol.toStringTag] : void 0;
}
function getStrictProperties(object) {
  return getOwnPropertyNames(object).concat(getOwnPropertySymbols(object));
}
var hasOwn = (
  // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
  Object.hasOwn || ((object, property) => hasOwnProperty.call(object, property))
);
function sameValueZeroEqual(a2, b2) {
  return a2 === b2 || !a2 && !b2 && a2 !== a2 && b2 !== b2;
}
var PREACT_VNODE = "__v";
var PREACT_OWNER = "__o";
var REACT_OWNER = "_owner";
var { getOwnPropertyDescriptor, keys: keys2 } = Object;
function areArrayBuffersEqual(a2, b2) {
  return a2.byteLength === b2.byteLength && areTypedArraysEqual(new Uint8Array(a2), new Uint8Array(b2));
}
function areArraysEqual(a2, b2, state) {
  let index = a2.length;
  if (b2.length !== index) {
    return false;
  }
  while (index-- > 0) {
    if (!state.equals(a2[index], b2[index], index, index, a2, b2, state)) {
      return false;
    }
  }
  return true;
}
function areDataViewsEqual(a2, b2) {
  return a2.byteLength === b2.byteLength && areTypedArraysEqual(new Uint8Array(a2.buffer, a2.byteOffset, a2.byteLength), new Uint8Array(b2.buffer, b2.byteOffset, b2.byteLength));
}
function areDatesEqual(a2, b2) {
  return sameValueZeroEqual(a2.getTime(), b2.getTime());
}
function areErrorsEqual(a2, b2) {
  return a2.name === b2.name && a2.message === b2.message && a2.cause === b2.cause && a2.stack === b2.stack;
}
function areFunctionsEqual(a2, b2) {
  return a2 === b2;
}
function areMapsEqual(a2, b2, state) {
  const size = a2.size;
  if (size !== b2.size) {
    return false;
  }
  if (!size) {
    return true;
  }
  const matchedIndices = new Array(size);
  const aIterable = a2.entries();
  let aResult;
  let bResult;
  let index = 0;
  while (aResult = aIterable.next()) {
    if (aResult.done) {
      break;
    }
    const bIterable = b2.entries();
    let hasMatch = false;
    let matchIndex = 0;
    while (bResult = bIterable.next()) {
      if (bResult.done) {
        break;
      }
      if (matchedIndices[matchIndex]) {
        matchIndex++;
        continue;
      }
      const aEntry = aResult.value;
      const bEntry = bResult.value;
      if (state.equals(aEntry[0], bEntry[0], index, matchIndex, a2, b2, state) && state.equals(aEntry[1], bEntry[1], aEntry[0], bEntry[0], a2, b2, state)) {
        hasMatch = matchedIndices[matchIndex] = true;
        break;
      }
      matchIndex++;
    }
    if (!hasMatch) {
      return false;
    }
    index++;
  }
  return true;
}
var areNumbersEqual = sameValueZeroEqual;
function areObjectsEqual(a2, b2, state) {
  const properties = keys2(a2);
  let index = properties.length;
  if (keys2(b2).length !== index) {
    return false;
  }
  while (index-- > 0) {
    if (!isPropertyEqual(a2, b2, state, properties[index])) {
      return false;
    }
  }
  return true;
}
function areObjectsEqualStrict(a2, b2, state) {
  const properties = getStrictProperties(a2);
  let index = properties.length;
  if (getStrictProperties(b2).length !== index) {
    return false;
  }
  let property;
  let descriptorA;
  let descriptorB;
  while (index-- > 0) {
    property = properties[index];
    if (!isPropertyEqual(a2, b2, state, property)) {
      return false;
    }
    descriptorA = getOwnPropertyDescriptor(a2, property);
    descriptorB = getOwnPropertyDescriptor(b2, property);
    if ((descriptorA || descriptorB) && (!descriptorA || !descriptorB || descriptorA.configurable !== descriptorB.configurable || descriptorA.enumerable !== descriptorB.enumerable || descriptorA.writable !== descriptorB.writable)) {
      return false;
    }
  }
  return true;
}
function arePrimitiveWrappersEqual(a2, b2) {
  return sameValueZeroEqual(a2.valueOf(), b2.valueOf());
}
function areRegExpsEqual(a2, b2) {
  return a2.source === b2.source && a2.flags === b2.flags;
}
function areSetsEqual(a2, b2, state) {
  const size = a2.size;
  if (size !== b2.size) {
    return false;
  }
  if (!size) {
    return true;
  }
  const matchedIndices = new Array(size);
  const aIterable = a2.values();
  let aResult;
  let bResult;
  while (aResult = aIterable.next()) {
    if (aResult.done) {
      break;
    }
    const bIterable = b2.values();
    let hasMatch = false;
    let matchIndex = 0;
    while (bResult = bIterable.next()) {
      if (bResult.done) {
        break;
      }
      if (!matchedIndices[matchIndex] && state.equals(aResult.value, bResult.value, aResult.value, bResult.value, a2, b2, state)) {
        hasMatch = matchedIndices[matchIndex] = true;
        break;
      }
      matchIndex++;
    }
    if (!hasMatch) {
      return false;
    }
  }
  return true;
}
function areTypedArraysEqual(a2, b2) {
  let index = a2.byteLength;
  if (b2.byteLength !== index || a2.byteOffset !== b2.byteOffset) {
    return false;
  }
  while (index-- > 0) {
    if (a2[index] !== b2[index]) {
      return false;
    }
  }
  return true;
}
function areUrlsEqual(a2, b2) {
  return a2.hostname === b2.hostname && a2.pathname === b2.pathname && a2.protocol === b2.protocol && a2.port === b2.port && a2.hash === b2.hash && a2.username === b2.username && a2.password === b2.password;
}
function isPropertyEqual(a2, b2, state, property) {
  if ((property === REACT_OWNER || property === PREACT_OWNER || property === PREACT_VNODE) && (a2.$$typeof || b2.$$typeof)) {
    return true;
  }
  return hasOwn(b2, property) && state.equals(a2[property], b2[property], property, property, a2, b2, state);
}
var ARRAY_BUFFER_TAG = "[object ArrayBuffer]";
var ARGUMENTS_TAG = "[object Arguments]";
var BOOLEAN_TAG = "[object Boolean]";
var DATA_VIEW_TAG = "[object DataView]";
var DATE_TAG = "[object Date]";
var ERROR_TAG = "[object Error]";
var MAP_TAG = "[object Map]";
var NUMBER_TAG = "[object Number]";
var OBJECT_TAG = "[object Object]";
var REG_EXP_TAG = "[object RegExp]";
var SET_TAG = "[object Set]";
var STRING_TAG = "[object String]";
var TYPED_ARRAY_TAGS = {
  "[object Int8Array]": true,
  "[object Uint8Array]": true,
  "[object Uint8ClampedArray]": true,
  "[object Int16Array]": true,
  "[object Uint16Array]": true,
  "[object Int32Array]": true,
  "[object Uint32Array]": true,
  "[object Float16Array]": true,
  "[object Float32Array]": true,
  "[object Float64Array]": true,
  "[object BigInt64Array]": true,
  "[object BigUint64Array]": true
};
var URL_TAG = "[object URL]";
var toString = Object.prototype.toString;
function createEqualityComparator({ areArrayBuffersEqual: areArrayBuffersEqual2, areArraysEqual: areArraysEqual2, areDataViewsEqual: areDataViewsEqual2, areDatesEqual: areDatesEqual2, areErrorsEqual: areErrorsEqual2, areFunctionsEqual: areFunctionsEqual2, areMapsEqual: areMapsEqual2, areNumbersEqual: areNumbersEqual2, areObjectsEqual: areObjectsEqual2, arePrimitiveWrappersEqual: arePrimitiveWrappersEqual2, areRegExpsEqual: areRegExpsEqual2, areSetsEqual: areSetsEqual2, areTypedArraysEqual: areTypedArraysEqual2, areUrlsEqual: areUrlsEqual2, unknownTagComparators }) {
  return function comparator(a2, b2, state) {
    if (a2 === b2) {
      return true;
    }
    if (a2 == null || b2 == null) {
      return false;
    }
    const type = typeof a2;
    if (type !== typeof b2) {
      return false;
    }
    if (type !== "object") {
      if (type === "number") {
        return areNumbersEqual2(a2, b2, state);
      }
      if (type === "function") {
        return areFunctionsEqual2(a2, b2, state);
      }
      return false;
    }
    const constructor = a2.constructor;
    if (constructor !== b2.constructor) {
      return false;
    }
    if (constructor === Object) {
      return areObjectsEqual2(a2, b2, state);
    }
    if (Array.isArray(a2)) {
      return areArraysEqual2(a2, b2, state);
    }
    if (constructor === Date) {
      return areDatesEqual2(a2, b2, state);
    }
    if (constructor === RegExp) {
      return areRegExpsEqual2(a2, b2, state);
    }
    if (constructor === Map) {
      return areMapsEqual2(a2, b2, state);
    }
    if (constructor === Set) {
      return areSetsEqual2(a2, b2, state);
    }
    const tag = toString.call(a2);
    if (tag === DATE_TAG) {
      return areDatesEqual2(a2, b2, state);
    }
    if (tag === REG_EXP_TAG) {
      return areRegExpsEqual2(a2, b2, state);
    }
    if (tag === MAP_TAG) {
      return areMapsEqual2(a2, b2, state);
    }
    if (tag === SET_TAG) {
      return areSetsEqual2(a2, b2, state);
    }
    if (tag === OBJECT_TAG) {
      return typeof a2.then !== "function" && typeof b2.then !== "function" && areObjectsEqual2(a2, b2, state);
    }
    if (tag === URL_TAG) {
      return areUrlsEqual2(a2, b2, state);
    }
    if (tag === ERROR_TAG) {
      return areErrorsEqual2(a2, b2, state);
    }
    if (tag === ARGUMENTS_TAG) {
      return areObjectsEqual2(a2, b2, state);
    }
    if (TYPED_ARRAY_TAGS[tag]) {
      return areTypedArraysEqual2(a2, b2, state);
    }
    if (tag === ARRAY_BUFFER_TAG) {
      return areArrayBuffersEqual2(a2, b2, state);
    }
    if (tag === DATA_VIEW_TAG) {
      return areDataViewsEqual2(a2, b2, state);
    }
    if (tag === BOOLEAN_TAG || tag === NUMBER_TAG || tag === STRING_TAG) {
      return arePrimitiveWrappersEqual2(a2, b2, state);
    }
    if (unknownTagComparators) {
      let unknownTagComparator = unknownTagComparators[tag];
      if (!unknownTagComparator) {
        const shortTag = getShortTag(a2);
        if (shortTag) {
          unknownTagComparator = unknownTagComparators[shortTag];
        }
      }
      if (unknownTagComparator) {
        return unknownTagComparator(a2, b2, state);
      }
    }
    return false;
  };
}
function createEqualityComparatorConfig({ circular, createCustomConfig, strict }) {
  let config = {
    areArrayBuffersEqual,
    areArraysEqual: strict ? areObjectsEqualStrict : areArraysEqual,
    areDataViewsEqual,
    areDatesEqual,
    areErrorsEqual,
    areFunctionsEqual,
    areMapsEqual: strict ? combineComparators(areMapsEqual, areObjectsEqualStrict) : areMapsEqual,
    areNumbersEqual,
    areObjectsEqual: strict ? areObjectsEqualStrict : areObjectsEqual,
    arePrimitiveWrappersEqual,
    areRegExpsEqual,
    areSetsEqual: strict ? combineComparators(areSetsEqual, areObjectsEqualStrict) : areSetsEqual,
    areTypedArraysEqual: strict ? combineComparators(areTypedArraysEqual, areObjectsEqualStrict) : areTypedArraysEqual,
    areUrlsEqual,
    unknownTagComparators: void 0
  };
  if (createCustomConfig) {
    config = Object.assign({}, config, createCustomConfig(config));
  }
  if (circular) {
    const areArraysEqual2 = createIsCircular(config.areArraysEqual);
    const areMapsEqual2 = createIsCircular(config.areMapsEqual);
    const areObjectsEqual2 = createIsCircular(config.areObjectsEqual);
    const areSetsEqual2 = createIsCircular(config.areSetsEqual);
    config = Object.assign({}, config, {
      areArraysEqual: areArraysEqual2,
      areMapsEqual: areMapsEqual2,
      areObjectsEqual: areObjectsEqual2,
      areSetsEqual: areSetsEqual2
    });
  }
  return config;
}
function createInternalEqualityComparator(compare) {
  return function(a2, b2, _indexOrKeyA, _indexOrKeyB, _parentA, _parentB, state) {
    return compare(a2, b2, state);
  };
}
function createIsEqual({ circular, comparator, createState, equals, strict }) {
  if (createState) {
    return function isEqual(a2, b2) {
      const { cache = circular ? /* @__PURE__ */ new WeakMap() : void 0, meta } = createState();
      return comparator(a2, b2, {
        cache,
        equals,
        meta,
        strict
      });
    };
  }
  if (circular) {
    return function isEqual(a2, b2) {
      return comparator(a2, b2, {
        cache: /* @__PURE__ */ new WeakMap(),
        equals,
        meta: void 0,
        strict
      });
    };
  }
  const state = {
    cache: void 0,
    equals,
    meta: void 0,
    strict
  };
  return function isEqual(a2, b2) {
    return comparator(a2, b2, state);
  };
}
var deepEqual = createCustomEqual();
var strictDeepEqual = createCustomEqual({ strict: true });
var circularDeepEqual = createCustomEqual({ circular: true });
var strictCircularDeepEqual = createCustomEqual({
  circular: true,
  strict: true
});
var shallowEqual = createCustomEqual({
  createInternalComparator: () => sameValueZeroEqual
});
var strictShallowEqual = createCustomEqual({
  strict: true,
  createInternalComparator: () => sameValueZeroEqual
});
var circularShallowEqual = createCustomEqual({
  circular: true,
  createInternalComparator: () => sameValueZeroEqual
});
var strictCircularShallowEqual = createCustomEqual({
  circular: true,
  createInternalComparator: () => sameValueZeroEqual,
  strict: true
});
function createCustomEqual(options = {}) {
  const { circular = false, createInternalComparator: createCustomInternalComparator, createState, strict = false } = options;
  const config = createEqualityComparatorConfig(options);
  const comparator = createEqualityComparator(config);
  const equals = createCustomInternalComparator ? createCustomInternalComparator(comparator) : createInternalEqualityComparator(comparator);
  return createIsEqual({ circular, comparator, createState, equals, strict });
}

// ../../node_modules/.pnpm/@tiptap+react@3.15.3_@floating-ui+dom@1.7.6_@tiptap+core@3.15.3_@tiptap+pm@3.15.3__@tip_af6d6602d31160262f55f8503ac5bcc6/node_modules/@tiptap/react/dist/index.js
var import_react11 = __toESM(require_react(), 1);
var import_with_selector = __toESM(require_with_selector(), 1);
var import_jsx_runtime17 = __toESM(require_jsx_runtime(), 1);
var import_react12 = __toESM(require_react(), 1);
var import_jsx_runtime18 = __toESM(require_jsx_runtime(), 1);
var import_react13 = __toESM(require_react(), 1);
var import_jsx_runtime19 = __toESM(require_jsx_runtime(), 1);
var import_react14 = __toESM(require_react(), 1);
var import_react15 = __toESM(require_react(), 1);
var import_react_dom3 = __toESM(require_react_dom(), 1);
var import_jsx_runtime20 = __toESM(require_jsx_runtime(), 1);
var import_jsx_runtime21 = __toESM(require_jsx_runtime(), 1);
var import_react16 = __toESM(require_react(), 1);
var import_jsx_runtime22 = __toESM(require_jsx_runtime(), 1);
var mergeRefs = (...refs) => {
  return (node) => {
    refs.forEach((ref) => {
      if (typeof ref === "function") {
        ref(node);
      } else if (ref) {
        ;
        ref.current = node;
      }
    });
  };
};
var Portals = ({ contentComponent }) => {
  const renderers = (0, import_shim.useSyncExternalStore)(
    contentComponent.subscribe,
    contentComponent.getSnapshot,
    contentComponent.getServerSnapshot
  );
  return /* @__PURE__ */ (0, import_jsx_runtime16.jsx)(import_jsx_runtime16.Fragment, { children: Object.values(renderers) });
};
function getInstance() {
  const subscribers = /* @__PURE__ */ new Set();
  let renderers = {};
  return {
    /**
     * Subscribe to the editor instance's changes.
     */
    subscribe(callback) {
      subscribers.add(callback);
      return () => {
        subscribers.delete(callback);
      };
    },
    getSnapshot() {
      return renderers;
    },
    getServerSnapshot() {
      return renderers;
    },
    /**
     * Adds a new NodeView Renderer to the editor.
     */
    setRenderer(id, renderer) {
      renderers = {
        ...renderers,
        [id]: import_react_dom2.default.createPortal(renderer.reactElement, renderer.element, id)
      };
      subscribers.forEach((subscriber) => subscriber());
    },
    /**
     * Removes a NodeView Renderer from the editor.
     */
    removeRenderer(id) {
      const nextRenderers = { ...renderers };
      delete nextRenderers[id];
      renderers = nextRenderers;
      subscribers.forEach((subscriber) => subscriber());
    }
  };
}
var PureEditorContent = class extends import_react9.default.Component {
  constructor(props) {
    var _a;
    super(props);
    this.editorContentRef = import_react9.default.createRef();
    this.initialized = false;
    this.state = {
      hasContentComponentInitialized: Boolean((_a = props.editor) == null ? void 0 : _a.contentComponent)
    };
  }
  componentDidMount() {
    this.init();
  }
  componentDidUpdate() {
    this.init();
  }
  init() {
    var _a;
    const editor = this.props.editor;
    if (editor && !editor.isDestroyed && ((_a = editor.view.dom) == null ? void 0 : _a.parentNode)) {
      if (editor.contentComponent) {
        return;
      }
      const element = this.editorContentRef.current;
      element.append(...editor.view.dom.parentNode.childNodes);
      editor.setOptions({
        element
      });
      editor.contentComponent = getInstance();
      if (!this.state.hasContentComponentInitialized) {
        this.unsubscribeToContentComponent = editor.contentComponent.subscribe(() => {
          this.setState((prevState) => {
            if (!prevState.hasContentComponentInitialized) {
              return {
                hasContentComponentInitialized: true
              };
            }
            return prevState;
          });
          if (this.unsubscribeToContentComponent) {
            this.unsubscribeToContentComponent();
          }
        });
      }
      editor.createNodeViews();
      this.initialized = true;
    }
  }
  componentWillUnmount() {
    var _a;
    const editor = this.props.editor;
    if (!editor) {
      return;
    }
    this.initialized = false;
    if (!editor.isDestroyed) {
      editor.view.setProps({
        nodeViews: {}
      });
    }
    if (this.unsubscribeToContentComponent) {
      this.unsubscribeToContentComponent();
    }
    editor.contentComponent = null;
    try {
      if (!((_a = editor.view.dom) == null ? void 0 : _a.parentNode)) {
        return;
      }
      const newElement = document.createElement("div");
      newElement.append(...editor.view.dom.parentNode.childNodes);
      editor.setOptions({
        element: newElement
      });
    } catch {
    }
  }
  render() {
    const { editor, innerRef, ...rest } = this.props;
    return /* @__PURE__ */ (0, import_jsx_runtime16.jsxs)(import_jsx_runtime16.Fragment, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime16.jsx)("div", { ref: mergeRefs(innerRef, this.editorContentRef), ...rest }),
      (editor == null ? void 0 : editor.contentComponent) && /* @__PURE__ */ (0, import_jsx_runtime16.jsx)(Portals, { contentComponent: editor.contentComponent })
    ] });
  }
};
var EditorContentWithKey = (0, import_react9.forwardRef)(
  (props, ref) => {
    const key = import_react9.default.useMemo(() => {
      return Math.floor(Math.random() * 4294967295).toString();
    }, [props.editor]);
    return import_react9.default.createElement(PureEditorContent, {
      key,
      innerRef: ref,
      ...props
    });
  }
);
var EditorContent = import_react9.default.memo(EditorContentWithKey);
var useIsomorphicLayoutEffect = typeof window !== "undefined" ? import_react11.useLayoutEffect : import_react11.useEffect;
var EditorStateManager = class {
  constructor(initialEditor) {
    this.transactionNumber = 0;
    this.lastTransactionNumber = 0;
    this.subscribers = /* @__PURE__ */ new Set();
    this.editor = initialEditor;
    this.lastSnapshot = { editor: initialEditor, transactionNumber: 0 };
    this.getSnapshot = this.getSnapshot.bind(this);
    this.getServerSnapshot = this.getServerSnapshot.bind(this);
    this.watch = this.watch.bind(this);
    this.subscribe = this.subscribe.bind(this);
  }
  /**
   * Get the current editor instance.
   */
  getSnapshot() {
    if (this.transactionNumber === this.lastTransactionNumber) {
      return this.lastSnapshot;
    }
    this.lastTransactionNumber = this.transactionNumber;
    this.lastSnapshot = { editor: this.editor, transactionNumber: this.transactionNumber };
    return this.lastSnapshot;
  }
  /**
   * Always disable the editor on the server-side.
   */
  getServerSnapshot() {
    return { editor: null, transactionNumber: 0 };
  }
  /**
   * Subscribe to the editor instance's changes.
   */
  subscribe(callback) {
    this.subscribers.add(callback);
    return () => {
      this.subscribers.delete(callback);
    };
  }
  /**
   * Watch the editor instance for changes.
   */
  watch(nextEditor) {
    this.editor = nextEditor;
    if (this.editor) {
      const fn = () => {
        this.transactionNumber += 1;
        this.subscribers.forEach((callback) => callback());
      };
      const currentEditor = this.editor;
      currentEditor.on("transaction", fn);
      return () => {
        currentEditor.off("transaction", fn);
      };
    }
    return void 0;
  }
};
function useEditorState(options) {
  var _a;
  const [editorStateManager] = (0, import_react11.useState)(() => new EditorStateManager(options.editor));
  const selectedState = (0, import_with_selector.useSyncExternalStoreWithSelector)(
    editorStateManager.subscribe,
    editorStateManager.getSnapshot,
    editorStateManager.getServerSnapshot,
    options.selector,
    (_a = options.equalityFn) != null ? _a : deepEqual
  );
  useIsomorphicLayoutEffect(() => {
    return editorStateManager.watch(options.editor);
  }, [options.editor, editorStateManager]);
  (0, import_react11.useDebugValue)(selectedState);
  return selectedState;
}
var isDev = true;
var isSSR = typeof window === "undefined";
var isNext = isSSR || Boolean(typeof window !== "undefined" && window.next);
var EditorInstanceManager = class _EditorInstanceManager {
  constructor(options) {
    this.editor = null;
    this.subscriptions = /* @__PURE__ */ new Set();
    this.isComponentMounted = false;
    this.previousDeps = null;
    this.instanceId = "";
    this.options = options;
    this.subscriptions = /* @__PURE__ */ new Set();
    this.setEditor(this.getInitialEditor());
    this.scheduleDestroy();
    this.getEditor = this.getEditor.bind(this);
    this.getServerSnapshot = this.getServerSnapshot.bind(this);
    this.subscribe = this.subscribe.bind(this);
    this.refreshEditorInstance = this.refreshEditorInstance.bind(this);
    this.scheduleDestroy = this.scheduleDestroy.bind(this);
    this.onRender = this.onRender.bind(this);
    this.createEditor = this.createEditor.bind(this);
  }
  setEditor(editor) {
    this.editor = editor;
    this.instanceId = Math.random().toString(36).slice(2, 9);
    this.subscriptions.forEach((cb) => cb());
  }
  getInitialEditor() {
    if (this.options.current.immediatelyRender === void 0) {
      if (isSSR || isNext) {
        if (isDev) {
          throw new Error(
            "Tiptap Error: SSR has been detected, please set `immediatelyRender` explicitly to `false` to avoid hydration mismatches."
          );
        }
        return null;
      }
      return this.createEditor();
    }
    if (this.options.current.immediatelyRender && isSSR && isDev) {
      throw new Error(
        "Tiptap Error: SSR has been detected, and `immediatelyRender` has been set to `true` this is an unsupported configuration that may result in errors, explicitly set `immediatelyRender` to `false` to avoid hydration mismatches."
      );
    }
    if (this.options.current.immediatelyRender) {
      return this.createEditor();
    }
    return null;
  }
  /**
   * Create a new editor instance. And attach event listeners.
   */
  createEditor() {
    const optionsToApply = {
      ...this.options.current,
      // Always call the most recent version of the callback function by default
      onBeforeCreate: (...args) => {
        var _a, _b;
        return (_b = (_a = this.options.current).onBeforeCreate) == null ? void 0 : _b.call(_a, ...args);
      },
      onBlur: (...args) => {
        var _a, _b;
        return (_b = (_a = this.options.current).onBlur) == null ? void 0 : _b.call(_a, ...args);
      },
      onCreate: (...args) => {
        var _a, _b;
        return (_b = (_a = this.options.current).onCreate) == null ? void 0 : _b.call(_a, ...args);
      },
      onDestroy: (...args) => {
        var _a, _b;
        return (_b = (_a = this.options.current).onDestroy) == null ? void 0 : _b.call(_a, ...args);
      },
      onFocus: (...args) => {
        var _a, _b;
        return (_b = (_a = this.options.current).onFocus) == null ? void 0 : _b.call(_a, ...args);
      },
      onSelectionUpdate: (...args) => {
        var _a, _b;
        return (_b = (_a = this.options.current).onSelectionUpdate) == null ? void 0 : _b.call(_a, ...args);
      },
      onTransaction: (...args) => {
        var _a, _b;
        return (_b = (_a = this.options.current).onTransaction) == null ? void 0 : _b.call(_a, ...args);
      },
      onUpdate: (...args) => {
        var _a, _b;
        return (_b = (_a = this.options.current).onUpdate) == null ? void 0 : _b.call(_a, ...args);
      },
      onContentError: (...args) => {
        var _a, _b;
        return (_b = (_a = this.options.current).onContentError) == null ? void 0 : _b.call(_a, ...args);
      },
      onDrop: (...args) => {
        var _a, _b;
        return (_b = (_a = this.options.current).onDrop) == null ? void 0 : _b.call(_a, ...args);
      },
      onPaste: (...args) => {
        var _a, _b;
        return (_b = (_a = this.options.current).onPaste) == null ? void 0 : _b.call(_a, ...args);
      },
      onDelete: (...args) => {
        var _a, _b;
        return (_b = (_a = this.options.current).onDelete) == null ? void 0 : _b.call(_a, ...args);
      }
    };
    const editor = new Editor(optionsToApply);
    return editor;
  }
  /**
   * Get the current editor instance.
   */
  getEditor() {
    return this.editor;
  }
  /**
   * Always disable the editor on the server-side.
   */
  getServerSnapshot() {
    return null;
  }
  /**
   * Subscribe to the editor instance's changes.
   */
  subscribe(onStoreChange) {
    this.subscriptions.add(onStoreChange);
    return () => {
      this.subscriptions.delete(onStoreChange);
    };
  }
  static compareOptions(a2, b2) {
    return Object.keys(a2).every((key) => {
      if ([
        "onCreate",
        "onBeforeCreate",
        "onDestroy",
        "onUpdate",
        "onTransaction",
        "onFocus",
        "onBlur",
        "onSelectionUpdate",
        "onContentError",
        "onDrop",
        "onPaste"
      ].includes(key)) {
        return true;
      }
      if (key === "extensions" && a2.extensions && b2.extensions) {
        if (a2.extensions.length !== b2.extensions.length) {
          return false;
        }
        return a2.extensions.every((extension, index) => {
          var _a;
          if (extension !== ((_a = b2.extensions) == null ? void 0 : _a[index])) {
            return false;
          }
          return true;
        });
      }
      if (a2[key] !== b2[key]) {
        return false;
      }
      return true;
    });
  }
  /**
   * On each render, we will create, update, or destroy the editor instance.
   * @param deps The dependencies to watch for changes
   * @returns A cleanup function
   */
  onRender(deps) {
    return () => {
      this.isComponentMounted = true;
      clearTimeout(this.scheduledDestructionTimeout);
      if (this.editor && !this.editor.isDestroyed && deps.length === 0) {
        if (!_EditorInstanceManager.compareOptions(this.options.current, this.editor.options)) {
          this.editor.setOptions({
            ...this.options.current,
            editable: this.editor.isEditable
          });
        }
      } else {
        this.refreshEditorInstance(deps);
      }
      return () => {
        this.isComponentMounted = false;
        this.scheduleDestroy();
      };
    };
  }
  /**
   * Recreate the editor instance if the dependencies have changed.
   */
  refreshEditorInstance(deps) {
    if (this.editor && !this.editor.isDestroyed) {
      if (this.previousDeps === null) {
        this.previousDeps = deps;
        return;
      }
      const depsAreEqual = this.previousDeps.length === deps.length && this.previousDeps.every((dep, index) => dep === deps[index]);
      if (depsAreEqual) {
        return;
      }
    }
    if (this.editor && !this.editor.isDestroyed) {
      this.editor.destroy();
    }
    this.setEditor(this.createEditor());
    this.previousDeps = deps;
  }
  /**
   * Schedule the destruction of the editor instance.
   * This will only destroy the editor if it was not mounted on the next tick.
   * This is to avoid destroying the editor instance when it's actually still mounted.
   */
  scheduleDestroy() {
    const currentInstanceId = this.instanceId;
    const currentEditor = this.editor;
    this.scheduledDestructionTimeout = setTimeout(() => {
      if (this.isComponentMounted && this.instanceId === currentInstanceId) {
        if (currentEditor) {
          currentEditor.setOptions(this.options.current);
        }
        return;
      }
      if (currentEditor && !currentEditor.isDestroyed) {
        currentEditor.destroy();
        if (this.instanceId === currentInstanceId) {
          this.setEditor(null);
        }
      }
    }, 1);
  }
};
function useEditor(options = {}, deps = []) {
  const mostRecentOptions = (0, import_react10.useRef)(options);
  mostRecentOptions.current = options;
  const [instanceManager] = (0, import_react10.useState)(() => new EditorInstanceManager(mostRecentOptions));
  const editor = (0, import_shim2.useSyncExternalStore)(
    instanceManager.subscribe,
    instanceManager.getEditor,
    instanceManager.getServerSnapshot
  );
  (0, import_react10.useDebugValue)(editor);
  (0, import_react10.useEffect)(instanceManager.onRender(deps));
  useEditorState({
    editor,
    selector: ({ transactionNumber }) => {
      if (options.shouldRerenderOnTransaction === false || options.shouldRerenderOnTransaction === void 0) {
        return null;
      }
      if (options.immediatelyRender && transactionNumber === 0) {
        return 0;
      }
      return transactionNumber + 1;
    }
  });
  return editor;
}
var EditorContext = (0, import_react8.createContext)({
  editor: null
});
var EditorConsumer = EditorContext.Consumer;
var ReactNodeViewContext = (0, import_react12.createContext)({
  onDragStart: () => {
  },
  nodeViewContentChildren: void 0,
  nodeViewContentRef: () => {
  }
});
var useReactNodeView = () => (0, import_react12.useContext)(ReactNodeViewContext);
var NodeViewWrapper = import_react13.default.forwardRef((props, ref) => {
  const { onDragStart } = useReactNodeView();
  const Tag = props.as || "div";
  return (
    // @ts-ignore
    /* @__PURE__ */ (0, import_jsx_runtime19.jsx)(
      Tag,
      {
        ...props,
        ref,
        "data-node-view-wrapper": "",
        onDragStart,
        style: {
          whiteSpace: "normal",
          ...props.style
        }
      }
    )
  );
});
var ReactMarkViewContext = import_react14.default.createContext({
  markViewContentRef: () => {
  }
});

// ../react/src/mindmap-editor/overlays/node-meta-popover.tsx
init_src();

// ../react/src/mobile-richtext-accessory.ts
var import_react17 = __toESM(require_react(), 1);
var ACTION_IDS = ["bold", "italic", "underline", "strike", "code", "codeBlock"];
var MOBILE_RICHTEXT_ACCESSORY_ATTR = "data-km-mobile-richtext-accessory";
var listeners = /* @__PURE__ */ new Set();
var consumerCount = 0;
var activeSession = null;
var cachedSnapshot = null;
function emitChange() {
  cachedSnapshot = null;
  for (const listener of listeners) listener();
}
function subscribe(listener) {
  listeners.add(listener);
  return () => {
    listeners.delete(listener);
  };
}
function noop2() {
}
function noopAction(_actionId) {
}
function isMobileRichTextAccessoryTarget(target2) {
  if (!(target2 instanceof Node)) return false;
  const element = target2 instanceof Element ? target2 : target2.parentElement;
  if (!element) return false;
  return Boolean(element.closest(`[${MOBILE_RICHTEXT_ACCESSORY_ATTR}]`));
}
function resolveActionActive(editor, actionId) {
  switch (actionId) {
    case "bold":
      return editor.isActive("bold");
    case "italic":
      return editor.isActive("italic");
    case "underline":
      return editor.isActive("underline");
    case "strike":
      return editor.isActive("strike");
    case "code":
      return editor.isActive("code");
    case "codeBlock":
      return editor.isActive("codeBlock");
    default:
      return false;
  }
}
function runEditorAction(editor, actionId) {
  const chain = editor.chain().focus();
  switch (actionId) {
    case "bold":
      chain.toggleBold().run();
      return;
    case "italic":
      chain.toggleItalic().run();
      return;
    case "underline":
      chain.toggleMark("underline").run();
      return;
    case "strike":
      chain.toggleStrike().run();
      return;
    case "code":
      chain.toggleCode().run();
      return;
    case "codeBlock":
      chain.toggleCodeBlock().run();
      return;
    default:
      return;
  }
}
function resolveSnapshot() {
  if (cachedSnapshot) return cachedSnapshot;
  const hasConsumer = consumerCount > 0;
  const session = activeSession;
  if (!session || session.editor.isDestroyed) {
    cachedSnapshot = {
      hasConsumer,
      active: false,
      context: null,
      actions: ACTION_IDS.map((id) => ({ id, active: false, disabled: true })),
      dismiss: noop2,
      runAction: noopAction
    };
    return cachedSnapshot;
  }
  cachedSnapshot = {
    hasConsumer,
    active: true,
    context: session.context,
    actions: ACTION_IDS.map((id) => ({
      id,
      active: resolveActionActive(session.editor, id),
      disabled: false
    })),
    dismiss: () => {
      if (activeSession?.id !== session.id) return;
      session.dismiss();
      emitChange();
    },
    runAction: (actionId) => {
      if (activeSession?.id !== session.id || session.editor.isDestroyed) return;
      runEditorAction(session.editor, actionId);
      emitChange();
    }
  };
  return cachedSnapshot;
}
function useMobileRichTextAccessoryBridge() {
  return (0, import_react17.useSyncExternalStore)(subscribe, resolveSnapshot, resolveSnapshot);
}
function bindMobileRichTextAccessorySession(session) {
  activeSession = session;
  emitChange();
  return () => {
    if (activeSession?.id !== session.id) return;
    activeSession = null;
    emitChange();
  };
}
function refreshMobileRichTextAccessory() {
  emitChange();
}

// ../react/src/mindmap-editor/utils/formula-target.ts
function resolveExpectedType(formulaView) {
  const kind = formulaView.getAttribute("data-km-formula-view");
  if (kind === "block") return "kmindFormulaBlock";
  if (kind === "inline") return "kmindFormula";
  return null;
}
function isFormulaType(type) {
  return type === "kmindFormula" || type === "kmindFormulaBlock";
}
function pushCandidate(candidates, value) {
  if (typeof value !== "number" || !Number.isFinite(value)) return;
  if (!candidates.includes(value)) candidates.push(value);
}
function resolveFormulaNodeAt(editor, basePos, expectedType) {
  const doc3 = editor.state.doc;
  const maxPos = doc3.content.size;
  const offsets = [0, -1, 1, -2, 2, -3, 3];
  for (const offset of offsets) {
    const pos = Math.max(0, Math.min(maxPos, basePos + offset));
    const node = doc3.nodeAt(pos);
    const type = node?.type.name ?? "";
    if (!isFormulaType(type)) continue;
    if (expectedType && type !== expectedType) continue;
    const latex = typeof node?.attrs?.latex === "string" ? node.attrs.latex : "";
    return { pos, type, latex };
  }
  return null;
}
function resolveKmindFormulaTargetFromView(editor, formulaView, pointer) {
  const expectedType = resolveExpectedType(formulaView);
  const candidates = [];
  try {
    pushCandidate(candidates, editor.view.posAtDOM(formulaView, 0));
  } catch {
  }
  try {
    pushCandidate(candidates, editor.view.posAtDOM(formulaView, formulaView.childNodes.length));
  } catch {
  }
  if (pointer) {
    try {
      const result = editor.view.posAtCoords({ left: pointer.clientX, top: pointer.clientY });
      pushCandidate(candidates, result?.pos);
    } catch {
    }
  }
  for (const candidate of candidates) {
    const resolved = resolveFormulaNodeAt(editor, candidate, expectedType);
    if (!resolved) continue;
    return {
      ...resolved,
      variant: resolved.type === "kmindFormulaBlock" ? "block" : "inline",
      rect: formulaView.getBoundingClientRect()
    };
  }
  return null;
}

// ../react/src/mindmap-editor/overlays/formula-popover.tsx
var import_react18 = __toESM(require_react(), 1);
var import_jsx_runtime23 = __toESM(require_jsx_runtime(), 1);
var defaultLabels = {
  title: "Formula\uFF08KaTeX + mhchem\uFF09",
  inline: "Inline",
  block: "Block",
  placeholder: "e.g. \\frac{a}{b}   or   \\ce{H2O + CO2 -> H2CO3}",
  preview: "Preview",
  shortcut: "Apply: Ctrl/Cmd+Enter",
  remove: "Remove",
  cancel: "Cancel",
  apply: "Apply"
};
var RichTextFormulaPopover = (0, import_react18.forwardRef)(function RichTextFormulaPopover2(props, ref) {
  const labels = { ...defaultLabels, ...props.labels ?? {} };
  const border = "1px solid var(--km-border, rgba(148, 163, 184, 0.38))";
  const panelStyle = {
    position: props.position ?? "absolute",
    left: props.x,
    top: props.y,
    transform: props.transform ?? "translate(-50%, 0)",
    width: props.width ?? 420,
    padding: 10,
    borderRadius: 12,
    border,
    background: "var(--km-panel, rgba(255, 255, 255, 0.98))",
    boxShadow: "0 18px 36px rgba(15, 23, 42, 0.18)",
    zIndex: props.zIndex ?? 90,
    pointerEvents: "auto",
    boxSizing: "border-box",
    color: "var(--km-text, #0f172a)",
    ...props.style
  };
  const resolveSegmentButtonStyle = (active) => ({
    border: active ? "1px solid rgba(59, 130, 246, 0.85)" : border,
    background: active ? "rgba(59, 130, 246, 0.18)" : "transparent",
    borderRadius: 10,
    padding: "4px 8px",
    fontSize: 12,
    color: "var(--km-text, #0f172a)",
    cursor: "pointer"
  });
  const actionButtonStyle = {
    border,
    background: "transparent",
    borderRadius: 10,
    padding: "6px 10px",
    fontSize: 12,
    color: "var(--km-text, #0f172a)",
    cursor: "pointer"
  };
  const applyButtonStyle = {
    ...actionButtonStyle,
    border: "1px solid rgba(59, 130, 246, 0.85)",
    background: "rgba(59, 130, 246, 0.18)"
  };
  const removeButtonStyle = {
    ...actionButtonStyle,
    border: "1px solid rgba(248, 113, 113, 0.55)",
    color: "rgba(248, 113, 113, 0.92)"
  };
  const handleTextareaKeyDown = (event) => {
    if (event.key === "Escape") {
      event.preventDefault();
      event.stopPropagation();
      props.onClose();
      return;
    }
    if (event.key === "Enter" && (event.metaKey || event.ctrlKey)) {
      event.preventDefault();
      event.stopPropagation();
      props.onApply();
    }
  };
  return /* @__PURE__ */ (0, import_jsx_runtime23.jsxs)(
    "div",
    {
      className: props.className,
      contentEditable: props.contentEditable,
      "data-km-meta-popover-toolbar": props.dataKmMetaPopoverToolbar ? "true" : void 0,
      ref,
      onMouseDown: props.onMouseDown,
      onPointerDownCapture: props.onPointerDownCapture,
      style: panelStyle,
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime23.jsx)("style", { children: katexRichTextCssText }),
        /* @__PURE__ */ (0, import_jsx_runtime23.jsxs)("div", { style: { display: "flex", alignItems: "center", justifyContent: "space-between", gap: 8, marginBottom: 8 }, children: [
          /* @__PURE__ */ (0, import_jsx_runtime23.jsx)("div", { style: { fontSize: 11, color: "var(--km-muted, #64748b)" }, children: labels.title }),
          /* @__PURE__ */ (0, import_jsx_runtime23.jsxs)("div", { style: { display: "flex", gap: 6, alignItems: "center" }, children: [
            /* @__PURE__ */ (0, import_jsx_runtime23.jsx)(
              "button",
              {
                onClick: () => props.onVariantChange("inline"),
                style: resolveSegmentButtonStyle(props.variant === "inline"),
                type: "button",
                children: labels.inline
              }
            ),
            /* @__PURE__ */ (0, import_jsx_runtime23.jsx)(
              "button",
              {
                onClick: () => props.onVariantChange("block"),
                style: resolveSegmentButtonStyle(props.variant === "block"),
                type: "button",
                children: labels.block
              }
            )
          ] })
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime23.jsx)(
          "textarea",
          {
            ref: props.inputRef,
            onChange: (event) => props.onLatexChange(event.target.value),
            onKeyDown: handleTextareaKeyDown,
            placeholder: labels.placeholder,
            style: {
              width: "100%",
              minHeight: 70,
              resize: "vertical",
              border,
              background: "transparent",
              color: "var(--km-text, #0f172a)",
              borderRadius: 10,
              padding: "8px 10px",
              outline: "none",
              fontFamily: 'ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace',
              fontSize: 12,
              lineHeight: "1.4",
              boxSizing: "border-box"
            },
            value: props.latex
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime23.jsxs)("div", { style: { marginTop: 10 }, children: [
          /* @__PURE__ */ (0, import_jsx_runtime23.jsx)("div", { style: { fontSize: 11, color: "var(--km-muted, #64748b)", marginBottom: 6 }, children: labels.preview }),
          /* @__PURE__ */ (0, import_jsx_runtime23.jsx)(
            "div",
            {
              className: "km-node-richtext",
              style: {
                border,
                borderRadius: 10,
                padding: "8px 10px",
                background: "rgba(255,255,255,0.03)",
                overflowX: "auto"
              },
              children: /* @__PURE__ */ (0, import_jsx_runtime23.jsx)(
                "span",
                {
                  dangerouslySetInnerHTML: {
                    __html: renderKmindFormulaToHtml({ latex: props.latex, displayMode: props.variant === "block" })
                  }
                }
              )
            }
          ),
          (() => {
            const result = props.latex.trim().length > 0 ? tryValidateKmindFormula(props.latex) : null;
            if (!result || result.ok) return null;
            return /* @__PURE__ */ (0, import_jsx_runtime23.jsx)("div", { style: { marginTop: 6, fontSize: 11, color: "rgba(248, 113, 113, 0.92)" }, children: result.error });
          })()
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime23.jsxs)("div", { style: { display: "flex", justifyContent: "space-between", alignItems: "center", gap: 8, marginTop: 10 }, children: [
          /* @__PURE__ */ (0, import_jsx_runtime23.jsx)("div", { style: { fontSize: 11, color: "var(--km-muted, #64748b)" }, children: labels.shortcut }),
          /* @__PURE__ */ (0, import_jsx_runtime23.jsxs)("div", { style: { display: "flex", gap: 8 }, children: [
            props.mode === "edit" ? /* @__PURE__ */ (0, import_jsx_runtime23.jsx)("button", { onClick: props.onRemove, style: removeButtonStyle, type: "button", children: labels.remove }) : null,
            /* @__PURE__ */ (0, import_jsx_runtime23.jsx)("button", { onClick: props.onClose, style: actionButtonStyle, type: "button", children: labels.cancel }),
            /* @__PURE__ */ (0, import_jsx_runtime23.jsx)("button", { onClick: props.onApply, style: applyButtonStyle, type: "button", children: labels.apply })
          ] })
        ] })
      ]
    }
  );
});

// ../react/src/workspace-presentation.ts
var import_react19 = __toESM(require_react(), 1);
function resolveWindow(ownerWindow) {
  if (ownerWindow) return ownerWindow;
  return typeof window !== "undefined" ? window : null;
}
function resolveKeyboardInset(win) {
  const visualViewport = win.visualViewport;
  if (!visualViewport) return 0;
  const layoutViewportHeight = Math.round(win.innerHeight);
  const visualViewportHeight = Math.round(visualViewport.height);
  const visualViewportOffsetTop = Math.round(visualViewport.offsetTop);
  return Math.max(0, layoutViewportHeight - visualViewportHeight - visualViewportOffsetTop);
}
function resolveWorkspacePresentationSnapshot(options) {
  const compactMaxWidth = options?.compactMaxWidth ?? 900;
  const compactCoarseMaxWidth = options?.compactCoarseMaxWidth ?? 1180;
  const win = resolveWindow(options?.ownerWindow);
  if (!win) {
    return {
      viewportWidth: compactCoarseMaxWidth + 1,
      viewportHeight: 0,
      layoutViewportHeight: 0,
      coarsePointer: false,
      isCompact: false,
      keyboardInset: 0,
      keyboardOpen: false
    };
  }
  const viewportWidth = Math.round(win.visualViewport?.width ?? win.innerWidth);
  const viewportHeight = Math.round(win.visualViewport?.height ?? win.innerHeight);
  const layoutViewportHeight = Math.round(win.innerHeight);
  const coarsePointer = Boolean(win.matchMedia?.("(pointer: coarse)").matches) || (win.navigator?.maxTouchPoints ?? 0) > 0;
  const isCompact = viewportWidth <= compactMaxWidth || coarsePointer && viewportWidth <= compactCoarseMaxWidth;
  const keyboardInset = resolveKeyboardInset(win);
  const keyboardOpenThreshold = Math.max(120, Math.round(layoutViewportHeight * 0.18));
  const keyboardOpen = coarsePointer && keyboardInset >= keyboardOpenThreshold;
  return {
    viewportWidth,
    viewportHeight,
    layoutViewportHeight,
    coarsePointer,
    isCompact,
    keyboardInset,
    keyboardOpen
  };
}
function useWorkspacePresentation(options) {
  const ownerWindow = options?.ownerWindow;
  const compactMaxWidth = options?.compactMaxWidth;
  const compactCoarseMaxWidth = options?.compactCoarseMaxWidth;
  const [snapshot, setSnapshot] = (0, import_react19.useState)(() => resolveWorkspacePresentationSnapshot(options));
  (0, import_react19.useEffect)(() => {
    const win = resolveWindow(ownerWindow);
    if (!win) return;
    const update = () => {
      setSnapshot(
        resolveWorkspacePresentationSnapshot({
          ownerWindow: win,
          compactMaxWidth,
          compactCoarseMaxWidth
        })
      );
    };
    update();
    const coarseMedia = win.matchMedia?.("(pointer: coarse)") ?? null;
    const visualViewport = win.visualViewport ?? null;
    win.addEventListener("resize", update);
    visualViewport?.addEventListener("resize", update);
    visualViewport?.addEventListener("scroll", update);
    coarseMedia?.addEventListener?.("change", update);
    coarseMedia?.addListener?.(update);
    return () => {
      win.removeEventListener("resize", update);
      visualViewport?.removeEventListener("resize", update);
      visualViewport?.removeEventListener("scroll", update);
      coarseMedia?.removeEventListener?.("change", update);
      coarseMedia?.removeListener?.(update);
    };
  }, [compactCoarseMaxWidth, compactMaxWidth, ownerWindow]);
  return snapshot;
}

// ../react/src/mindmap-editor/overlays/node-meta-popover.tsx
var import_jsx_runtime24 = __toESM(require_jsx_runtime(), 1);
var nodeMetaPopoverCssText = `
  .km-meta-popover .km-node-richtext,
  .km-meta-popover .km-node-richtext * {
    box-sizing: border-box;
  }
  .km-meta-popover .km-popover-scroll {
    scrollbar-width: thin;
    scrollbar-color: rgba(148, 163, 184, 0.58) transparent;
  }
  .km-meta-popover .km-popover-scroll::-webkit-scrollbar {
    width: 12px;
    height: 12px;
  }
  .km-meta-popover .km-popover-scroll::-webkit-scrollbar-track {
    background: transparent;
  }
  .km-meta-popover .km-popover-scroll::-webkit-scrollbar-thumb {
    background-color: rgba(148, 163, 184, 0.5);
    border-radius: 999px;
    border: 3px solid transparent;
    background-clip: content-box;
  }
  .km-meta-popover .km-popover-scroll:hover::-webkit-scrollbar-thumb {
    background-color: rgba(148, 163, 184, 0.72);
  }
  .km-meta-popover .km-node-richtext {
    overflow-wrap: anywhere;
    word-break: break-word;
  }
  .km-meta-popover .km-node-richtext p {
    margin: 0;
  }
  .km-meta-popover .km-node-richtext img {
    display: inline-block;
    max-width: 100%;
    height: auto;
    border-radius: 10px;
    vertical-align: middle;
  }
  .km-meta-popover .km-node-richtext pre {
    margin: 0;
    padding: 8px 10px;
    border-radius: 8px;
    background: var(--km-code-bg, rgba(15, 23, 42, 0.06));
    box-shadow: inset 0 0 0 1px var(--km-code-border, rgba(148, 163, 184, 0.35));
    overflow: hidden;
    white-space: pre-wrap;
    word-break: break-word;
    font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;
    font-size: 13px;
    line-height: 1.4;
  }
  .km-meta-popover .km-node-richtext code {
    font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;
  }
  .km-meta-popover .km-node-richtext .km-formula-block {
    display: flex;
    justify-content: center;
    align-items: center;
    margin: 6px 0;
    max-width: 100%;
    overflow: visible;
  }
  ${katexRichTextCssText}
  .km-meta-popover .km-node-richtext .km-code-token--keyword {
    color: var(--km-code-token-keyword, rgba(124, 58, 237, 0.95));
  }
  .km-meta-popover .km-node-richtext .km-code-token--string {
    color: var(--km-code-token-string, rgba(2, 132, 199, 0.95));
  }
  .km-meta-popover .km-node-richtext .km-code-token--number {
    color: var(--km-code-token-number, rgba(234, 88, 12, 0.95));
  }
  .km-meta-popover .km-node-richtext .km-code-token--comment {
    color: var(--km-code-token-comment, rgba(100, 116, 139, 0.85));
  }
  .km-meta-popover .km-node-richtext .km-code-token--property {
    color: var(--km-code-token-property, rgba(29, 78, 216, 0.95));
  }
  .km-meta-popover .km-node-richtext .km-code-token--punct {
    color: var(--km-code-token-punct, rgba(51, 65, 85, 0.88));
  }
  .km-meta-popover .km-node-richtext a {
    color: inherit;
    text-decoration: underline;
  }
  .km-meta-popover .km-tiptap-editor {
    outline: none;
    white-space: pre-wrap;
    word-break: break-word;
  }
`;
var CLOZE_ADVANCED_UI_ENABLED = false;
function countPremiumNodes(value) {
  let formula = 0;
  let cloze = 0;
  const visit = (node) => {
    if (!node || typeof node !== "object") return;
    const record = node;
    const type = typeof record.type === "string" ? record.type : "";
    if (type === "kmindFormula" || type === "kmindFormulaBlock") formula += 1;
    if (type === "kmindCloze") cloze += 1;
    if (Array.isArray(record.content)) {
      for (const child of record.content) visit(child);
    }
  };
  visit(value);
  return { formula, cloze };
}
function NodeMetaPopover(props) {
  const t = useT();
  const node = props.doc.nodes[props.nodeId];
  const readOnly = Boolean(props.readOnly);
  const mode = readOnly ? "preview" : props.mode;
  const variant = props.variant ?? "floating";
  const rootRef = (0, import_react20.useRef)(null);
  const effectivePremium = props.premiumCapabilities ?? {
    canCreateBacklinks: true,
    canInsertFormula: true,
    canInsertCloze: true,
    canCreateComments: true,
    canInsertSiyuanDocLink: true
  };
  (0, import_react20.useEffect)(() => {
    const win = resolveOwnerWindow(rootRef.current) ?? (typeof window !== "undefined" ? window : null);
    if (!win) return;
    const onPointerDown = (event) => {
      const target2 = event.target;
      if (!isNodeLike(target2)) return;
      if (isElementLike(target2)) {
        const metaIcon = target2.closest('[data-km-action="notes.open"],[data-km-action="comments.open"]');
        if (metaIcon) {
          if (mode === "edit") {
            try {
              props.commitRef.current?.();
            } catch {
            }
          }
          return;
        }
      }
      const root = rootRef.current;
      if (root && root.contains(target2)) return;
      if (isElementLike(target2) && target2.closest("[data-km-meta-popover-toolbar]")) return;
      if (isMobileRichTextAccessoryTarget(target2)) return;
      if (mode === "edit") {
        try {
          props.commitRef.current?.();
        } catch {
        }
      }
      props.onRequestClose();
    };
    win.addEventListener("pointerdown", onPointerDown, true);
    return () => win.removeEventListener("pointerdown", onPointerDown, true);
  }, [mode, props.commitRef, props.onRequestClose]);
  if (!node) return null;
  const cardStyle = variant === "embedded" ? {
    position: "relative",
    left: 0,
    top: 0,
    width: "100%",
    maxHeight: "none",
    overflow: "hidden",
    borderRadius: 0,
    border: "none",
    background: "transparent",
    boxShadow: "none",
    pointerEvents: "auto",
    display: "flex",
    flexDirection: "column",
    minHeight: 0
  } : {
    position: "absolute",
    left: props.x,
    top: props.y,
    width: props.width,
    maxHeight: props.maxHeight,
    overflow: "hidden",
    borderRadius: 14,
    border: "1px solid var(--km-border)",
    background: "var(--km-panel)",
    boxShadow: "0 18px 36px rgba(15, 23, 42, 0.18)",
    pointerEvents: "auto",
    zIndex: 70,
    display: "flex",
    flexDirection: "column",
    minHeight: 0
  };
  const headerStyle = {
    display: "flex",
    alignItems: "center",
    justifyContent: "space-between",
    gap: 10,
    padding: "10px 12px",
    borderBottom: "1px solid var(--km-border)",
    background: "rgba(255,255,255,0.04)"
  };
  const buttonStyle2 = {
    border: "1px solid var(--km-border)",
    background: "transparent",
    borderRadius: 10,
    padding: "6px 10px",
    fontSize: 12,
    color: "var(--km-text)",
    cursor: "pointer"
  };
  const canEnterEdit = Boolean(!readOnly && !node.attrs?.locked && !node.attrs?.readonly);
  const title = props.kind === "notes" ? t("editor.meta.title.notes") : t("editor.meta.title.comments");
  const contentMaxHeight = props.maxHeight > 0 ? Math.max(72, props.maxHeight - 56) : void 0;
  return /* @__PURE__ */ (0, import_jsx_runtime24.jsxs)(
    "div",
    {
      className: "km-meta-popover",
      ref: rootRef,
      onPointerEnter: () => props.onHoverChange(true),
      onPointerLeave: () => props.onHoverChange(false),
      style: cardStyle,
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime24.jsx)("style", { children: nodeMetaPopoverCssText }),
        /* @__PURE__ */ (0, import_jsx_runtime24.jsxs)("div", { style: headerStyle, children: [
          /* @__PURE__ */ (0, import_jsx_runtime24.jsx)("div", { style: { fontSize: 12, fontWeight: 650, color: "var(--km-text)" }, children: title }),
          /* @__PURE__ */ (0, import_jsx_runtime24.jsxs)("div", { style: { display: "flex", gap: 8, alignItems: "center" }, children: [
            mode === "preview" && canEnterEdit ? /* @__PURE__ */ (0, import_jsx_runtime24.jsx)("button", { onClick: () => props.onRequestModeChange("edit"), style: buttonStyle2, type: "button", children: t("editor.meta.action.edit") }) : null,
            /* @__PURE__ */ (0, import_jsx_runtime24.jsx)("button", { onClick: props.onRequestClose, style: buttonStyle2, type: "button", children: t("editor.meta.action.close") })
          ] })
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime24.jsx)(
          "div",
          {
            className: "km-popover-scroll",
            style: {
              padding: 12,
              overflow: "auto",
              flex: 1,
              minHeight: 0,
              maxHeight: contentMaxHeight,
              scrollbarGutter: "stable"
            },
            children: props.kind === "notes" ? /* @__PURE__ */ (0, import_jsx_runtime24.jsx)(
              NodeNotesPopoverContent,
              {
                assetObjectUrlById: props.assetObjectUrlById,
                commitRef: props.commitRef,
                core: props.core,
                dialog: props.dialog,
                doc: props.doc,
                mode,
                node,
                nodeId: props.nodeId,
                onAction: props.onAction,
                onRequestModeChange: props.onRequestModeChange,
                premiumCapabilities: effectivePremium,
                onPremiumFeatureBlocked: props.onPremiumFeatureBlocked
              }
            ) : /* @__PURE__ */ (0, import_jsx_runtime24.jsx)(
              NodeCommentsPopoverContent,
              {
                commitRef: props.commitRef,
                core: props.core,
                mode,
                node,
                nodeId: props.nodeId,
                onAction: props.onAction,
                premiumCapabilities: effectivePremium,
                onPremiumFeatureBlocked: props.onPremiumFeatureBlocked
              }
            )
          }
        )
      ]
    }
  );
}
function createLocalId(prefix) {
  return createKmindId(prefix);
}
function ensureBlocksContentForMeta(node) {
  if (node.content?.schemaVersion === 1 && node.content.kind === "blocks") {
    return { content: node.content, plainText: node.text };
  }
  const blocks = [];
  if (node.content?.schemaVersion === 1 && node.content.kind === "richtext" && node.content.engine === "prosemirror") {
    blocks.push({
      id: createLocalId("rt"),
      type: "richtext",
      region: "main",
      order: 0,
      engine: "prosemirror",
      doc: node.content.doc,
      html: node.content.html
    });
  } else {
    const docJson = fromKmind({ content: node.content, fallbackText: node.text });
    blocks.push({
      id: createLocalId("rt"),
      type: "richtext",
      region: "main",
      order: 0,
      engine: "prosemirror",
      doc: docJson,
      html: void 0
    });
  }
  return { content: { schemaVersion: 1, kind: "blocks", blocks }, plainText: node.text };
}
function resolveNodeComments(node) {
  const content = node.content;
  if (content?.schemaVersion === 1 && content.kind === "blocks") {
    const block = content.blocks.find((b2) => b2.type === "comments");
    if (block) return block.items;
  }
  return [];
}
function NodeNotesPopoverContent(props) {
  const t = useT();
  const notesBlock = props.node.content?.schemaVersion === 1 && props.node.content.kind === "blocks" ? props.node.content.blocks.find((b2) => b2.type === "notes") ?? null : null;
  const resolvePreview = () => {
    if (!notesBlock) return { html: null, text: null };
    const candidate = notesBlock;
    if (typeof candidate.html === "string" && candidate.html.trim().length > 0) return { html: candidate.html, text: null };
    if (candidate.engine === "prosemirror" && candidate.doc && typeof candidate.doc === "object" && !Array.isArray(candidate.doc)) {
      return { html: renderHtml(candidate.doc), text: null };
    }
    if (typeof candidate.text === "string" && candidate.text.trim().length > 0) return { html: null, text: candidate.text };
    return { html: null, text: null };
  };
  const preview = resolvePreview();
  const previewHtml = (0, import_react20.useMemo)(() => {
    if (!preview.html) return null;
    const withAssets = resolveAssetBackedHtml({
      html: preview.html,
      doc: props.doc,
      assetObjectUrlById: props.assetObjectUrlById ?? null
    });
    return applyFormulaRenderingToHtml(applyCodeHighlightingToHtml(withAssets));
  }, [preview.html, props.assetObjectUrlById, props.doc]);
  if (props.mode !== "edit") {
    if (previewHtml) {
      return /* @__PURE__ */ (0, import_jsx_runtime24.jsx)("div", { className: "km-node-richtext", dangerouslySetInnerHTML: { __html: previewHtml } });
    }
    if (preview.text) {
      return /* @__PURE__ */ (0, import_jsx_runtime24.jsx)("div", { style: { fontSize: 12, lineHeight: "1.45", color: "var(--km-text)", whiteSpace: "pre-wrap", overflowWrap: "anywhere" }, children: preview.text });
    }
    return /* @__PURE__ */ (0, import_jsx_runtime24.jsx)("div", { style: { fontSize: 12, color: "var(--km-muted)" }, children: t("editor.meta.notes.empty") });
  }
  return /* @__PURE__ */ (0, import_jsx_runtime24.jsx)(
    NodeNotesEditor,
    {
      commitRef: props.commitRef,
      core: props.core,
      dialog: props.dialog,
      node: props.node,
      nodeId: props.nodeId,
      notesBlock,
      onAction: props.onAction,
      onRequestModeChange: props.onRequestModeChange,
      premiumCapabilities: props.premiumCapabilities,
      onPremiumFeatureBlocked: props.onPremiumFeatureBlocked
    }
  );
}
function NodeNotesEditor(props) {
  const t = useT();
  const overlayPortalContainer = useOverlayPortalContainer();
  const overlayPortalTarget = resolveOverlayPortalTarget(overlayPortalContainer);
  const scopedOverlayPortal = hasScopedOverlayPortal(overlayPortalContainer);
  const presentation = useWorkspacePresentation();
  const mobileRichTextAccessory = useMobileRichTextAccessoryBridge();
  const initialContent = (0, import_react20.useMemo)(() => {
    const block = props.notesBlock;
    if (!block) return createDocFromText("");
    const candidate = block;
    if (candidate.engine === "prosemirror" && candidate.doc && typeof candidate.doc === "object" && !Array.isArray(candidate.doc)) {
      return createEditableDocFromHtmlBackedContent2({
        doc: candidate.doc,
        html: typeof candidate.html === "string" ? candidate.html : void 0,
        fallbackText: typeof candidate.text === "string" ? candidate.text : ""
      });
    }
    if (typeof candidate.text === "string") return createDocFromText(candidate.text);
    return createDocFromText("");
  }, [props.nodeId, props.notesBlock]);
  const effectivePremium = props.premiumCapabilities ?? {
    canCreateBacklinks: true,
    canInsertFormula: true,
    canInsertCloze: true,
    canCreateComments: true,
    canInsertSiyuanDocLink: true
  };
  const notifyBlocked = (feature) => {
    props.onPremiumFeatureBlocked?.(feature);
  };
  const editor = useEditor(
    {
      immediatelyRender: false,
      extensions: createKmindTiptapExtensions(),
      content: initialContent,
      autofocus: "end",
      editorProps: {
        transformPastedHTML: (html) => sanitizeExternalHtml(html),
        attributes: {
          class: "km-node-richtext km-tiptap-editor",
          style: ["min-height:120px", "font-size:12px", "line-height:1.45"].join(";")
        }
      }
    },
    [initialContent]
  );
  const didAutofocusRef = (0, import_react20.useRef)(false);
  (0, import_react20.useLayoutEffect)(() => {
    if (!editor) return;
    if (didAutofocusRef.current) return;
    didAutofocusRef.current = true;
    const raf = typeof requestAnimationFrame === "function" ? requestAnimationFrame : (fn) => window.setTimeout(fn, 0);
    const cancel = typeof cancelAnimationFrame === "function" ? cancelAnimationFrame : (id2) => window.clearTimeout(id2);
    const id = raf(() => {
      try {
        editor.commands.focus("end");
      } catch {
      }
    });
    return () => cancel(id);
  }, [editor]);
  const toolbarRef = (0, import_react20.useRef)(null);
  const editorFrameRef = (0, import_react20.useRef)(null);
  const lastToolbarPointerDownAtRef = (0, import_react20.useRef)(0);
  const lastSelectionRef = (0, import_react20.useRef)(null);
  const toolbarMetricsRef = (0, import_react20.useRef)({ width: 360, height: 104 });
  const updateToolbarRef = (0, import_react20.useRef)(null);
  const [toolbarThemeVars, setToolbarThemeVars] = (0, import_react20.useState)(null);
  const [toolbar, setToolbar] = (0, import_react20.useState)({
    visible: false,
    x: 0,
    y: 0,
    placement: "above"
  });
  const [lastTextColor, setLastTextColor] = (0, import_react20.useState)("#0f172a");
  const [lastTextBackground, setLastTextBackground] = (0, import_react20.useState)("#fde68a");
  (0, import_react20.useLayoutEffect)(() => {
    if (typeof window === "undefined") return;
    const el = editorFrameRef.current;
    if (!el) return;
    try {
      const computed = window.getComputedStyle(el);
      const vars = {};
      for (const name of ["--km-bg", "--km-panel", "--km-text", "--km-muted", "--km-border"]) {
        const value = computed.getPropertyValue(name).trim();
        if (!value) continue;
        vars[name] = value;
      }
      setToolbarThemeVars(Object.keys(vars).length > 0 ? vars : null);
    } catch {
    }
  }, []);
  const [linkPopoverOpen, setLinkPopoverOpen] = (0, import_react20.useState)(false);
  const linkAnchorRef = (0, import_react20.useRef)(null);
  const linkPopoverRef = (0, import_react20.useRef)(null);
  const [linkAnchorRect, setLinkAnchorRect] = (0, import_react20.useState)(null);
  const linkRangeRef = (0, import_react20.useRef)(null);
  const [linkHrefDraft, setLinkHrefDraft] = (0, import_react20.useState)("");
  const linkInputRef = (0, import_react20.useRef)(null);
  const [clozePopoverOpen, setClozePopoverOpen] = (0, import_react20.useState)(false);
  const clozeAnchorRef = (0, import_react20.useRef)(null);
  const clozePopoverRef = (0, import_react20.useRef)(null);
  const [clozeAnchorRect, setClozeAnchorRect] = (0, import_react20.useState)(null);
  const clozeRangeRef = (0, import_react20.useRef)(null);
  const clozeIdRef = (0, import_react20.useRef)(null);
  const [clozeStyleDraft, setClozeStyleDraft] = (0, import_react20.useState)("hole");
  const [clozeRevealModeDraft, setClozeRevealModeDraft] = (0, import_react20.useState)("click");
  const [clozeHintDraft, setClozeHintDraft] = (0, import_react20.useState)("");
  const clozeHintRef = (0, import_react20.useRef)(null);
  const [formulaPopoverOpen, setFormulaPopoverOpen] = (0, import_react20.useState)(false);
  const suppressToolbarForFormulaRef = (0, import_react20.useRef)(false);
  const formulaAnchorRef = (0, import_react20.useRef)(null);
  const formulaPopoverRef = (0, import_react20.useRef)(null);
  const [formulaAnchorRect, setFormulaAnchorRect] = (0, import_react20.useState)(null);
  const formulaAnchorKindRef = (0, import_react20.useRef)("toolbar");
  const formulaAnchorPosRef = (0, import_react20.useRef)(null);
  const formulaTargetRef = (0, import_react20.useRef)(null);
  const [formulaLatexDraft, setFormulaLatexDraft] = (0, import_react20.useState)("");
  const [formulaVariantDraft, setFormulaVariantDraft] = (0, import_react20.useState)("inline");
  const formulaInputRef = (0, import_react20.useRef)(null);
  const [slashMenuOpen, setSlashMenuOpen] = (0, import_react20.useState)(false);
  const slashMenuRef = (0, import_react20.useRef)(null);
  const slashMenuStartPosRef = (0, import_react20.useRef)(null);
  const [slashMenuAnchorRect, setSlashMenuAnchorRect] = (0, import_react20.useState)(null);
  const [slashMenuSelectedIndex, setSlashMenuSelectedIndex] = (0, import_react20.useState)(0);
  const resolveFormulaAnchorRect = () => {
    if (!editor) return null;
    if (formulaAnchorKindRef.current === "toolbar") {
      const el = formulaAnchorRef.current;
      if (el) return el.getBoundingClientRect();
    }
    const pos = formulaAnchorPosRef.current ?? editor.state.selection.from;
    try {
      const coords = editor.view.coordsAtPos(pos);
      const width = Math.max(0, coords.right - coords.left);
      const height = Math.max(0, coords.bottom - coords.top);
      if (typeof DOMRect === "undefined") return null;
      return new DOMRect(coords.left, coords.top, width, height);
    } catch {
      return null;
    }
  };
  const resolveSlashMenuAnchorRect = () => {
    if (!editor) return null;
    try {
      const coords = editor.view.coordsAtPos(editor.state.selection.from);
      const width = Math.max(0, coords.right - coords.left);
      const height = Math.max(0, coords.bottom - coords.top);
      if (typeof DOMRect === "undefined") return null;
      return new DOMRect(coords.left, coords.top, width, height);
    } catch {
      return null;
    }
  };
  const executeSlashCommand = (payload) => {
    if (!editor) return;
    if (!effectivePremium.canInsertFormula) {
      notifyBlocked("formula");
      return;
    }
    const startPos = slashMenuStartPosRef.current;
    setSlashMenuOpen(false);
    if (startPos === null) return;
    editor.chain().focus().deleteRange({ from: startPos, to: startPos + 1 }).run();
    formulaAnchorKindRef.current = "selection";
    formulaAnchorPosRef.current = startPos;
    openFormulaPopover("open", { variant: payload.variant });
  };
  (0, import_react20.useEffect)(() => {
    if (!linkPopoverOpen && !clozePopoverOpen && !formulaPopoverOpen) return;
    const win = resolveOwnerWindow(editorFrameRef.current) ?? (typeof window !== "undefined" ? window : null);
    if (!win) return;
    const onPointerDownCapture = (event) => {
      const target2 = event.target;
      if (!isNodeLike(target2)) return;
      if (linkPopoverOpen && (linkPopoverRef.current?.contains(target2) || linkAnchorRef.current?.contains(target2)) || clozePopoverOpen && (clozePopoverRef.current?.contains(target2) || clozeAnchorRef.current?.contains(target2)) || formulaPopoverOpen && (formulaPopoverRef.current?.contains(target2) || formulaAnchorRef.current?.contains(target2))) {
        return;
      }
      setLinkPopoverOpen(false);
      setClozePopoverOpen(false);
      setFormulaPopoverOpen(false);
    };
    win.addEventListener("pointerdown", onPointerDownCapture, true);
    return () => win.removeEventListener("pointerdown", onPointerDownCapture, true);
  }, [clozePopoverOpen, formulaPopoverOpen, linkPopoverOpen]);
  (0, import_react20.useEffect)(() => {
    if (!linkPopoverOpen) return;
    const win = resolveOwnerWindow(editorFrameRef.current) ?? (typeof window !== "undefined" ? window : null);
    if (!win) return;
    const update = () => setLinkAnchorRect(linkAnchorRef.current ? linkAnchorRef.current.getBoundingClientRect() : null);
    update();
    win.addEventListener("resize", update);
    win.addEventListener("scroll", update, true);
    return () => {
      win.removeEventListener("resize", update);
      win.removeEventListener("scroll", update, true);
    };
  }, [linkPopoverOpen]);
  (0, import_react20.useEffect)(() => {
    if (!clozePopoverOpen) return;
    const win = resolveOwnerWindow(editorFrameRef.current) ?? (typeof window !== "undefined" ? window : null);
    if (!win) return;
    const update = () => setClozeAnchorRect(clozeAnchorRef.current ? clozeAnchorRef.current.getBoundingClientRect() : null);
    update();
    win.addEventListener("resize", update);
    win.addEventListener("scroll", update, true);
    return () => {
      win.removeEventListener("resize", update);
      win.removeEventListener("scroll", update, true);
    };
  }, [clozePopoverOpen]);
  (0, import_react20.useEffect)(() => {
    if (!formulaPopoverOpen) return;
    const win = resolveOwnerWindow(editorFrameRef.current) ?? (typeof window !== "undefined" ? window : null);
    if (!win) return;
    const update = () => setFormulaAnchorRect(resolveFormulaAnchorRect());
    update();
    win.addEventListener("resize", update);
    win.addEventListener("scroll", update, true);
    return () => {
      win.removeEventListener("resize", update);
      win.removeEventListener("scroll", update, true);
    };
  }, [editor, formulaPopoverOpen]);
  (0, import_react20.useEffect)(() => {
    if (!slashMenuOpen) return;
    const win = resolveOwnerWindow(editorFrameRef.current) ?? (typeof window !== "undefined" ? window : null);
    if (!win) return;
    const update = () => setSlashMenuAnchorRect(resolveSlashMenuAnchorRect());
    const onPointerDownCapture = (event) => {
      const target2 = event.target;
      if (!isNodeLike(target2)) return;
      if (slashMenuRef.current?.contains(target2)) return;
      setSlashMenuOpen(false);
    };
    update();
    win.addEventListener("pointerdown", onPointerDownCapture, true);
    win.addEventListener("resize", update);
    win.addEventListener("scroll", update, true);
    return () => {
      win.removeEventListener("pointerdown", onPointerDownCapture, true);
      win.removeEventListener("resize", update);
      win.removeEventListener("scroll", update, true);
    };
  }, [editor, slashMenuOpen]);
  (0, import_react20.useEffect)(() => {
    if (!linkPopoverOpen) return;
    const id = window.setTimeout(() => {
      try {
        linkInputRef.current?.focus({ preventScroll: true });
      } catch {
        linkInputRef.current?.focus();
      }
      try {
        linkInputRef.current?.select();
      } catch {
      }
    }, 0);
    return () => window.clearTimeout(id);
  }, [linkPopoverOpen]);
  (0, import_react20.useEffect)(() => {
    if (!clozePopoverOpen) return;
    const id = window.setTimeout(() => {
      try {
        clozeHintRef.current?.focus({ preventScroll: true });
      } catch {
        clozeHintRef.current?.focus();
      }
      try {
        const value = clozeHintRef.current?.value ?? "";
        clozeHintRef.current?.setSelectionRange(value.length, value.length);
      } catch {
      }
    }, 0);
    return () => window.clearTimeout(id);
  }, [clozePopoverOpen]);
  (0, import_react20.useEffect)(() => {
    if (!formulaPopoverOpen) return;
    const id = window.setTimeout(() => {
      try {
        formulaInputRef.current?.focus({ preventScroll: true });
      } catch {
        formulaInputRef.current?.focus();
      }
      try {
        formulaInputRef.current?.select();
      } catch {
      }
    }, 0);
    return () => window.clearTimeout(id);
  }, [formulaPopoverOpen]);
  const applyLink = () => {
    if (!editor) return;
    const href = linkHrefDraft.trim();
    const range = linkRangeRef.current;
    if (!href) {
      const chain2 = editor.chain().focus();
      const chainWithSelection2 = range ? chain2.setTextSelection(range) : chain2;
      chainWithSelection2.unsetLink().run();
      setLinkPopoverOpen(false);
      return;
    }
    const chain = editor.chain().focus();
    const chainWithSelection = range ? chain.setTextSelection(range) : chain;
    chainWithSelection.setLink({ href }).run();
    setLinkPopoverOpen(false);
  };
  const removeLink = () => {
    if (!editor) return;
    const range = linkRangeRef.current;
    const chain = editor.chain().focus();
    const chainWithSelection = range ? chain.setTextSelection(range) : chain;
    chainWithSelection.unsetLink().run();
    setLinkPopoverOpen(false);
  };
  const applyCloze = () => {
    if (!editor) return;
    const id = clozeIdRef.current ?? createKmindId("cloze");
    const hint = clozeHintDraft.trim();
    const range = clozeRangeRef.current;
    const chain = editor.chain().focus();
    const chainWithSelection = range ? chain.setTextSelection(range) : chain;
    chainWithSelection.setMark("kmindCloze", {
      id,
      style: clozeStyleDraft,
      revealMode: clozeRevealModeDraft,
      hint: hint.length > 0 ? hint : null
    }).run();
    setClozePopoverOpen(false);
  };
  const removeCloze = () => {
    if (!editor) return;
    const range = clozeRangeRef.current;
    const chain = editor.chain().focus();
    const chainWithSelection = range ? chain.setTextSelection(range) : chain;
    chainWithSelection.unsetMark("kmindCloze").run();
    setClozePopoverOpen(false);
  };
  const toggleClozeFixed = () => {
    if (!editor) return;
    const selection = editor.state.selection;
    const range = selection && !selection.empty ? { from: selection.from, to: selection.to } : lastSelectionRef.current;
    if (!range) return;
    const chain = editor.chain().focus();
    const chainWithSelection = chain.setTextSelection(range);
    if (editor.isActive("kmindCloze")) {
      chainWithSelection.unsetMark("kmindCloze").run();
      return;
    }
    chainWithSelection.setMark("kmindCloze", {
      id: createKmindId("cloze"),
      style: "blur",
      revealMode: "hover",
      hint: null
    }).run();
  };
  const applyFormula = () => {
    if (!editor) return;
    const latex = formulaLatexDraft.trim();
    if (!latex) return;
    const target2 = formulaTargetRef.current;
    if (target2?.mode === "edit") {
      editor.chain().focus().updateAttributes(target2.type, { latex }).run();
      setFormulaPopoverOpen(false);
      return;
    }
    const type = formulaVariantDraft === "block" ? "kmindFormulaBlock" : "kmindFormula";
    if (type === "kmindFormula") {
      editor.chain().focus().insertContent([{ type, attrs: { latex } }, { type: "text", text: " " }]).run();
      setFormulaPopoverOpen(false);
      return;
    }
    editor.chain().focus().insertContent([{ type, attrs: { latex } }, { type: "paragraph" }]).run();
    setFormulaPopoverOpen(false);
  };
  const removeFormula = () => {
    if (!editor) return;
    editor.chain().focus().deleteSelection().run();
    setFormulaPopoverOpen(false);
  };
  const openFormulaPopover = (behavior, options) => {
    if (!editor) return;
    const selection = editor.state.selection;
    const selectedText = selection && !selection.empty ? editor.state.doc.textBetween(selection.from, selection.to, "\n") : "";
    const editingBlock = editor.isActive("kmindFormulaBlock");
    const editingInline = editor.isActive("kmindFormula");
    const targetType = editingBlock ? "kmindFormulaBlock" : "kmindFormula";
    const mode = editingBlock || editingInline ? "edit" : "insert";
    formulaTargetRef.current = { mode, type: targetType };
    const attrs = editingBlock || editingInline ? editor.getAttributes(targetType) : null;
    const currentLatex = typeof attrs?.latex === "string" ? attrs.latex : "";
    setFormulaVariantDraft(mode === "insert" ? options?.variant ?? "inline" : editingBlock ? "block" : "inline");
    setFormulaLatexDraft(mode === "edit" ? currentLatex : selectedText);
    setLinkPopoverOpen(false);
    setClozePopoverOpen(false);
    setFormulaPopoverOpen((prev) => behavior === "toggle" ? !prev : true);
  };
  const openResolvedFormulaPopover = (target2) => {
    if (!editor || !target2) return;
    suppressToolbarForFormulaRef.current = true;
    formulaAnchorKindRef.current = "selection";
    formulaAnchorPosRef.current = target2.pos;
    formulaTargetRef.current = { mode: "edit", type: target2.type };
    editor.chain().focus().setNodeSelection(target2.pos).run();
    setFormulaVariantDraft(target2.variant);
    setFormulaLatexDraft(target2.latex);
    setFormulaAnchorRect(target2.rect);
    setLinkPopoverOpen(false);
    setClozePopoverOpen(false);
    setToolbar((prev) => prev.visible ? { ...prev, visible: false } : prev);
    setFormulaPopoverOpen(true);
  };
  const applyTextStyle = (patch) => {
    if (!editor) return;
    const selection = editor.state.selection;
    const range = selection ? { from: selection.from, to: selection.to } : lastSelectionRef.current;
    const current = editor.getAttributes("kmindTextStyle");
    const currentFontSize = typeof current.fontSize === "number" ? current.fontSize : typeof current.fontSize === "string" ? Number.parseFloat(current.fontSize) : null;
    const next = {
      color: typeof current.color === "string" ? current.color : null,
      background: typeof current.background === "string" ? current.background : null,
      fontSize: Number.isFinite(currentFontSize) ? currentFontSize : null,
      fontFamily: current.fontFamily === "sans" || current.fontFamily === "serif" || current.fontFamily === "mono" ? current.fontFamily : null,
      ...patch
    };
    const hasColor = typeof next.color === "string" && next.color.trim().length > 0;
    const hasBackground = typeof next.background === "string" && next.background.trim().length > 0;
    const hasFontSize = typeof next.fontSize === "number" && Number.isFinite(next.fontSize);
    const hasFontFamily = next.fontFamily === "sans" || next.fontFamily === "serif" || next.fontFamily === "mono";
    const chain = editor.chain().focus();
    const chainWithSelection = range ? chain.setTextSelection(range) : chain;
    if (!hasColor && !hasBackground && !hasFontSize && !hasFontFamily) {
      chainWithSelection.unsetMark("kmindTextStyle").run();
      return;
    }
    chainWithSelection.setMark("kmindTextStyle", {
      color: hasColor ? next.color : null,
      background: hasBackground ? next.background : null,
      fontSize: hasFontSize ? next.fontSize : null,
      fontFamily: hasFontFamily ? next.fontFamily : null
    }).run();
  };
  const updateToolbar = () => {
    if (!editor) {
      setToolbar((prev) => prev.visible ? { ...prev, visible: false } : prev);
      return;
    }
    if (suppressToolbarForFormulaRef.current) {
      setToolbar((prev) => prev.visible ? { ...prev, visible: false } : prev);
      return;
    }
    const selection = editor.state.selection;
    const now = typeof Date !== "undefined" ? Date.now() : 0;
    const recentlyInteractedWithToolbar = now - lastToolbarPointerDownAtRef.current < 250;
    const active = typeof document !== "undefined" ? document.activeElement : null;
    const focusInToolbar = Boolean(active && toolbarRef.current?.contains(active));
    const keepVisible = focusInToolbar || recentlyInteractedWithToolbar;
    if (selection && !selection.empty) {
      lastSelectionRef.current = { from: selection.from, to: selection.to };
    }
    const selectionEmpty = !selection || selection.empty;
    const range = selectionEmpty ? keepVisible ? lastSelectionRef.current : null : { from: selection.from, to: selection.to };
    if (!range) {
      setToolbar((prev) => prev.visible ? { ...prev, visible: false } : prev);
      return;
    }
    if (!editor.isFocused && !keepVisible) {
      setToolbar((prev) => prev.visible ? { ...prev, visible: false } : prev);
      return;
    }
    try {
      const start = editor.view.coordsAtPos(range.from);
      const end = editor.view.coordsAtPos(range.to);
      const left = Math.min(start.left, end.left);
      const right = Math.max(start.right, end.right);
      const top = Math.min(start.top, end.top);
      const bottom = Math.max(start.bottom, end.bottom);
      const viewportWidth = typeof window !== "undefined" ? window.innerWidth : 0;
      const viewportHeight = typeof window !== "undefined" ? window.innerHeight : 0;
      if (viewportWidth <= 0 || viewportHeight <= 0) return;
      const x5 = (left + right) / 2;
      const yTop = top;
      const yBottom = bottom;
      const gap = 10;
      const margin = 12;
      const metrics = toolbarMetricsRef.current;
      const toolbarWidth = Math.max(40, metrics.width);
      const toolbarHeight = Math.max(24, metrics.height);
      const halfWidth = toolbarWidth / 2;
      const minX = margin + halfWidth;
      const maxX = viewportWidth - margin - halfWidth;
      const safeX = maxX >= minX ? Math.max(minX, Math.min(maxX, x5)) : viewportWidth / 2;
      const aboveTop = yTop - toolbarHeight - gap;
      const belowBottom = yBottom + gap + toolbarHeight;
      const aboveFits = aboveTop >= margin;
      const belowFits = belowBottom <= viewportHeight - margin;
      const placement = !aboveFits && belowFits ? "below" : !aboveFits && !belowFits ? "below" : "above";
      const anchorY = placement === "above" ? yTop : yBottom;
      const safeY = (() => {
        if (placement === "above") {
          const minY2 = toolbarHeight + gap + margin;
          const maxY2 = viewportHeight - margin + gap;
          if (maxY2 < minY2) return Math.max(0, Math.min(viewportHeight, anchorY));
          return Math.max(minY2, Math.min(maxY2, anchorY));
        }
        const minY = margin - gap;
        const maxY = viewportHeight - margin - gap - toolbarHeight;
        if (maxY < minY) return Math.max(0, Math.min(viewportHeight, anchorY));
        return Math.max(minY, Math.min(maxY, anchorY));
      })();
      setToolbar((prev) => {
        const next = { visible: true, x: safeX, y: safeY, placement };
        if (prev.visible && prev.placement === next.placement && Math.abs(prev.x - next.x) < 0.5 && Math.abs(prev.y - next.y) < 0.5) {
          return prev;
        }
        return next;
      });
    } catch {
      setToolbar((prev) => prev.visible ? { ...prev, visible: false } : prev);
    }
  };
  updateToolbarRef.current = updateToolbar;
  (0, import_react20.useEffect)(() => {
    if (formulaPopoverOpen) return;
    suppressToolbarForFormulaRef.current = false;
  }, [formulaPopoverOpen]);
  (0, import_react20.useEffect)(() => {
    const win = resolveOwnerWindow(editorFrameRef.current) ?? (typeof window !== "undefined" ? window : null);
    if (!win) return;
    const onViewportChange = () => updateToolbarRef.current?.();
    win.addEventListener("scroll", onViewportChange, true);
    win.addEventListener("resize", onViewportChange);
    return () => {
      win.removeEventListener("scroll", onViewportChange, true);
      win.removeEventListener("resize", onViewportChange);
    };
  }, []);
  (0, import_react20.useLayoutEffect)(() => {
    if (!toolbar.visible) return;
    const el = toolbarRef.current;
    if (!el) return;
    const rect = el.getBoundingClientRect();
    const prev = toolbarMetricsRef.current;
    const next = { width: rect.width, height: rect.height };
    const changed = Math.abs(prev.width - next.width) > 0.5 || Math.abs(prev.height - next.height) > 0.5;
    if (!changed) return;
    toolbarMetricsRef.current = next;
    if (typeof window === "undefined") return;
    window.requestAnimationFrame(() => updateToolbarRef.current?.());
  }, [toolbar.placement, toolbar.visible]);
  (0, import_react20.useEffect)(() => {
    if (!editor) return;
    const onSelection = () => updateToolbar();
    const onTransaction = () => updateToolbar();
    const onFocus = () => updateToolbar();
    const onBlur = ({ event } = {}) => {
      const next = event?.relatedTarget;
      const now = typeof Date !== "undefined" ? Date.now() : 0;
      const recentlyInteractedWithToolbar = now - lastToolbarPointerDownAtRef.current < 250;
      if (recentlyInteractedWithToolbar) return;
      if (next && toolbarRef.current?.contains(next)) return;
      setToolbar((prev) => prev.visible ? { ...prev, visible: false } : prev);
    };
    editor.on("selectionUpdate", onSelection);
    editor.on("transaction", onTransaction);
    editor.on("focus", onFocus);
    editor.on("blur", onBlur);
    updateToolbar();
    return () => {
      editor.off("selectionUpdate", onSelection);
      editor.off("transaction", onTransaction);
      editor.off("focus", onFocus);
      editor.off("blur", onBlur);
    };
  }, [editor]);
  (0, import_react20.useEffect)(() => {
    if (!editor) return;
    const dom = editor.view.dom;
    const onPointerDown = (event) => {
      if (event.button !== 0) return;
      const target2 = event.target;
      if (!isElementLike(target2)) return;
      const formulaView = target2.closest("[data-km-formula-view]");
      if (!formulaView) return;
      const formulaTarget = resolveKmindFormulaTargetFromView(editor, formulaView, {
        clientX: event.clientX,
        clientY: event.clientY
      });
      if (!formulaTarget) return;
      event.preventDefault();
      openResolvedFormulaPopover(formulaTarget);
    };
    dom.addEventListener("pointerdown", onPointerDown);
    return () => dom.removeEventListener("pointerdown", onPointerDown);
  }, [editor]);
  const buttonStyle2 = {
    border: "1px solid var(--km-border)",
    background: "transparent",
    borderRadius: 10,
    padding: "6px 10px",
    fontSize: 12,
    color: "var(--km-text)",
    cursor: "pointer"
  };
  const dispatchSet = (payload) => {
    if (props.onAction) {
      props.onAction({ type: "notes.set", nodeId: props.nodeId, doc: payload.doc, html: payload.html });
      return;
    }
    const latest = props.core.getNode(props.nodeId) ?? props.node;
    const ensured = ensureBlocksContentForMeta(latest);
    const existing = ensured.content.blocks.find((b2) => b2.type === "notes");
    const nextBlocks = ensured.content.blocks.filter((b2) => b2.type !== "notes");
    nextBlocks.push({
      id: existing?.id ?? createLocalId("notes"),
      type: "notes",
      region: "right",
      order: 0,
      engine: "prosemirror",
      doc: payload.doc,
      html: payload.html
    });
    props.core.dispatch({
      type: "set_node_content",
      payload: { nodeId: props.nodeId, content: { ...ensured.content, blocks: nextBlocks }, plainText: ensured.plainText }
    });
  };
  const dispatchClear = () => {
    if (props.onAction) {
      props.onAction({ type: "notes.clear", nodeId: props.nodeId });
      return;
    }
    const latest = props.core.getNode(props.nodeId) ?? props.node;
    const ensured = ensureBlocksContentForMeta(latest);
    const nextBlocks = ensured.content.blocks.filter((b2) => b2.type !== "notes");
    props.core.dispatch({
      type: "set_node_content",
      payload: { nodeId: props.nodeId, content: { ...ensured.content, blocks: nextBlocks }, plainText: ensured.plainText }
    });
  };
  const commit = () => {
    if (!editor) return;
    const text5 = editor.getText().trim();
    if (text5.length === 0) {
      dispatchClear();
      props.onRequestModeChange("preview");
      return;
    }
    const docJson = editor.getJSON();
    const previousCounts = countPremiumNodes(initialContent);
    const nextCounts = countPremiumNodes(docJson);
    if (!effectivePremium.canInsertFormula && nextCounts.formula > previousCounts.formula) {
      notifyBlocked("formula");
      return;
    }
    if (!effectivePremium.canInsertCloze && nextCounts.cloze > previousCounts.cloze) {
      notifyBlocked("cloze");
      return;
    }
    const html = editor.getHTML();
    dispatchSet({ doc: docJson, html });
    props.onRequestModeChange("preview");
  };
  (0, import_react20.useEffect)(() => {
    props.commitRef.current = commit;
    return () => {
      if (props.commitRef.current === commit) props.commitRef.current = null;
    };
  }, [commit, props.commitRef]);
  const dismissAccessoryRef = (0, import_react20.useRef)(() => {
  });
  dismissAccessoryRef.current = commit;
  (0, import_react20.useEffect)(() => {
    if (!editor) return;
    return bindMobileRichTextAccessorySession({
      id: `notes:${props.nodeId}`,
      context: "notes",
      editor,
      dismiss: () => dismissAccessoryRef.current()
    });
  }, [editor, props.nodeId]);
  (0, import_react20.useEffect)(() => {
    if (!editor) return;
    const notify = () => refreshMobileRichTextAccessory();
    editor.on("selectionUpdate", notify);
    editor.on("transaction", notify);
    editor.on("focus", notify);
    editor.on("blur", notify);
    notify();
    return () => {
      editor.off("selectionUpdate", notify);
      editor.off("transaction", notify);
      editor.off("focus", notify);
      editor.off("blur", notify);
      refreshMobileRichTextAccessory();
    };
  }, [editor]);
  const toolbarPosition = toolbar.visible ? toOverlayPortalPoint(overlayPortalContainer, { x: toolbar.x, y: toolbar.y }) : null;
  const toolbarNode = !(mobileRichTextAccessory.hasConsumer && presentation.isCompact && presentation.coarsePointer) && toolbar.visible && editor && toolbarPosition ? (() => {
    const attrs = editor.getAttributes("kmindTextStyle");
    const activeColor = typeof attrs.color === "string" ? attrs.color : "";
    const activeBackground = typeof attrs.background === "string" ? attrs.background : "";
    const activeFontFamily = attrs.fontFamily === "sans" || attrs.fontFamily === "serif" || attrs.fontFamily === "mono" ? attrs.fontFamily : "";
    const activeFontSize = typeof attrs.fontSize === "number" ? attrs.fontSize : typeof attrs.fontSize === "string" ? Number.parseFloat(attrs.fontSize) : Number.NaN;
    const displayColor = (activeColor.trim().length > 0 ? normalizeCssColorForInput(activeColor) : null) ?? lastTextColor;
    const displayBackground = (activeBackground.trim().length > 0 ? normalizeCssColorForInput(activeBackground) : null) ?? lastTextBackground;
    return /* @__PURE__ */ (0, import_jsx_runtime24.jsxs)(
      "div",
      {
        "data-km-meta-popover-toolbar": "true",
        ref: toolbarRef,
        onPointerDownCapture: () => {
          lastToolbarPointerDownAtRef.current = Date.now();
        },
        style: {
          position: scopedOverlayPortal ? "absolute" : "fixed",
          left: toolbarPosition.x,
          top: toolbarPosition.y,
          transform: toolbar.placement === "below" ? "translate(-50%, 10px)" : "translate(-50%, calc(-100% - 10px))",
          zIndex: 1e3,
          display: "flex",
          flexWrap: "wrap",
          gap: 6,
          alignItems: "center",
          padding: 8,
          borderRadius: 12,
          border: "1px solid var(--km-border)",
          background: "var(--km-panel)",
          boxShadow: "0 10px 24px rgba(15, 23, 42, 0.10)",
          userSelect: "none",
          pointerEvents: "auto",
          ...toolbarThemeVars ?? {}
        },
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime24.jsxs)("div", { style: { display: "flex", flexWrap: "wrap", gap: 4, alignItems: "center" }, children: [
            /* @__PURE__ */ (0, import_jsx_runtime24.jsx)(ToolbarButton, { active: editor.isActive("bold"), label: "B", onClick: () => editor.chain().focus().toggleBold().run() }),
            /* @__PURE__ */ (0, import_jsx_runtime24.jsx)(ToolbarButton, { active: editor.isActive("italic"), label: "I", onClick: () => editor.chain().focus().toggleItalic().run() }),
            /* @__PURE__ */ (0, import_jsx_runtime24.jsx)(ToolbarButton, { active: editor.isActive("strike"), label: "S", onClick: () => editor.chain().focus().toggleStrike().run() }),
            /* @__PURE__ */ (0, import_jsx_runtime24.jsx)(ToolbarButton, { active: editor.isActive("code"), label: "</>", onClick: () => editor.chain().focus().toggleCode().run() }),
            /* @__PURE__ */ (0, import_jsx_runtime24.jsx)(ToolbarButton, { active: editor.isActive("codeBlock"), label: "Block", onClick: () => editor.chain().focus().toggleCodeBlock().run() }),
            /* @__PURE__ */ (0, import_jsx_runtime24.jsx)("span", { style: { height: 16, width: 1, background: "var(--km-border)" } }),
            /* @__PURE__ */ (0, import_jsx_runtime24.jsxs)("div", { style: { display: "inline-flex", alignItems: "center", gap: 6 }, children: [
              /* @__PURE__ */ (0, import_jsx_runtime24.jsx)("div", { style: { fontSize: 11, color: "var(--km-muted)" }, children: "A" }),
              /* @__PURE__ */ (0, import_jsx_runtime24.jsx)(
                "input",
                {
                  onChange: (event) => {
                    const color = event.target.value;
                    setLastTextColor(color);
                    applyTextStyle({ color });
                  },
                  onPointerDown: tryOpenNativeColorPicker,
                  style: {
                    width: 26,
                    height: 22,
                    padding: 0,
                    border: "1px solid var(--km-border)",
                    borderRadius: 8,
                    background: "transparent",
                    cursor: "pointer"
                  },
                  type: "color",
                  value: displayColor
                }
              ),
              /* @__PURE__ */ (0, import_jsx_runtime24.jsx)(ToolbarButton, { active: activeColor.trim().length > 0, label: "\xD7", onClick: () => applyTextStyle({ color: null }) })
            ] }),
            /* @__PURE__ */ (0, import_jsx_runtime24.jsxs)("div", { style: { display: "inline-flex", alignItems: "center", gap: 6 }, children: [
              /* @__PURE__ */ (0, import_jsx_runtime24.jsx)("div", { style: { fontSize: 11, color: "var(--km-muted)" }, children: "Bg" }),
              /* @__PURE__ */ (0, import_jsx_runtime24.jsx)(
                "input",
                {
                  onChange: (event) => {
                    const background = event.target.value;
                    setLastTextBackground(background);
                    applyTextStyle({ background });
                  },
                  onPointerDown: tryOpenNativeColorPicker,
                  style: {
                    width: 26,
                    height: 22,
                    padding: 0,
                    border: "1px solid var(--km-border)",
                    borderRadius: 8,
                    background: "transparent",
                    cursor: "pointer"
                  },
                  type: "color",
                  value: displayBackground
                }
              ),
              /* @__PURE__ */ (0, import_jsx_runtime24.jsx)(ToolbarButton, { active: activeBackground.trim().length > 0, label: "\xD7", onClick: () => applyTextStyle({ background: null }) })
            ] }),
            /* @__PURE__ */ (0, import_jsx_runtime24.jsxs)("div", { style: { display: "inline-flex", alignItems: "center", gap: 6 }, children: [
              /* @__PURE__ */ (0, import_jsx_runtime24.jsx)("div", { style: { fontSize: 11, color: "var(--km-muted)" }, children: "Size" }),
              /* @__PURE__ */ (0, import_jsx_runtime24.jsxs)(
                "select",
                {
                  onChange: (event) => {
                    const value = event.target.value;
                    if (value.trim().length === 0) {
                      applyTextStyle({ fontSize: null });
                      return;
                    }
                    const num = Number.parseFloat(value);
                    applyTextStyle({ fontSize: Number.isFinite(num) ? num : null });
                  },
                  style: {
                    border: "1px solid var(--km-border)",
                    background: "transparent",
                    color: "var(--km-text)",
                    borderRadius: 8,
                    fontSize: 12,
                    padding: "4px 6px",
                    cursor: "pointer"
                  },
                  value: Number.isFinite(activeFontSize) ? String(activeFontSize) : "",
                  children: [
                    /* @__PURE__ */ (0, import_jsx_runtime24.jsx)("option", { value: "", children: "auto" }),
                    [10, 11, 12, 13, 14, 16, 18, 20, 24, 28, 32].map((size) => /* @__PURE__ */ (0, import_jsx_runtime24.jsxs)("option", { value: String(size), children: [
                      size,
                      "px"
                    ] }, size))
                  ]
                }
              )
            ] }),
            /* @__PURE__ */ (0, import_jsx_runtime24.jsxs)("div", { style: { display: "inline-flex", alignItems: "center", gap: 6 }, children: [
              /* @__PURE__ */ (0, import_jsx_runtime24.jsx)("div", { style: { fontSize: 11, color: "var(--km-muted)" }, children: "Font" }),
              /* @__PURE__ */ (0, import_jsx_runtime24.jsxs)(
                "select",
                {
                  onChange: (event) => {
                    const value = event.target.value.trim();
                    if (value.length === 0) {
                      applyTextStyle({ fontFamily: null });
                      return;
                    }
                    if (value === "sans" || value === "serif" || value === "mono") {
                      applyTextStyle({ fontFamily: value });
                    }
                  },
                  style: {
                    border: "1px solid var(--km-border)",
                    background: "transparent",
                    color: "var(--km-text)",
                    borderRadius: 8,
                    fontSize: 12,
                    padding: "4px 6px",
                    cursor: "pointer"
                  },
                  value: activeFontFamily,
                  children: [
                    /* @__PURE__ */ (0, import_jsx_runtime24.jsx)("option", { value: "", children: "inherit" }),
                    /* @__PURE__ */ (0, import_jsx_runtime24.jsx)("option", { value: "sans", children: "Sans" }),
                    /* @__PURE__ */ (0, import_jsx_runtime24.jsx)("option", { value: "serif", children: "Serif" }),
                    /* @__PURE__ */ (0, import_jsx_runtime24.jsx)("option", { value: "mono", children: "Mono" })
                  ]
                }
              )
            ] }),
            /* @__PURE__ */ (0, import_jsx_runtime24.jsx)("span", { style: { height: 16, width: 1, background: "var(--km-border)" } }),
            /* @__PURE__ */ (0, import_jsx_runtime24.jsx)("span", { ref: linkAnchorRef, style: { display: "inline-flex" }, children: /* @__PURE__ */ (0, import_jsx_runtime24.jsx)(
              ToolbarButton,
              {
                active: editor.isActive("link"),
                label: "Link",
                onClick: () => {
                  if (!editor) return;
                  const attrs2 = editor.getAttributes("link");
                  const currentHref = typeof attrs2.href === "string" ? attrs2.href : "";
                  setLinkHrefDraft(currentHref);
                  const selection = editor.state.selection;
                  linkRangeRef.current = selection && !selection.empty ? { from: selection.from, to: selection.to } : lastSelectionRef.current;
                  setClozePopoverOpen(false);
                  setLinkPopoverOpen((prev) => !prev);
                }
              }
            ) }),
            /* @__PURE__ */ (0, import_jsx_runtime24.jsx)("span", { ref: clozeAnchorRef, style: { display: "inline-flex" }, children: /* @__PURE__ */ (0, import_jsx_runtime24.jsx)(
              ToolbarButton,
              {
                active: editor.isActive("kmindCloze"),
                label: "Cloze",
                onClick: () => {
                  if (!editor) return;
                  if (!effectivePremium.canInsertCloze && !editor.isActive("kmindCloze")) {
                    notifyBlocked("cloze");
                    return;
                  }
                  setLinkPopoverOpen(false);
                  setClozePopoverOpen(false);
                  toggleClozeFixed();
                }
              }
            ) }),
            /* @__PURE__ */ (0, import_jsx_runtime24.jsx)("span", { ref: formulaAnchorRef, style: { display: "inline-flex" }, children: /* @__PURE__ */ (0, import_jsx_runtime24.jsx)(
              ToolbarButton,
              {
                active: editor.isActive("kmindFormula") || editor.isActive("kmindFormulaBlock"),
                label: "Fx",
                onClick: () => {
                  if (!effectivePremium.canInsertFormula && !(editor.isActive("kmindFormula") || editor.isActive("kmindFormulaBlock"))) {
                    notifyBlocked("formula");
                    return;
                  }
                  openFormulaPopover("toggle");
                }
              }
            ) })
          ] }),
          linkPopoverOpen && linkAnchorRect ? /* @__PURE__ */ (0, import_jsx_runtime24.jsxs)(
            "div",
            {
              ref: linkPopoverRef,
              onPointerDownCapture: (event) => event.stopPropagation(),
              style: {
                position: "absolute",
                left: (() => {
                  const toolbarRect = toolbarRef.current?.getBoundingClientRect();
                  if (!toolbarRect) return 0;
                  return linkAnchorRect.left - toolbarRect.left + linkAnchorRect.width / 2;
                })(),
                top: (() => {
                  const toolbarRect = toolbarRef.current?.getBoundingClientRect();
                  if (!toolbarRect) return 0;
                  return linkAnchorRect.bottom - toolbarRect.top + 10;
                })(),
                transform: "translate(-50%, 0)",
                width: 320,
                padding: 10,
                borderRadius: 12,
                border: "1px solid var(--km-border)",
                background: "var(--km-panel)",
                boxShadow: "0 18px 36px rgba(15, 23, 42, 0.18)",
                zIndex: 1100
              },
              children: [
                /* @__PURE__ */ (0, import_jsx_runtime24.jsx)("div", { style: { fontSize: 11, color: "var(--km-muted)", marginBottom: 8 }, children: "Link" }),
                /* @__PURE__ */ (0, import_jsx_runtime24.jsx)(
                  "input",
                  {
                    ref: linkInputRef,
                    onChange: (event) => setLinkHrefDraft(event.target.value),
                    onKeyDown: (event) => {
                      if (event.key === "Escape") {
                        event.preventDefault();
                        event.stopPropagation();
                        setLinkPopoverOpen(false);
                        return;
                      }
                      if (event.key === "Enter") {
                        event.preventDefault();
                        event.stopPropagation();
                        applyLink();
                      }
                    },
                    placeholder: "https://...",
                    style: {
                      width: "100%",
                      border: "1px solid var(--km-border)",
                      background: "transparent",
                      color: "var(--km-text)",
                      borderRadius: 10,
                      padding: "8px 10px",
                      outline: "none"
                    },
                    value: linkHrefDraft
                  }
                ),
                /* @__PURE__ */ (0, import_jsx_runtime24.jsxs)("div", { style: { display: "flex", justifyContent: "flex-end", gap: 8, marginTop: 10 }, children: [
                  /* @__PURE__ */ (0, import_jsx_runtime24.jsx)(
                    "button",
                    {
                      onClick: removeLink,
                      style: {
                        border: "1px solid var(--km-border)",
                        background: "transparent",
                        borderRadius: 10,
                        padding: "6px 10px",
                        fontSize: 12,
                        color: "var(--km-text)",
                        cursor: "pointer",
                        opacity: editor.isActive("link") ? 1 : 0.55
                      },
                      type: "button",
                      children: "Remove"
                    }
                  ),
                  /* @__PURE__ */ (0, import_jsx_runtime24.jsx)(
                    "button",
                    {
                      onClick: applyLink,
                      style: {
                        border: "1px solid rgba(59, 130, 246, 0.85)",
                        background: "rgba(59, 130, 246, 0.18)",
                        borderRadius: 10,
                        padding: "6px 10px",
                        fontSize: 12,
                        color: "var(--km-text)",
                        cursor: "pointer"
                      },
                      type: "button",
                      children: "Apply"
                    }
                  )
                ] })
              ]
            }
          ) : null,
          CLOZE_ADVANCED_UI_ENABLED && clozePopoverOpen && clozeAnchorRect ? /* @__PURE__ */ (0, import_jsx_runtime24.jsxs)(
            "div",
            {
              ref: clozePopoverRef,
              onPointerDownCapture: (event) => event.stopPropagation(),
              style: {
                position: "absolute",
                left: (() => {
                  const toolbarRect = toolbarRef.current?.getBoundingClientRect();
                  if (!toolbarRect) return 0;
                  return clozeAnchorRect.left - toolbarRect.left + clozeAnchorRect.width / 2;
                })(),
                top: (() => {
                  const toolbarRect = toolbarRef.current?.getBoundingClientRect();
                  if (!toolbarRect) return 0;
                  return clozeAnchorRect.bottom - toolbarRect.top + 10;
                })(),
                transform: "translate(-50%, 0)",
                width: 360,
                padding: 10,
                borderRadius: 12,
                border: "1px solid var(--km-border)",
                background: "var(--km-panel)",
                boxShadow: "0 18px 36px rgba(15, 23, 42, 0.18)",
                zIndex: 1100
              },
              children: [
                /* @__PURE__ */ (0, import_jsx_runtime24.jsx)("div", { style: { fontSize: 11, color: "var(--km-muted)", marginBottom: 8 }, children: "Cloze" }),
                /* @__PURE__ */ (0, import_jsx_runtime24.jsxs)("div", { style: { display: "flex", gap: 8, flexWrap: "wrap" }, children: [
                  /* @__PURE__ */ (0, import_jsx_runtime24.jsxs)("label", { style: { display: "flex", flexDirection: "column", gap: 6, flex: "1 1 120px" }, children: [
                    /* @__PURE__ */ (0, import_jsx_runtime24.jsx)("div", { style: { fontSize: 11, color: "var(--km-muted)" }, children: "Style" }),
                    /* @__PURE__ */ (0, import_jsx_runtime24.jsxs)(
                      "select",
                      {
                        onChange: (event) => setClozeStyleDraft(event.target.value === "blur" ? "blur" : "hole"),
                        style: {
                          border: "1px solid var(--km-border)",
                          background: "transparent",
                          color: "var(--km-text)",
                          borderRadius: 10,
                          padding: "8px 10px",
                          cursor: "pointer"
                        },
                        value: clozeStyleDraft,
                        children: [
                          /* @__PURE__ */ (0, import_jsx_runtime24.jsx)("option", { value: "hole", children: "hole" }),
                          /* @__PURE__ */ (0, import_jsx_runtime24.jsx)("option", { value: "blur", children: "blur" })
                        ]
                      }
                    )
                  ] }),
                  /* @__PURE__ */ (0, import_jsx_runtime24.jsxs)("label", { style: { display: "flex", flexDirection: "column", gap: 6, flex: "1 1 120px" }, children: [
                    /* @__PURE__ */ (0, import_jsx_runtime24.jsx)("div", { style: { fontSize: 11, color: "var(--km-muted)" }, children: "Reveal" }),
                    /* @__PURE__ */ (0, import_jsx_runtime24.jsxs)(
                      "select",
                      {
                        onChange: (event) => {
                          const value = event.target.value;
                          setClozeRevealModeDraft(value === "hover" ? "hover" : value === "manual" ? "manual" : "click");
                        },
                        style: {
                          border: "1px solid var(--km-border)",
                          background: "transparent",
                          color: "var(--km-text)",
                          borderRadius: 10,
                          padding: "8px 10px",
                          cursor: "pointer"
                        },
                        value: clozeRevealModeDraft,
                        children: [
                          /* @__PURE__ */ (0, import_jsx_runtime24.jsx)("option", { value: "click", children: "click" }),
                          /* @__PURE__ */ (0, import_jsx_runtime24.jsx)("option", { value: "hover", children: "hover" }),
                          /* @__PURE__ */ (0, import_jsx_runtime24.jsx)("option", { value: "manual", children: "manual" })
                        ]
                      }
                    )
                  ] })
                ] }),
                /* @__PURE__ */ (0, import_jsx_runtime24.jsxs)("label", { style: { display: "flex", flexDirection: "column", gap: 6, marginTop: 10 }, children: [
                  /* @__PURE__ */ (0, import_jsx_runtime24.jsx)("div", { style: { fontSize: 11, color: "var(--km-muted)" }, children: "Hint" }),
                  /* @__PURE__ */ (0, import_jsx_runtime24.jsx)(
                    "input",
                    {
                      ref: clozeHintRef,
                      onChange: (event) => setClozeHintDraft(event.target.value),
                      onKeyDown: (event) => {
                        if (event.key === "Escape") {
                          event.preventDefault();
                          event.stopPropagation();
                          setClozePopoverOpen(false);
                          return;
                        }
                        if (event.key === "Enter") {
                          event.preventDefault();
                          event.stopPropagation();
                          applyCloze();
                        }
                      },
                      placeholder: "optional",
                      style: {
                        width: "100%",
                        border: "1px solid var(--km-border)",
                        background: "transparent",
                        color: "var(--km-text)",
                        borderRadius: 10,
                        padding: "8px 10px",
                        outline: "none"
                      },
                      value: clozeHintDraft
                    }
                  )
                ] }),
                /* @__PURE__ */ (0, import_jsx_runtime24.jsxs)("div", { style: { display: "flex", justifyContent: "flex-end", gap: 8, marginTop: 10 }, children: [
                  /* @__PURE__ */ (0, import_jsx_runtime24.jsx)(
                    "button",
                    {
                      onClick: removeCloze,
                      style: {
                        border: "1px solid var(--km-border)",
                        background: "transparent",
                        borderRadius: 10,
                        padding: "6px 10px",
                        fontSize: 12,
                        color: "var(--km-text)",
                        cursor: "pointer",
                        opacity: editor.isActive("kmindCloze") ? 1 : 0.55
                      },
                      type: "button",
                      children: "Remove"
                    }
                  ),
                  /* @__PURE__ */ (0, import_jsx_runtime24.jsx)(
                    "button",
                    {
                      onClick: applyCloze,
                      style: {
                        border: "1px solid rgba(59, 130, 246, 0.85)",
                        background: "rgba(59, 130, 246, 0.18)",
                        borderRadius: 10,
                        padding: "6px 10px",
                        fontSize: 12,
                        color: "var(--km-text)",
                        cursor: "pointer"
                      },
                      type: "button",
                      children: "Apply"
                    }
                  )
                ] })
              ]
            }
          ) : null
        ]
      }
    );
  })() : null;
  const slashMenuPosition = slashMenuOpen && slashMenuAnchorRect ? toOverlayPortalPoint(overlayPortalContainer, {
    x: (() => {
      const width = 220;
      const margin = 12;
      const viewportWidth = typeof window !== "undefined" ? window.innerWidth : 0;
      const raw = slashMenuAnchorRect.left;
      const maxX = Math.max(margin, viewportWidth - width - margin);
      return Math.max(margin, Math.min(maxX, raw));
    })(),
    y: slashMenuAnchorRect.bottom + 8
  }) : null;
  const slashMenuNode = slashMenuOpen && slashMenuAnchorRect && slashMenuPosition ? /* @__PURE__ */ (0, import_jsx_runtime24.jsxs)(
    "div",
    {
      "data-km-meta-popover-toolbar": "true",
      ref: slashMenuRef,
      onPointerDownCapture: (event) => event.stopPropagation(),
      style: {
        position: scopedOverlayPortal ? "absolute" : "fixed",
        left: slashMenuPosition.x,
        top: slashMenuPosition.y,
        width: 220,
        padding: 6,
        borderRadius: 12,
        border: "1px solid var(--km-border)",
        background: "var(--km-panel)",
        boxShadow: "0 18px 36px rgba(15, 23, 42, 0.18)",
        zIndex: 1050,
        pointerEvents: "auto",
        ...toolbarThemeVars ?? {}
      },
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime24.jsx)("div", { style: { fontSize: 11, color: "var(--km-muted)", padding: "2px 6px 6px" }, children: "Commands" }),
        /* @__PURE__ */ (0, import_jsx_runtime24.jsxs)(
          "button",
          {
            onMouseDown: (event) => event.preventDefault(),
            onClick: () => executeSlashCommand({ variant: "inline" }),
            style: {
              width: "100%",
              display: "flex",
              justifyContent: "space-between",
              alignItems: "center",
              gap: 8,
              border: "1px solid transparent",
              background: slashMenuSelectedIndex === 0 ? "rgba(59, 130, 246, 0.14)" : "transparent",
              borderRadius: 10,
              padding: "8px 10px",
              color: "var(--km-text)",
              cursor: "pointer",
              textAlign: "left"
            },
            type: "button",
            children: [
              /* @__PURE__ */ (0, import_jsx_runtime24.jsx)("span", { style: { fontSize: 12 }, children: "Formula (inline)" }),
              /* @__PURE__ */ (0, import_jsx_runtime24.jsx)("span", { style: { fontSize: 11, color: "var(--km-muted)" }, children: "Enter" })
            ]
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime24.jsxs)(
          "button",
          {
            onMouseDown: (event) => event.preventDefault(),
            onClick: () => executeSlashCommand({ variant: "block" }),
            style: {
              width: "100%",
              display: "flex",
              justifyContent: "space-between",
              alignItems: "center",
              gap: 8,
              border: "1px solid transparent",
              background: slashMenuSelectedIndex === 1 ? "rgba(59, 130, 246, 0.14)" : "transparent",
              borderRadius: 10,
              padding: "8px 10px",
              color: "var(--km-text)",
              cursor: "pointer",
              textAlign: "left"
            },
            type: "button",
            children: [
              /* @__PURE__ */ (0, import_jsx_runtime24.jsx)("span", { style: { fontSize: 12 }, children: "Formula (block)" }),
              /* @__PURE__ */ (0, import_jsx_runtime24.jsx)("span", { style: { fontSize: 11, color: "var(--km-muted)" }, children: "\u2193" })
            ]
          }
        )
      ]
    }
  ) : null;
  const formulaPopoverPosition = formulaPopoverOpen && formulaAnchorRect ? toOverlayPortalPoint(overlayPortalContainer, {
    x: formulaAnchorRect.left + formulaAnchorRect.width / 2,
    y: formulaAnchorRect.bottom + 10
  }) : null;
  const formulaPopoverNode = formulaPopoverOpen && formulaAnchorRect && formulaPopoverPosition ? /* @__PURE__ */ (0, import_jsx_runtime24.jsx)(
    RichTextFormulaPopover,
    {
      dataKmMetaPopoverToolbar: true,
      inputRef: formulaInputRef,
      ref: formulaPopoverRef,
      latex: formulaLatexDraft,
      mode: formulaTargetRef.current?.mode ?? "insert",
      onPointerDownCapture: (event) => event.stopPropagation(),
      onApply: applyFormula,
      onClose: () => setFormulaPopoverOpen(false),
      onLatexChange: setFormulaLatexDraft,
      onRemove: removeFormula,
      onVariantChange: setFormulaVariantDraft,
      position: scopedOverlayPortal ? "absolute" : "fixed",
      style: toolbarThemeVars ?? void 0,
      variant: formulaVariantDraft,
      x: formulaPopoverPosition.x,
      y: formulaPopoverPosition.y,
      zIndex: 1100
    }
  ) : null;
  return /* @__PURE__ */ (0, import_jsx_runtime24.jsxs)(
    "div",
    {
      onKeyDownCapture: (event) => {
        const native = event.nativeEvent;
        if ("isComposing" in native && native.isComposing) return;
        if (slashMenuOpen) {
          if (event.key === "Escape") {
            event.preventDefault();
            event.stopPropagation();
            setSlashMenuOpen(false);
            return;
          }
          if (event.key === "ArrowDown" || event.key === "ArrowUp") {
            event.preventDefault();
            event.stopPropagation();
            setSlashMenuSelectedIndex((prev) => {
              const next = event.key === "ArrowDown" ? prev + 1 : prev - 1;
              return Math.max(0, Math.min(1, next));
            });
            return;
          }
          if (event.key === "Enter") {
            event.preventDefault();
            event.stopPropagation();
            executeSlashCommand({ variant: slashMenuSelectedIndex === 1 ? "block" : "inline" });
            return;
          }
          setSlashMenuOpen(false);
        }
        if (event.key === "Escape") {
          event.preventDefault();
          event.stopPropagation();
          props.onRequestModeChange("preview");
          return;
        }
        if (event.key === "/" && !event.metaKey && !event.ctrlKey && !event.altKey) {
          if (!editor) return;
          const selection = editor.state.selection;
          if (!selection || !selection.empty) return;
          if (editor.isActive("codeBlock")) return;
          if (selection.$from.parentOffset !== 0) return;
          event.preventDefault();
          event.stopPropagation();
          const startPos = selection.from;
          editor.chain().focus().insertContent("/").run();
          slashMenuStartPosRef.current = startPos;
          setSlashMenuSelectedIndex(0);
          setSlashMenuOpen(true);
          setSlashMenuAnchorRect(resolveSlashMenuAnchorRect());
          return;
        }
        if (event.key.toLowerCase() === "m" && (event.metaKey || event.ctrlKey)) {
          event.preventDefault();
          event.stopPropagation();
          formulaAnchorKindRef.current = "selection";
          formulaAnchorPosRef.current = editor?.state.selection.from ?? null;
          openFormulaPopover("open");
          return;
        }
        if (event.key === "Enter" && (event.metaKey || event.ctrlKey)) {
          event.preventDefault();
          event.stopPropagation();
          commit();
        }
      },
      style: { display: "flex", flexDirection: "column", gap: 10 },
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime24.jsx)("div", { ref: editorFrameRef, style: { border: "1px solid var(--km-border)", borderRadius: 12, padding: 10, position: "relative" }, children: /* @__PURE__ */ (0, import_jsx_runtime24.jsx)(EditorContent, { editor }) }),
        /* @__PURE__ */ (0, import_jsx_runtime24.jsxs)("div", { style: { display: "flex", justifyContent: "flex-end", gap: 8 }, children: [
          /* @__PURE__ */ (0, import_jsx_runtime24.jsx)(
            "button",
            {
              onClick: () => {
                dispatchClear();
                props.onRequestModeChange("preview");
              },
              style: buttonStyle2,
              type: "button",
              children: t("editor.meta.notes.action.clear")
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime24.jsx)("button", { onClick: commit, style: buttonStyle2, type: "button", children: t("editor.meta.notes.action.save") })
        ] }),
        overlayPortalTarget ? (0, import_react_dom4.createPortal)(
          /* @__PURE__ */ (0, import_jsx_runtime24.jsxs)(import_jsx_runtime24.Fragment, { children: [
            toolbarNode,
            slashMenuNode,
            formulaPopoverNode
          ] }),
          overlayPortalTarget
        ) : /* @__PURE__ */ (0, import_jsx_runtime24.jsxs)(import_jsx_runtime24.Fragment, { children: [
          toolbarNode,
          slashMenuNode,
          formulaPopoverNode
        ] })
      ]
    }
  );
}
function NodeCommentsPopoverContent(props) {
  const t = useT();
  const comments = (0, import_react20.useMemo)(() => resolveNodeComments(props.node), [props.node]);
  const effectivePremium = props.premiumCapabilities ?? {
    canCreateBacklinks: true,
    canInsertFormula: true,
    canInsertCloze: true,
    canCreateComments: true,
    canInsertSiyuanDocLink: true
  };
  const sorted = (0, import_react20.useMemo)(() => [...comments].sort((a2, b2) => a2.createdAt - b2.createdAt), [comments]);
  const draftTextareaRef = (0, import_react20.useRef)(null);
  const editingTextareaRef = (0, import_react20.useRef)(null);
  const [draftText, setDraftText] = (0, import_react20.useState)("");
  const [editingId, setEditingId] = (0, import_react20.useState)(null);
  const [editingText, setEditingText] = (0, import_react20.useState)("");
  (0, import_react20.useEffect)(() => {
    if (!editingId) return;
    const found2 = sorted.find((c) => c.id === editingId);
    if (!found2) {
      setEditingId(null);
      setEditingText("");
    }
  }, [editingId, sorted]);
  (0, import_react20.useLayoutEffect)(() => {
    if (props.mode !== "edit") return;
    const el = editingId ? editingTextareaRef.current : draftTextareaRef.current;
    if (!el) return;
    try {
      el.focus({ preventScroll: true });
    } catch {
      try {
        el.focus();
      } catch {
      }
    }
    try {
      const end = el.value.length;
      el.setSelectionRange(end, end);
    } catch {
    }
  }, [editingId, props.mode]);
  const buttonStyle2 = {
    border: "1px solid var(--km-border)",
    background: "transparent",
    borderRadius: 10,
    padding: "6px 10px",
    fontSize: 12,
    color: "var(--km-text)",
    cursor: "pointer"
  };
  const dispatchUpdate = (action) => {
    if (action.type === "comments.add" && !effectivePremium.canCreateComments) {
      props.onPremiumFeatureBlocked?.("comments");
      return;
    }
    if (props.onAction) {
      props.onAction(action);
      return;
    }
    const latest = props.core.getNode(props.nodeId) ?? props.node;
    const ensured = ensureBlocksContentForMeta(latest);
    const current = resolveNodeComments(latest);
    const existingBlock = ensured.content.blocks.find((b2) => b2.type === "comments");
    const baseItems = existingBlock ? existingBlock.items : current;
    const nextBlocks = (() => {
      if (action.type === "comments.clear") return ensured.content.blocks.filter((b2) => b2.type !== "comments");
      if (action.type === "comments.add") {
        const nextItem = { id: createLocalId("c"), text: action.text, createdAt: action.createdAt ?? Date.now() };
        const items = [...baseItems, nextItem];
        const nextBlocks2 = ensured.content.blocks.filter((b2) => b2.type !== "comments");
        nextBlocks2.push({ id: existingBlock?.id ?? createLocalId("comments"), type: "comments", region: "right", order: 10, items });
        return nextBlocks2;
      }
      if (action.type === "comments.remove") {
        const items = baseItems.filter((c) => c.id !== action.commentId);
        return items.length === 0 ? ensured.content.blocks.filter((b2) => b2.type !== "comments") : ensured.content.blocks.map((b2) => b2.type === "comments" ? { ...b2, items } : b2);
      }
      if (action.type === "comments.update") {
        const items = baseItems.map((c) => c.id === action.commentId ? { ...c, text: action.text } : c);
        const nextBlocks2 = ensured.content.blocks.filter((b2) => b2.type !== "comments");
        nextBlocks2.push({ id: existingBlock?.id ?? createLocalId("comments"), type: "comments", region: "right", order: 10, items });
        return nextBlocks2;
      }
      return ensured.content.blocks;
    })();
    props.core.dispatch({
      type: "set_node_content",
      payload: { nodeId: props.nodeId, content: { ...ensured.content, blocks: nextBlocks }, plainText: ensured.plainText }
    });
  };
  (0, import_react20.useEffect)(() => {
    if (props.mode !== "edit") {
      props.commitRef.current = null;
      return;
    }
    props.commitRef.current = () => {
      const pendingEditId = editingId;
      const pendingEditText = editingText.trim();
      if (pendingEditId && pendingEditText.length > 0) {
        dispatchUpdate({ type: "comments.update", nodeId: props.nodeId, commentId: pendingEditId, text: pendingEditText });
      }
      const pendingDraft = draftText.trim();
      if (pendingDraft.length > 0) {
        dispatchUpdate({ type: "comments.add", nodeId: props.nodeId, text: pendingDraft, createdAt: Date.now() });
      }
    };
    return () => {
      props.commitRef.current = null;
    };
  }, [dispatchUpdate, draftText, editingId, editingText, props.commitRef, props.mode, props.nodeId]);
  const formatTime = (timestamp) => {
    try {
      return new Date(timestamp).toLocaleString();
    } catch {
      return String(timestamp);
    }
  };
  if (props.mode !== "edit") {
    if (sorted.length === 0) return /* @__PURE__ */ (0, import_jsx_runtime24.jsx)("div", { style: { fontSize: 12, color: "var(--km-muted)" }, children: t("editor.meta.comments.empty") });
    return /* @__PURE__ */ (0, import_jsx_runtime24.jsx)("div", { style: { display: "flex", flexDirection: "column", gap: 10 }, children: sorted.map((item) => /* @__PURE__ */ (0, import_jsx_runtime24.jsxs)(
      "div",
      {
        style: { display: "flex", flexDirection: "column", gap: 6, paddingBottom: 10, borderBottom: "1px solid var(--km-border)" },
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime24.jsx)("div", { style: { fontSize: 11, color: "var(--km-muted)" }, children: formatTime(item.createdAt) }),
          /* @__PURE__ */ (0, import_jsx_runtime24.jsx)("div", { style: { fontSize: 12, lineHeight: "1.45", color: "var(--km-text)", whiteSpace: "pre-wrap", overflowWrap: "anywhere" }, children: item.text })
        ]
      },
      item.id
    )) });
  }
  return /* @__PURE__ */ (0, import_jsx_runtime24.jsxs)("div", { style: { display: "flex", flexDirection: "column", gap: 12 }, children: [
    sorted.length > 0 ? /* @__PURE__ */ (0, import_jsx_runtime24.jsx)("div", { style: { display: "flex", flexDirection: "column", gap: 12 }, children: sorted.map((item) => {
      const isEditing = editingId === item.id;
      return /* @__PURE__ */ (0, import_jsx_runtime24.jsxs)(
        "div",
        {
          style: { display: "flex", flexDirection: "column", gap: 8, paddingBottom: 12, borderBottom: "1px solid var(--km-border)" },
          children: [
            /* @__PURE__ */ (0, import_jsx_runtime24.jsxs)("div", { style: { display: "flex", justifyContent: "space-between", gap: 10 }, children: [
              /* @__PURE__ */ (0, import_jsx_runtime24.jsx)("div", { style: { fontSize: 11, color: "var(--km-muted)" }, children: formatTime(item.createdAt) }),
              /* @__PURE__ */ (0, import_jsx_runtime24.jsxs)("div", { style: { display: "flex", gap: 8 }, children: [
                /* @__PURE__ */ (0, import_jsx_runtime24.jsx)(
                  "button",
                  {
                    onClick: () => {
                      setEditingId(item.id);
                      setEditingText(item.text);
                    },
                    style: buttonStyle2,
                    type: "button",
                    children: t("editor.meta.action.edit")
                  }
                ),
                /* @__PURE__ */ (0, import_jsx_runtime24.jsx)(
                  "button",
                  {
                    onClick: () => dispatchUpdate({ type: "comments.remove", nodeId: props.nodeId, commentId: item.id }),
                    style: buttonStyle2,
                    type: "button",
                    children: t("editor.meta.comments.action.delete")
                  }
                )
              ] })
            ] }),
            isEditing ? /* @__PURE__ */ (0, import_jsx_runtime24.jsxs)(import_jsx_runtime24.Fragment, { children: [
              /* @__PURE__ */ (0, import_jsx_runtime24.jsx)(
                "textarea",
                {
                  ref: isEditing ? editingTextareaRef : void 0,
                  onChange: (e) => setEditingText(e.target.value),
                  rows: 3,
                  style: {
                    width: "100%",
                    resize: "vertical",
                    padding: "8px 10px",
                    borderRadius: 10,
                    border: "1px solid var(--km-border)",
                    background: "transparent",
                    fontSize: 12,
                    lineHeight: "1.45",
                    color: "var(--km-text)"
                  },
                  value: editingText
                }
              ),
              /* @__PURE__ */ (0, import_jsx_runtime24.jsxs)("div", { style: { display: "flex", justifyContent: "flex-end", gap: 8 }, children: [
                /* @__PURE__ */ (0, import_jsx_runtime24.jsx)(
                  "button",
                  {
                    onClick: () => {
                      setEditingId(null);
                      setEditingText("");
                    },
                    style: buttonStyle2,
                    type: "button",
                    children: t("editor.meta.action.cancel")
                  }
                ),
                /* @__PURE__ */ (0, import_jsx_runtime24.jsx)(
                  "button",
                  {
                    onClick: () => {
                      const next = editingText.trim();
                      if (next.length === 0) return;
                      dispatchUpdate({ type: "comments.update", nodeId: props.nodeId, commentId: item.id, text: next });
                      setEditingId(null);
                      setEditingText("");
                    },
                    style: buttonStyle2,
                    type: "button",
                    children: t("editor.meta.action.save")
                  }
                )
              ] })
            ] }) : /* @__PURE__ */ (0, import_jsx_runtime24.jsx)("div", { style: { fontSize: 12, lineHeight: "1.45", color: "var(--km-text)", whiteSpace: "pre-wrap", overflowWrap: "anywhere" }, children: item.text })
          ]
        },
        item.id
      );
    }) }) : /* @__PURE__ */ (0, import_jsx_runtime24.jsx)("div", { style: { fontSize: 12, color: "var(--km-muted)" }, children: t("editor.meta.comments.empty") }),
    /* @__PURE__ */ (0, import_jsx_runtime24.jsxs)("div", { style: { display: "flex", flexDirection: "column", gap: 8 }, children: [
      /* @__PURE__ */ (0, import_jsx_runtime24.jsx)(
        "textarea",
        {
          ref: draftTextareaRef,
          onChange: (e) => setDraftText(e.target.value),
          placeholder: t("editor.meta.comments.placeholder.new"),
          rows: 3,
          style: {
            width: "100%",
            resize: "vertical",
            padding: "8px 10px",
            borderRadius: 10,
            border: "1px solid var(--km-border)",
            background: "transparent",
            fontSize: 12,
            lineHeight: "1.45",
            color: "var(--km-text)"
          },
          value: draftText
        }
      ),
      /* @__PURE__ */ (0, import_jsx_runtime24.jsxs)("div", { style: { display: "flex", justifyContent: "flex-end", gap: 8 }, children: [
        sorted.length > 0 ? /* @__PURE__ */ (0, import_jsx_runtime24.jsx)("button", { onClick: () => dispatchUpdate({ type: "comments.clear", nodeId: props.nodeId }), style: buttonStyle2, type: "button", children: t("editor.meta.comments.action.clearAll") }) : null,
        /* @__PURE__ */ (0, import_jsx_runtime24.jsx)(
          "button",
          {
            onClick: () => {
              const text5 = draftText.trim();
              if (text5.length === 0) return;
              dispatchUpdate({ type: "comments.add", nodeId: props.nodeId, text: text5, createdAt: Date.now() });
              setDraftText("");
            },
            style: buttonStyle2,
            type: "button",
            children: t("editor.meta.comments.action.add")
          }
        )
      ] })
    ] })
  ] });
}
function ToolbarButton(props) {
  return /* @__PURE__ */ (0, import_jsx_runtime24.jsx)(
    "button",
    {
      onMouseDown: (event) => {
        event.preventDefault();
      },
      onClick: (event) => {
        event.preventDefault();
        props.onClick();
      },
      style: {
        border: props.active ? "1px solid rgba(59, 130, 246, 0.85)" : "1px solid transparent",
        background: props.active ? "rgba(59, 130, 246, 0.18)" : "transparent",
        color: "var(--km-text)",
        borderRadius: 8,
        fontSize: 12,
        padding: "4px 8px",
        cursor: "pointer",
        lineHeight: "16px"
      },
      type: "button",
      children: props.label
    }
  );
}
function tryOpenNativeColorPicker(event) {
  const el = event.currentTarget;
  if (typeof el.showPicker !== "function") return;
  try {
    el.showPicker();
  } catch {
  }
}
function normalizeCssColorForInput(input) {
  if (!input) return null;
  const trimmed = input.trim().toLowerCase();
  if (trimmed.startsWith("#")) {
    if (trimmed.length === 4) {
      const r3 = trimmed[1];
      const g2 = trimmed[2];
      const b3 = trimmed[3];
      return `#${r3}${r3}${g2}${g2}${b3}${b3}`;
    }
    if (trimmed.length === 7) return trimmed;
    return null;
  }
  const rgb = trimmed.match(/^rgb\\(\\s*(\\d+)\\s*,\\s*(\\d+)\\s*,\\s*(\\d+)\\s*\\)$/);
  if (!rgb) return null;
  const r2 = clampByte(Number(rgb[1]));
  const g = clampByte(Number(rgb[2]));
  const b2 = clampByte(Number(rgb[3]));
  return `#${toHex(r2)}${toHex(g)}${toHex(b2)}`;
}
function clampByte(value) {
  if (!Number.isFinite(value)) return 0;
  return Math.max(0, Math.min(255, Math.round(value)));
}
function toHex(value) {
  const hex = value.toString(16);
  return hex.length === 1 ? `0${hex}` : hex;
}

// ../react/src/mindmap-editor/overlays/node-plaintext-editor-overlay.tsx
var import_react22 = __toESM(require_react(), 1);
var import_jsx_runtime25 = __toESM(require_jsx_runtime(), 1);
function NodePlainTextEditorOverlay(props) {
  const [value, setValue] = (0, import_react22.useState)(props.initialText);
  const textareaRef = (0, import_react22.useRef)(null);
  const [themeVars, setThemeVars] = (0, import_react22.useState)(null);
  const [canvasSize, setCanvasSize] = (0, import_react22.useState)(null);
  const isAiCoWritePending = (() => {
    if (props.kind !== "node") return false;
    const node = props.core.getNode(props.entityId);
    const data = node?.data;
    if (!data || typeof data !== "object" || Array.isArray(data)) return false;
    const raw = data.kmindAiCoWrite;
    if (!raw || typeof raw !== "object" || Array.isArray(raw)) return false;
    const schemaVersion = raw.schemaVersion;
    const state = raw.state;
    if (schemaVersion !== 1) return false;
    return state === "generating" || state === "suggested";
  })();
  (0, import_react22.useEffect)(() => {
    setValue(props.initialText);
  }, [props.initialText]);
  (0, import_react22.useLayoutEffect)(() => {
    if (typeof window === "undefined") return;
    const el = props.canvasRef.current;
    if (!el) return;
    try {
      const computed = window.getComputedStyle(el);
      const vars = {};
      for (const name of ["--km-bg", "--km-panel", "--km-text", "--km-muted", "--km-border"]) {
        const current = computed.getPropertyValue(name).trim();
        if (!current) continue;
        vars[name] = current;
      }
      setThemeVars(Object.keys(vars).length > 0 ? vars : null);
    } catch {
    }
  }, [props.canvasRef]);
  (0, import_react22.useLayoutEffect)(() => {
    if (typeof window === "undefined") return;
    const el = props.canvasRef.current;
    if (!el) return;
    const resizeObserver = typeof ResizeObserver === "function" ? new ResizeObserver(() => {
      setCanvasSize({ width: el.clientWidth, height: el.clientHeight });
    }) : null;
    setCanvasSize({ width: el.clientWidth, height: el.clientHeight });
    resizeObserver?.observe(el);
    return () => resizeObserver?.disconnect();
  }, [props.canvasRef]);
  (0, import_react22.useLayoutEffect)(() => {
    const focusEditor = () => {
      const el = textareaRef.current;
      if (!el) return false;
      try {
        el.focus({ preventScroll: true });
      } catch {
        try {
          el.focus();
        } catch {
          return false;
        }
      }
      try {
        el.select();
      } catch {
      }
      props.requestSoftKeyboard?.();
      return true;
    };
    focusEditor();
    const raf = typeof requestAnimationFrame === "function" ? requestAnimationFrame : (fn) => setTimeout(fn, 0);
    const caf = typeof cancelAnimationFrame === "function" ? cancelAnimationFrame : clearTimeout;
    const handle = raf(() => {
      focusEditor();
    });
    return () => caf(handle);
  }, [props.requestSoftKeyboard]);
  const clampedBounds = (0, import_react22.useMemo)(() => {
    const width = Math.max(140, props.bounds.width);
    const height = Math.max(44, props.bounds.height);
    const canvasWidth = canvasSize?.width ?? Number.POSITIVE_INFINITY;
    const canvasHeight = canvasSize?.height ?? Number.POSITIVE_INFINITY;
    const left = Math.min(Math.max(12, props.bounds.left), Math.max(12, canvasWidth - width - 12));
    const top = Math.min(Math.max(12, props.bounds.top), Math.max(12, canvasHeight - height - 12));
    return { left, top, width, height };
  }, [canvasSize?.height, canvasSize?.width, props.bounds.height, props.bounds.left, props.bounds.top, props.bounds.width]);
  const commit = (0, import_react22.useCallback)(() => {
    const text5 = value.trimEnd();
    if (props.kind === "node") {
      const nodeId = props.entityId;
      const node = props.core.getNode(nodeId);
      if (!node) {
        props.onCommit();
        return true;
      }
      const data = node.data;
      const raw = data && typeof data === "object" && !Array.isArray(data) ? data.kmindAiCoWrite : void 0;
      const isAiPending = (() => {
        if (!raw || typeof raw !== "object" || Array.isArray(raw)) return false;
        const schemaVersion = raw.schemaVersion;
        const state = raw.state;
        if (schemaVersion !== 1) return false;
        return state === "generating" || state === "suggested";
      })();
      if (isAiPending) {
        const currentData = data && typeof data === "object" && !Array.isArray(data) ? data : null;
        const nextData = (() => {
          if (!currentData || !("kmindAiCoWrite" in currentData)) return currentData;
          const rest = { ...currentData };
          delete rest.kmindAiCoWrite;
          return Object.keys(rest).length > 0 ? rest : null;
        })();
        const batch = props.core.dispatchBatch([
          { type: "set_node_content", payload: { nodeId, content: void 0, plainText: text5 } },
          { type: "set_node_data", payload: { nodeId, data: nextData } }
        ]);
        if (!batch.ok) {
          void props.dialog.alert(batch.error);
          return false;
        }
        props.onCommit();
        return true;
      }
      const result2 = props.core.dispatch({ type: "set_node_content", payload: { nodeId, content: void 0, plainText: text5 } });
      if (!result2.ok) {
        void props.dialog.alert(result2.error);
        return false;
      }
      props.onCommit();
      return true;
    }
    const summaryId = props.entityId;
    const exists = props.core.getState().document.summaries.some((item) => item.id === summaryId);
    if (!exists) {
      props.onCommit();
      return true;
    }
    const result = props.core.dispatch({ type: "set_summary_content", payload: { summaryId, content: void 0, plainText: text5 } });
    if (!result.ok) {
      void props.dialog.alert(result.error);
      return false;
    }
    props.onCommit();
    return true;
  }, [props, value]);
  const onKeyDown = (event) => {
    if (event.key === "Escape") {
      event.preventDefault();
      event.stopPropagation();
      if (isAiCoWritePending && props.kind === "node") {
        props.core.dispatch({ type: "delete_node", payload: { nodeId: props.entityId } });
      }
      props.onCancel();
      return;
    }
    if (event.key === "Enter" && !event.shiftKey) {
      event.preventDefault();
      event.stopPropagation();
      commit();
      return;
    }
    if (event.key === "Tab") {
      event.preventDefault();
      event.stopPropagation();
      commit();
    }
  };
  return /* @__PURE__ */ (0, import_jsx_runtime25.jsx)(
    "div",
    {
      "data-km-plaintext-editor-overlay": "true",
      onPointerDown: (event) => {
        if (event.target !== event.currentTarget) return;
        event.preventDefault();
        event.stopPropagation();
        commit();
      },
      style: {
        position: "absolute",
        inset: 0,
        zIndex: 120,
        background: "rgba(0,0,0,0)",
        ...themeVars ?? {}
      },
      children: /* @__PURE__ */ (0, import_jsx_runtime25.jsx)(
        "div",
        {
          onPointerDown: (event) => {
            event.stopPropagation();
          },
          style: {
            position: "absolute",
            left: clampedBounds.left,
            top: clampedBounds.top,
            width: clampedBounds.width,
            minHeight: clampedBounds.height,
            maxWidth: "min(720px, calc(100% - 24px))",
            borderRadius: 14,
            border: "1px solid var(--km-border)",
            background: "var(--km-panel)",
            boxShadow: "0 18px 36px rgba(15, 23, 42, 0.18)",
            overflow: "hidden",
            display: "flex",
            opacity: isAiCoWritePending ? 0.76 : 1
          },
          children: /* @__PURE__ */ (0, import_jsx_runtime25.jsx)(
            "textarea",
            {
              ref: textareaRef,
              onBlur: () => {
                commit();
              },
              onChange: (event) => setValue(event.target.value),
              onKeyDown,
              spellCheck: false,
              style: {
                flex: 1,
                padding: "10px 12px",
                border: 0,
                outline: "none",
                resize: "none",
                background: "transparent",
                color: "var(--km-text)",
                fontSize: 14,
                fontFamily: "inherit",
                lineHeight: 1.5
              },
              value
            }
          )
        }
      )
    }
  );
}

// ../react/src/mindmap-editor/overlays/node-richtext-editor-overlay.tsx
var import_react23 = __toESM(require_react(), 1);
var import_react_dom5 = __toESM(require_react_dom(), 1);
init_src();

// ../react/src/mindmap-editor/utils/measurer-options.ts
function toMeasurerOptions(args) {
  const layout = args.layout;
  const out = {};
  if (layout) {
    out.fontFamily = layout.fontFamily;
    out.fontSize = layout.fontSize;
    if (typeof layout.fontWeight === "number") out.fontWeight = layout.fontWeight;
    out.lineHeight = layout.lineHeight;
    if (layout.textAlign) out.textAlign = layout.textAlign;
    out.paddingX = layout.paddingX;
    out.paddingY = layout.paddingY;
    if (typeof layout.nodeMinWidth === "number") out.minWidth = layout.nodeMinWidth;
    if (typeof layout.nodeMinHeight === "number") out.minHeight = layout.nodeMinHeight;
  }
  if (typeof args.cssText === "string") out.cssText = args.cssText;
  return Object.keys(out).length > 0 ? out : void 0;
}

// ../react/src/mindmap-editor/utils/scroll-into-view-nearest.ts
function resolveNearestVerticalScrollTop(args) {
  const containerScrollTop = Number.isFinite(args.containerScrollTop) ? Math.max(0, args.containerScrollTop) : 0;
  const containerClientHeight = Number.isFinite(args.containerClientHeight) ? Math.max(0, args.containerClientHeight) : 0;
  const itemTop = Number.isFinite(args.itemTop) ? Math.max(0, args.itemTop) : 0;
  const itemHeight = Number.isFinite(args.itemHeight) ? Math.max(0, args.itemHeight) : 0;
  if (containerClientHeight <= 0 || itemHeight <= 0) return null;
  const containerBottom = containerScrollTop + containerClientHeight;
  const itemBottom = itemTop + itemHeight;
  if (itemTop < containerScrollTop) return itemTop;
  if (itemBottom > containerBottom) return Math.max(0, itemBottom - containerClientHeight);
  return null;
}
function keepElementVerticallyVisible(container, item) {
  if (!container || !item) return;
  const containerRect = container.getBoundingClientRect();
  const itemRect = item.getBoundingClientRect();
  const nextScrollTop = resolveNearestVerticalScrollTop({
    containerScrollTop: container.scrollTop,
    containerClientHeight: container.clientHeight,
    itemTop: itemRect.top - containerRect.top + container.scrollTop,
    itemHeight: itemRect.height
  });
  if (nextScrollTop === null) return;
  if (Math.abs(container.scrollTop - nextScrollTop) < 1) return;
  container.scrollTop = nextScrollTop;
}

// ../react/src/mindmap-editor/overlays/node-richtext-editor-overlay.tsx
var import_jsx_runtime26 = __toESM(require_jsx_runtime(), 1);
var CLOZE_ADVANCED_UI_ENABLED2 = false;
function countPremiumNodes2(value) {
  let formula = 0;
  let cloze = 0;
  const visit = (node) => {
    if (!node || typeof node !== "object") return;
    const record = node;
    const type = typeof record.type === "string" ? record.type : "";
    if (type === "kmindFormula" || type === "kmindFormulaBlock") formula += 1;
    if (type === "kmindCloze") cloze += 1;
    if (Array.isArray(record.content)) {
      for (const child of record.content) visit(child);
    }
  };
  visit(value);
  return { formula, cloze };
}
function NodeRichTextEditorOverlay(props) {
  const {
    active = true,
    entityId,
    entity,
    accessoryContext = "node",
    theme,
    nodeBodyLayout = "classic",
    zoom: zoomRaw,
    maxWidth,
    tabEnterBehavior,
    layoutMode,
    fitWidth = false,
    variant = "overlay",
    measurer,
    buildMeasureHtml,
    bounds,
    canvasRef,
    initialSelection,
    reuseEditorOnContentChange = false,
    slashMenuProviders,
    premiumCapabilities,
    onPremiumFeatureBlocked,
    onDraftSizeChange,
    onNavigateOut,
    onCommit,
    onRequestAddChild,
    onRequestAddSibling,
    onCancel
  } = props;
  const zoom = typeof zoomRaw === "number" && Number.isFinite(zoomRaw) && zoomRaw > 0 ? zoomRaw : 1;
  const effectivePremium = premiumCapabilities ?? {
    canCreateBacklinks: true,
    canInsertFormula: true,
    canInsertCloze: true,
    canCreateComments: true,
    canInsertSiyuanDocLink: true
  };
  const rootRef = (0, import_react23.useRef)(null);
  const toolbarRef = (0, import_react23.useRef)(null);
  const lastToolbarPointerDownAtRef = (0, import_react23.useRef)(0);
  const lastSelectionRef = (0, import_react23.useRef)(null);
  const measureRafRef = (0, import_react23.useRef)(null);
  const [measuredSize, setMeasuredSize] = (0, import_react23.useState)({ width: bounds.width, height: bounds.height });
  const lastDraftSizeRef = (0, import_react23.useRef)(null);
  const loadedContentKeyRef = (0, import_react23.useRef)(null);
  const isDark = theme?.variantId === "dark";
  const presentation = useWorkspacePresentation();
  const mobileRichTextAccessory = useMobileRichTextAccessoryBridge();
  const hideFloatingToolbar = mobileRichTextAccessory.hasConsumer && presentation.isCompact && presentation.coarsePointer;
  const tokens = theme?.layout;
  const paint = theme?.paint;
  const shape = theme?.nodeShape;
  const editorFill = paint?.nodeFillSelected ?? paint?.nodeFill ?? paint?.panel ?? "var(--km-panel)";
  const isInline2 = variant === "inline";
  const isEditorActive = active && Boolean(entity);
  const layoutFontFamily = tokens?.fontFamily ?? nodeFontFamily;
  const layoutFontSize = tokens?.fontSize ?? nodeFontSize;
  const layoutFontWeight = tokens?.fontWeight ?? 400;
  const layoutLineHeight = tokens?.lineHeight ?? nodeLineHeight;
  const layoutTextAlign = tokens?.textAlign ?? "left";
  const layoutPaddingX = tokens?.paddingX ?? nodePaddingX;
  const layoutPaddingY = tokens?.paddingY ?? nodePaddingY;
  const scaledFontSize = layoutFontSize * zoom;
  const scaledPaddingX = layoutPaddingX * zoom;
  const scaledPaddingY = layoutPaddingY * zoom;
  const scaledStrokeWidth = resolveNodeStrokeWidth(shape) * zoom;
  const scaledBorderRadius = resolveBorderRadius(shape, measuredSize.width / zoom, measuredSize.height / zoom) * zoom;
  const scaledSafeInsets = (0, import_react23.useMemo)(() => {
    if (nodeBodyLayout !== "card-v1") return { x: 0, y: 0 };
    const width = measuredSize.width / zoom;
    const height = measuredSize.height / zoom;
    if (!(width > 0) || !(height > 0)) return { x: 0, y: 0 };
    const safe = resolveCardV1NodeShapeSafeInsets(shape, width, height);
    return { x: safe.insetX * zoom, y: safe.insetY * zoom };
  }, [measuredSize.height, measuredSize.width, nodeBodyLayout, shape, zoom]);
  const scaledSafePaddingX = scaledPaddingX + scaledSafeInsets.x;
  const scaledSafePaddingY = scaledPaddingY + scaledSafeInsets.y;
  const buildMeasureHtmlRef = (0, import_react23.useRef)(buildMeasureHtml);
  (0, import_react23.useEffect)(() => {
    buildMeasureHtmlRef.current = buildMeasureHtml;
  }, [buildMeasureHtml]);
  const tryOpenNativeColorPicker2 = (event) => {
    const el = event.currentTarget;
    if (typeof el.showPicker !== "function") return;
    try {
      el.showPicker();
    } catch {
    }
  };
  const initialContent = (0, import_react23.useMemo)(() => {
    return fromKmind({ content: entity?.content, fallbackText: entity?.text ?? "" });
  }, [entity?.content, entity?.text]);
  const reusableInitialContentRef = (0, import_react23.useRef)(null);
  if (reusableInitialContentRef.current === null) {
    reusableInitialContentRef.current = fromKmind({ content: void 0, fallbackText: "" });
  }
  const editorInitialContent = reuseEditorOnContentChange ? reusableInitialContentRef.current : initialContent;
  const tiptapExtensions = (0, import_react23.useMemo)(() => createKmindTiptapExtensions(), []);
  const editorDeps = reuseEditorOnContentChange ? [] : [initialContent];
  const editor = useEditor(
    {
      immediatelyRender: false,
      extensions: tiptapExtensions,
      content: editorInitialContent,
      autofocus: false,
      editorProps: {
        transformPastedHTML: (html) => sanitizeExternalHtml(html),
        attributes: {
          class: "km-node-richtext km-tiptap-editor",
          style: [
            "outline:none",
            `font-family:${layoutFontFamily}`,
            `font-size:${scaledFontSize}px`,
            `font-weight:${layoutFontWeight}`,
            `line-height:${String(layoutLineHeight)}`,
            `text-align:${layoutTextAlign}`,
            "white-space:pre-wrap",
            "word-break:break-word"
          ].join(";")
        }
      }
    },
    editorDeps
  );
  (0, import_react23.useLayoutEffect)(() => {
    if (!editor) return;
    if (!reuseEditorOnContentChange) return;
    if (!isEditorActive) return;
    if (loadedContentKeyRef.current === entityId) return;
    try {
      editor.commands.setContent(initialContent, { emitUpdate: false });
      loadedContentKeyRef.current = entityId;
      lastDraftSizeRef.current = null;
    } catch {
    }
  }, [editor, entityId, initialContent, isEditorActive, reuseEditorOnContentChange]);
  (0, import_react23.useEffect)(() => {
    if (!editor) return;
    const dom = editor.view.dom;
    dom.style.fontFamily = layoutFontFamily;
    dom.style.fontSize = `${scaledFontSize}px`;
    dom.style.fontWeight = String(layoutFontWeight);
    dom.style.lineHeight = String(layoutLineHeight);
    dom.style.textAlign = layoutTextAlign;
  }, [editor, layoutFontFamily, layoutFontWeight, layoutLineHeight, layoutTextAlign, scaledFontSize]);
  (0, import_react23.useEffect)(() => {
    if (!props.editorRef) return;
    props.editorRef.current = editor;
    return () => {
      if (props.editorRef) props.editorRef.current = null;
    };
  }, [editor, props.editorRef]);
  const [lastTextColor, setLastTextColor] = (0, import_react23.useState)("#0f172a");
  const [lastTextBackground, setLastTextBackground] = (0, import_react23.useState)("#fde68a");
  const [linkPopoverOpen, setLinkPopoverOpen] = (0, import_react23.useState)(false);
  const linkAnchorRef = (0, import_react23.useRef)(null);
  const linkPopoverRef = (0, import_react23.useRef)(null);
  const [linkAnchorRect, setLinkAnchorRect] = (0, import_react23.useState)(null);
  const linkRangeRef = (0, import_react23.useRef)(null);
  const [linkHrefDraft, setLinkHrefDraft] = (0, import_react23.useState)("");
  const linkInputRef = (0, import_react23.useRef)(null);
  const [clozePopoverOpen, setClozePopoverOpen] = (0, import_react23.useState)(false);
  const clozeAnchorRef = (0, import_react23.useRef)(null);
  const clozePopoverRef = (0, import_react23.useRef)(null);
  const [clozeAnchorRect, setClozeAnchorRect] = (0, import_react23.useState)(null);
  const clozeRangeRef = (0, import_react23.useRef)(null);
  const clozeIdRef = (0, import_react23.useRef)(null);
  const [clozeStyleDraft, setClozeStyleDraft] = (0, import_react23.useState)("hole");
  const [clozeRevealModeDraft, setClozeRevealModeDraft] = (0, import_react23.useState)("click");
  const [clozeHintDraft, setClozeHintDraft] = (0, import_react23.useState)("");
  const clozeHintRef = (0, import_react23.useRef)(null);
  const [formulaPopoverOpen, setFormulaPopoverOpen] = (0, import_react23.useState)(false);
  const suppressToolbarForFormulaRef = (0, import_react23.useRef)(false);
  const formulaAnchorRef = (0, import_react23.useRef)(null);
  const formulaPopoverRef = (0, import_react23.useRef)(null);
  const [formulaAnchorRect, setFormulaAnchorRect] = (0, import_react23.useState)(null);
  const formulaAnchorKindRef = (0, import_react23.useRef)("toolbar");
  const formulaAnchorPosRef = (0, import_react23.useRef)(null);
  const formulaTargetRef = (0, import_react23.useRef)(null);
  const [formulaLatexDraft, setFormulaLatexDraft] = (0, import_react23.useState)("");
  const [formulaVariantDraft, setFormulaVariantDraft] = (0, import_react23.useState)("inline");
  const formulaInputRef = (0, import_react23.useRef)(null);
  const [slashMenuOpen, setSlashMenuOpen] = (0, import_react23.useState)(false);
  const slashMenuRef = (0, import_react23.useRef)(null);
  const slashMenuListRef = (0, import_react23.useRef)(null);
  const slashMenuItemRefs = (0, import_react23.useRef)(/* @__PURE__ */ new Map());
  const slashMenuStartPosRef = (0, import_react23.useRef)(null);
  const [slashMenuAnchorRect, setSlashMenuAnchorRect] = (0, import_react23.useState)(null);
  const [slashMenuSelectedIndex, setSlashMenuSelectedIndex] = (0, import_react23.useState)(0);
  const [slashMenuQuery, setSlashMenuQuery] = (0, import_react23.useState)("");
  const [slashMenuDynamicItems, setSlashMenuDynamicItems] = (0, import_react23.useState)([]);
  const applyLink = () => {
    if (!editor) return;
    const href = linkHrefDraft.trim();
    const range = linkRangeRef.current;
    if (!href) {
      const chain2 = editor.chain().focus();
      const chainWithSelection2 = range ? chain2.setTextSelection(range) : chain2;
      chainWithSelection2.unsetLink().run();
      setLinkPopoverOpen(false);
      return;
    }
    const chain = editor.chain().focus();
    const chainWithSelection = range ? chain.setTextSelection(range) : chain;
    chainWithSelection.setLink({ href }).run();
    setLinkPopoverOpen(false);
  };
  const removeLink = () => {
    if (!editor) return;
    const range = linkRangeRef.current;
    const chain = editor.chain().focus();
    const chainWithSelection = range ? chain.setTextSelection(range) : chain;
    chainWithSelection.unsetLink().run();
    setLinkPopoverOpen(false);
  };
  const applyCloze = () => {
    if (!editor) return;
    const id = clozeIdRef.current ?? createKmindId("cloze");
    const hint = clozeHintDraft.trim();
    const range = clozeRangeRef.current;
    const chain = editor.chain().focus();
    const chainWithSelection = range ? chain.setTextSelection(range) : chain;
    chainWithSelection.setMark("kmindCloze", {
      id,
      style: clozeStyleDraft,
      revealMode: clozeRevealModeDraft,
      hint: hint.length > 0 ? hint : null
    }).run();
    setClozePopoverOpen(false);
  };
  const removeCloze = () => {
    if (!editor) return;
    const range = clozeRangeRef.current;
    const chain = editor.chain().focus();
    const chainWithSelection = range ? chain.setTextSelection(range) : chain;
    chainWithSelection.unsetMark("kmindCloze").run();
    setClozePopoverOpen(false);
  };
  const toggleClozeFixed = () => {
    if (!editor) return;
    const selection = editor.state.selection;
    const range = selection && !selection.empty ? { from: selection.from, to: selection.to } : lastSelectionRef.current;
    if (!range) return;
    const chain = editor.chain().focus();
    const chainWithSelection = chain.setTextSelection(range);
    if (editor.isActive("kmindCloze")) {
      chainWithSelection.unsetMark("kmindCloze").run();
      return;
    }
    chainWithSelection.setMark("kmindCloze", {
      id: createKmindId("cloze"),
      style: "blur",
      revealMode: "hover",
      hint: null
    }).run();
  };
  const applyFormula = () => {
    if (!editor) return;
    const latex = formulaLatexDraft.trim();
    if (!latex) return;
    const target2 = formulaTargetRef.current;
    if (target2?.mode === "edit") {
      editor.chain().focus().updateAttributes(target2.type, { latex }).run();
      setFormulaPopoverOpen(false);
      return;
    }
    const type = formulaVariantDraft === "block" ? "kmindFormulaBlock" : "kmindFormula";
    if (type === "kmindFormula") {
      editor.chain().focus().insertContent([{ type, attrs: { latex } }, { type: "text", text: " " }]).run();
      setFormulaPopoverOpen(false);
      return;
    }
    editor.chain().focus().insertContent([{ type, attrs: { latex } }, { type: "paragraph" }]).run();
    setFormulaPopoverOpen(false);
  };
  const removeFormula = () => {
    if (!editor) return;
    editor.chain().focus().deleteSelection().run();
    setFormulaPopoverOpen(false);
  };
  const openFormulaPopover = (behavior, options) => {
    if (!editor) return;
    const selection = editor.state.selection;
    const selectedText = selection && !selection.empty ? editor.state.doc.textBetween(selection.from, selection.to, "\n") : "";
    const editingBlock = editor.isActive("kmindFormulaBlock");
    const editingInline = editor.isActive("kmindFormula");
    const targetType = editingBlock ? "kmindFormulaBlock" : "kmindFormula";
    const mode = editingBlock || editingInline ? "edit" : "insert";
    formulaTargetRef.current = { mode, type: targetType };
    const attrs = editingBlock || editingInline ? editor.getAttributes(targetType) : null;
    const currentLatex = typeof attrs?.latex === "string" ? attrs.latex : "";
    setFormulaVariantDraft(mode === "insert" ? options?.variant ?? "inline" : editingBlock ? "block" : "inline");
    setFormulaLatexDraft(mode === "edit" ? currentLatex : selectedText);
    setLinkPopoverOpen(false);
    setClozePopoverOpen(false);
    setFormulaPopoverOpen((prev) => behavior === "toggle" ? !prev : true);
  };
  const openResolvedFormulaPopover = (target2) => {
    if (!editor || !target2) return;
    suppressToolbarForFormulaRef.current = true;
    formulaAnchorKindRef.current = "selection";
    formulaAnchorPosRef.current = target2.pos;
    formulaTargetRef.current = { mode: "edit", type: target2.type };
    editor.chain().focus().setNodeSelection(target2.pos).run();
    setFormulaVariantDraft(target2.variant);
    setFormulaLatexDraft(target2.latex);
    setFormulaAnchorRect(target2.rect);
    setLinkPopoverOpen(false);
    setClozePopoverOpen(false);
    setToolbar((prev) => prev.visible ? { ...prev, visible: false } : prev);
    setFormulaPopoverOpen(true);
  };
  const resolveFormulaAnchorRect = () => {
    if (!editor) return null;
    if (formulaAnchorKindRef.current === "toolbar") {
      const el = formulaAnchorRef.current;
      if (el) return el.getBoundingClientRect();
    }
    const pos = formulaAnchorPosRef.current ?? editor.state.selection.from;
    try {
      const coords = editor.view.coordsAtPos(pos);
      const width = Math.max(0, coords.right - coords.left);
      const height = Math.max(0, coords.bottom - coords.top);
      if (typeof DOMRect === "undefined") return null;
      return new DOMRect(coords.left, coords.top, width, height);
    } catch {
      return null;
    }
  };
  const notifyBlocked = (feature) => {
    onPremiumFeatureBlocked?.(feature);
  };
  const resolveSlashMenuAnchorRect = () => {
    if (!editor) return null;
    try {
      const coords = editor.view.coordsAtPos(editor.state.selection.from);
      const width = Math.max(0, coords.right - coords.left);
      const height = Math.max(0, coords.bottom - coords.top);
      if (typeof DOMRect === "undefined") return null;
      return new DOMRect(coords.left, coords.top, width, height);
    } catch {
      return null;
    }
  };
  const baseSlashMenuItems = (0, import_react23.useMemo)(
    () => [
      {
        id: "slash.formula.inline",
        title: "Formula (inline)",
        description: "Insert inline formula",
        keywords: ["formula", "math", "latex", "katex"],
        action: { kind: "openFormula", variant: "inline" }
      },
      {
        id: "slash.formula.block",
        title: "Formula (block)",
        description: "Insert block formula",
        keywords: ["formula", "math", "latex", "katex", "block"],
        action: { kind: "openFormula", variant: "block" }
      }
    ],
    []
  );
  const resolveSlashMenuInputRange = () => {
    if (!editor) return null;
    const startPos = slashMenuStartPosRef.current;
    if (startPos === null) return null;
    const endPos = editor.state.selection.from;
    if (!Number.isFinite(startPos) || !Number.isFinite(endPos)) return null;
    if (endPos < startPos) return null;
    return { startPos, endPos };
  };
  const executeSlashMenuItem = (item) => {
    if (!editor) return;
    const range = resolveSlashMenuInputRange();
    setSlashMenuOpen(false);
    if (!range) return;
    const { startPos, endPos } = range;
    editor.chain().focus().deleteRange({ from: startPos, to: endPos }).run();
    if (item.action.kind === "openFormula") {
      if (!effectivePremium.canInsertFormula) {
        notifyBlocked("formula");
        return;
      }
      formulaAnchorKindRef.current = "selection";
      formulaAnchorPosRef.current = startPos;
      openFormulaPopover("open", { variant: item.action.variant });
      return;
    }
    if (item.action.kind === "insertText") {
      editor.chain().focus().insertContent(item.action.text).run();
      return;
    }
    if (item.action.kind === "insertLink") {
      if (item.action.href.startsWith("siyuan://") && !effectivePremium.canInsertSiyuanDocLink) {
        notifyBlocked("siyuanLink");
        return;
      }
      editor.chain().focus().insertContent({
        type: "text",
        text: item.action.text,
        marks: [{ type: "link", attrs: { href: item.action.href } }]
      }).run();
    }
  };
  (0, import_react23.useEffect)(() => {
    if (!linkPopoverOpen && !clozePopoverOpen && !formulaPopoverOpen) return;
    const win = resolveOwnerWindow(rootRef.current) ?? (typeof window !== "undefined" ? window : null);
    if (!win) return;
    const onPointerDownCapture = (event) => {
      const target2 = event.target;
      if (!isNodeLike(target2)) return;
      if (linkPopoverOpen && (linkPopoverRef.current?.contains(target2) || linkAnchorRef.current?.contains(target2)) || clozePopoverOpen && (clozePopoverRef.current?.contains(target2) || clozeAnchorRef.current?.contains(target2)) || formulaPopoverOpen && (formulaPopoverRef.current?.contains(target2) || formulaAnchorRef.current?.contains(target2))) {
        return;
      }
      setLinkPopoverOpen(false);
      setClozePopoverOpen(false);
      setFormulaPopoverOpen(false);
    };
    win.addEventListener("pointerdown", onPointerDownCapture, true);
    return () => win.removeEventListener("pointerdown", onPointerDownCapture, true);
  }, [clozePopoverOpen, formulaPopoverOpen, linkPopoverOpen]);
  (0, import_react23.useEffect)(() => {
    if (!linkPopoverOpen) return;
    const win = resolveOwnerWindow(rootRef.current) ?? (typeof window !== "undefined" ? window : null);
    if (!win) return;
    const update = () => setLinkAnchorRect(linkAnchorRef.current ? linkAnchorRef.current.getBoundingClientRect() : null);
    update();
    win.addEventListener("resize", update);
    win.addEventListener("scroll", update, true);
    return () => {
      win.removeEventListener("resize", update);
      win.removeEventListener("scroll", update, true);
    };
  }, [linkPopoverOpen]);
  (0, import_react23.useEffect)(() => {
    if (!clozePopoverOpen) return;
    const win = resolveOwnerWindow(rootRef.current) ?? (typeof window !== "undefined" ? window : null);
    if (!win) return;
    const update = () => setClozeAnchorRect(clozeAnchorRef.current ? clozeAnchorRef.current.getBoundingClientRect() : null);
    update();
    win.addEventListener("resize", update);
    win.addEventListener("scroll", update, true);
    return () => {
      win.removeEventListener("resize", update);
      win.removeEventListener("scroll", update, true);
    };
  }, [clozePopoverOpen]);
  (0, import_react23.useEffect)(() => {
    if (!formulaPopoverOpen) return;
    const win = resolveOwnerWindow(rootRef.current) ?? (typeof window !== "undefined" ? window : null);
    if (!win) return;
    const update = () => setFormulaAnchorRect(resolveFormulaAnchorRect());
    update();
    win.addEventListener("resize", update);
    win.addEventListener("scroll", update, true);
    return () => {
      win.removeEventListener("resize", update);
      win.removeEventListener("scroll", update, true);
    };
  }, [editor, formulaPopoverOpen]);
  (0, import_react23.useEffect)(() => {
    if (!slashMenuOpen) return;
    const win = resolveOwnerWindow(rootRef.current) ?? (typeof window !== "undefined" ? window : null);
    if (!win) return;
    const update = () => setSlashMenuAnchorRect(resolveSlashMenuAnchorRect());
    const onPointerDownCapture = (event) => {
      const target2 = event.target;
      if (!isNodeLike(target2)) return;
      if (slashMenuRef.current?.contains(target2)) return;
      setSlashMenuOpen(false);
    };
    update();
    win.addEventListener("pointerdown", onPointerDownCapture, true);
    win.addEventListener("resize", update);
    win.addEventListener("scroll", update, true);
    return () => {
      win.removeEventListener("pointerdown", onPointerDownCapture, true);
      win.removeEventListener("resize", update);
      win.removeEventListener("scroll", update, true);
    };
  }, [editor, slashMenuOpen]);
  (0, import_react23.useEffect)(() => {
    if (slashMenuOpen) return;
    slashMenuStartPosRef.current = null;
    slashMenuItemRefs.current.clear();
    setSlashMenuAnchorRect(null);
    setSlashMenuSelectedIndex(0);
    setSlashMenuQuery("");
    setSlashMenuDynamicItems([]);
  }, [slashMenuOpen]);
  (0, import_react23.useEffect)(() => {
    if (!editor) return;
    if (!slashMenuOpen) return;
    const updateQuery = () => {
      const startPos = slashMenuStartPosRef.current;
      if (startPos === null) return;
      const selectionPos = editor.state.selection.from;
      if (selectionPos < startPos) {
        setSlashMenuOpen(false);
        return;
      }
      const raw = editor.state.doc.textBetween(startPos, startPos + 1, "\n", "\n");
      if (raw !== "/") {
        setSlashMenuOpen(false);
        return;
      }
      const query = editor.state.doc.textBetween(startPos + 1, selectionPos, "\n", "\n");
      setSlashMenuQuery(query);
    };
    updateQuery();
    editor.on("update", updateQuery);
    editor.on("selectionUpdate", updateQuery);
    return () => {
      editor.off("update", updateQuery);
      editor.off("selectionUpdate", updateQuery);
    };
  }, [editor, slashMenuOpen]);
  (0, import_react23.useEffect)(() => {
    if (!slashMenuOpen) return;
    const providers = slashMenuProviders ?? [];
    if (providers.length === 0) {
      setSlashMenuDynamicItems([]);
      return;
    }
    let cancelled = false;
    const timeout = window.setTimeout(() => {
      void (async () => {
        const query = slashMenuQuery.trim();
        const limit = 12;
        const results = await Promise.all(
          providers.map(async (provider) => {
            try {
              return await provider.provide({ query, limit });
            } catch {
              return [];
            }
          })
        );
        const merged = [];
        const seen = /* @__PURE__ */ new Set();
        for (const list of results) {
          for (const item of list) {
            if (!item || typeof item.id !== "string") continue;
            if (seen.has(item.id)) continue;
            seen.add(item.id);
            merged.push(item);
            if (merged.length >= limit) break;
          }
          if (merged.length >= limit) break;
        }
        if (cancelled) return;
        setSlashMenuDynamicItems(merged);
      })();
    }, 80);
    return () => {
      cancelled = true;
      window.clearTimeout(timeout);
    };
  }, [slashMenuOpen, slashMenuProviders, slashMenuQuery]);
  (0, import_react23.useEffect)(() => {
    if (!linkPopoverOpen) return;
    const id = window.setTimeout(() => {
      try {
        linkInputRef.current?.focus({ preventScroll: true });
      } catch {
        linkInputRef.current?.focus();
      }
      try {
        linkInputRef.current?.select();
      } catch {
      }
    }, 0);
    return () => window.clearTimeout(id);
  }, [linkPopoverOpen]);
  (0, import_react23.useEffect)(() => {
    if (!clozePopoverOpen) return;
    const id = window.setTimeout(() => {
      try {
        clozeHintRef.current?.focus({ preventScroll: true });
      } catch {
        clozeHintRef.current?.focus();
      }
      try {
        const value = clozeHintRef.current?.value ?? "";
        clozeHintRef.current?.setSelectionRange(value.length, value.length);
      } catch {
      }
    }, 0);
    return () => window.clearTimeout(id);
  }, [clozePopoverOpen]);
  (0, import_react23.useEffect)(() => {
    if (!formulaPopoverOpen) return;
    const id = window.setTimeout(() => {
      try {
        formulaInputRef.current?.focus({ preventScroll: true });
      } catch {
        formulaInputRef.current?.focus();
      }
      try {
        formulaInputRef.current?.select();
      } catch {
      }
    }, 0);
    return () => window.clearTimeout(id);
  }, [formulaPopoverOpen]);
  const applyTextStyle = (patch) => {
    if (!editor) return;
    const selection = editor.state.selection;
    const range = selection && !selection.empty ? { from: selection.from, to: selection.to } : lastSelectionRef.current;
    const current = editor.getAttributes("kmindTextStyle");
    const currentFontSize = typeof current.fontSize === "number" ? current.fontSize : typeof current.fontSize === "string" ? Number.parseFloat(current.fontSize) : null;
    const next = {
      color: typeof current.color === "string" ? current.color : null,
      background: typeof current.background === "string" ? current.background : null,
      fontSize: Number.isFinite(currentFontSize) ? currentFontSize : null,
      fontFamily: current.fontFamily === "sans" || current.fontFamily === "serif" || current.fontFamily === "mono" ? current.fontFamily : null,
      ...patch
    };
    const hasColor = typeof next.color === "string" && next.color.trim().length > 0;
    const hasBackground = typeof next.background === "string" && next.background.trim().length > 0;
    const hasFontSize = typeof next.fontSize === "number" && Number.isFinite(next.fontSize);
    const hasFontFamily = next.fontFamily === "sans" || next.fontFamily === "serif" || next.fontFamily === "mono";
    const chain = editor.chain().focus();
    const chainWithSelection = range ? chain.setTextSelection(range) : chain;
    if (!hasColor && !hasBackground && !hasFontSize && !hasFontFamily) {
      chainWithSelection.unsetMark("kmindTextStyle").run();
      return;
    }
    chainWithSelection.setMark("kmindTextStyle", {
      color: hasColor ? next.color : null,
      background: hasBackground ? next.background : null,
      fontSize: hasFontSize ? next.fontSize : null,
      fontFamily: hasFontFamily ? next.fontFamily : null
    }).run();
  };
  const [toolbar, setToolbar] = (0, import_react23.useState)({
    visible: false,
    x: 0,
    y: 0
  });
  (0, import_react23.useEffect)(() => {
    if (active) return;
    loadedContentKeyRef.current = null;
    setToolbar((prev) => prev.visible ? { ...prev, visible: false } : prev);
    setSlashMenuOpen(false);
    setFormulaPopoverOpen(false);
  }, [active]);
  (0, import_react23.useEffect)(() => {
    if (formulaPopoverOpen) return;
    suppressToolbarForFormulaRef.current = false;
  }, [formulaPopoverOpen]);
  const updateToolbar = () => {
    if (!editor) {
      setToolbar((prev) => prev.visible ? { ...prev, visible: false } : prev);
      return;
    }
    if (suppressToolbarForFormulaRef.current) {
      setToolbar((prev) => prev.visible ? { ...prev, visible: false } : prev);
      return;
    }
    const selection = editor.state.selection;
    const now = typeof Date !== "undefined" ? Date.now() : 0;
    const recentlyInteractedWithToolbar = now - lastToolbarPointerDownAtRef.current < 250;
    const active2 = typeof document !== "undefined" ? document.activeElement : null;
    const focusInToolbar = Boolean(active2 && toolbarRef.current?.contains(active2));
    const keepVisible = focusInToolbar || recentlyInteractedWithToolbar;
    if (selection && !selection.empty) {
      lastSelectionRef.current = { from: selection.from, to: selection.to };
    }
    const selectionEmpty = !selection || selection.empty;
    const range = selectionEmpty ? keepVisible ? lastSelectionRef.current : null : { from: selection.from, to: selection.to };
    if (!range) {
      setToolbar((prev) => prev.visible ? { ...prev, visible: false } : prev);
      return;
    }
    if (!editor.isFocused && !keepVisible) {
      setToolbar((prev) => prev.visible ? { ...prev, visible: false } : prev);
      return;
    }
    const canvas = canvasRef.current;
    if (!canvas) return;
    const canvasRect = canvas.getBoundingClientRect();
    try {
      const start = editor.view.coordsAtPos(range.from);
      const end = editor.view.coordsAtPos(range.to);
      const left = Math.min(start.left, end.left);
      const right = Math.max(start.right, end.right);
      const top = Math.min(start.top, end.top);
      const x5 = (left + right) / 2 - canvasRect.left;
      const y = top - canvasRect.top;
      const safeX = Math.max(12, Math.min(canvasRect.width - 12, x5));
      const safeY = Math.max(12, y);
      setToolbar({ visible: true, x: safeX, y: safeY });
    } catch {
      setToolbar((prev) => prev.visible ? { ...prev, visible: false } : prev);
    }
  };
  (0, import_react23.useEffect)(() => {
    if (!editor) return;
    if (!isEditorActive) {
      setToolbar((prev) => prev.visible ? { ...prev, visible: false } : prev);
      return;
    }
    const onSelection = () => updateToolbar();
    const onTransaction = () => updateToolbar();
    const onFocus = () => updateToolbar();
    const onBlur = ({ event } = {}) => {
      const next = event?.relatedTarget;
      const now = typeof Date !== "undefined" ? Date.now() : 0;
      const recentlyInteractedWithToolbar = now - lastToolbarPointerDownAtRef.current < 250;
      if (recentlyInteractedWithToolbar) return;
      if (next && toolbarRef.current?.contains(next)) return;
      setToolbar((prev) => prev.visible ? { ...prev, visible: false } : prev);
    };
    editor.on("selectionUpdate", onSelection);
    editor.on("transaction", onTransaction);
    editor.on("focus", onFocus);
    editor.on("blur", onBlur);
    updateToolbar();
    return () => {
      editor.off("selectionUpdate", onSelection);
      editor.off("transaction", onTransaction);
      editor.off("focus", onFocus);
      editor.off("blur", onBlur);
    };
  }, [editor, isEditorActive]);
  (0, import_react23.useEffect)(() => {
    if (!editor) return;
    if (!isEditorActive) return;
    const dom = editor.view.dom;
    const onPointerDown = (event) => {
      if (event.button !== 0) return;
      const target2 = event.target;
      if (!isElementLike(target2)) return;
      const formulaView = target2.closest("[data-km-formula-view]");
      if (!formulaView) return;
      const formulaTarget = resolveKmindFormulaTargetFromView(editor, formulaView, {
        clientX: event.clientX,
        clientY: event.clientY
      });
      if (!formulaTarget) return;
      event.preventDefault();
      openResolvedFormulaPopover(formulaTarget);
    };
    dom.addEventListener("pointerdown", onPointerDown);
    return () => dom.removeEventListener("pointerdown", onPointerDown);
  }, [editor, isEditorActive]);
  const initialSelectionKey = initialSelection?.type === "coords" ? `coords:${initialSelection.clientX}:${initialSelection.clientY}` : initialSelection?.type === "relativeCoords" ? `relative:${initialSelection.offsetX}:${initialSelection.offsetY}:${initialSelection.sourceWidth}:${initialSelection.sourceHeight}` : initialSelection?.type ?? "end";
  (0, import_react23.useLayoutEffect)(() => {
    if (!editor) return;
    if (!isEditorActive) return;
    const resolveInitialSelectionCoords = () => {
      if (initialSelection?.type === "coords") {
        return { left: initialSelection.clientX, top: initialSelection.clientY };
      }
      if (initialSelection?.type !== "relativeCoords") return null;
      const editorRect = editor.view.dom?.getBoundingClientRect();
      if (!editorRect || editorRect.width <= 0 || editorRect.height <= 0) return null;
      const sourceWidth = Math.max(1, initialSelection.sourceWidth);
      const rawLeft = initialSelection.offsetX / sourceWidth * editorRect.width;
      const rawTop = initialSelection.offsetY;
      const safeLeft = Math.max(1, Math.min(editorRect.width - 1, rawLeft));
      const safeTop = Math.max(1, Math.min(editorRect.height - 1, rawTop));
      return { left: editorRect.left + safeLeft, top: editorRect.top + safeTop };
    };
    const applyInitialSelection = () => {
      try {
        if (initialSelection?.type === "coords" || initialSelection?.type === "relativeCoords") {
          const coords = resolveInitialSelectionCoords();
          if (!coords) return false;
          const pos = editor.view.posAtCoords(coords);
          if (pos && typeof pos.pos === "number") {
            editor.chain().focus().setTextSelection(pos.pos).run();
            return true;
          }
          return false;
        } else if (initialSelection?.type === "start") {
          editor.commands.focus("start");
          return true;
        } else {
          editor.commands.focus("end");
          return true;
        }
      } catch {
        return false;
      }
    };
    const focusEditor = (allowFallback) => {
      const applied = applyInitialSelection();
      if (!applied && allowFallback) {
        try {
          editor.commands.focus("end");
        } catch {
        }
      }
      const dom = editor.view.dom;
      if (dom) {
        try {
          dom.focus({ preventScroll: true });
        } catch {
          try {
            dom.focus();
          } catch {
          }
        }
      }
      props.requestSoftKeyboard?.();
      return applied;
    };
    const wantsCoordinateSelection = initialSelection?.type === "coords" || initialSelection?.type === "relativeCoords";
    focusEditor(!wantsCoordinateSelection);
    const raf = typeof requestAnimationFrame === "function" ? requestAnimationFrame : (fn) => window.setTimeout(fn, 0);
    const cancel = typeof cancelAnimationFrame === "function" ? cancelAnimationFrame : (id) => window.clearTimeout(id);
    const ids = [];
    let frame = 0;
    const schedule = () => {
      const id = raf(() => {
        frame += 1;
        const applied = focusEditor(!wantsCoordinateSelection || frame >= 3);
        if (wantsCoordinateSelection && !applied && frame < 3) schedule();
      });
      ids.push(id);
    };
    schedule();
    return () => {
      for (const id of ids) cancel(id);
    };
  }, [editor, entityId, initialSelection, initialSelectionKey, isEditorActive, props.requestSoftKeyboard]);
  (0, import_react23.useEffect)(() => {
    if (!isEditorActive) return;
    const win = resolveOwnerWindow(rootRef.current) ?? (typeof window !== "undefined" ? window : null);
    if (!win) return;
    const onPointerDown = (event) => {
      const target2 = event.target;
      if (!isNodeLike(target2)) return;
      if (rootRef.current?.contains(target2)) return;
      if (toolbarRef.current?.contains(target2)) return;
      if (formulaPopoverRef.current?.contains(target2)) return;
      if (isMobileRichTextAccessoryTarget(target2)) return;
      commit();
    };
    win.addEventListener("pointerdown", onPointerDown);
    return () => win.removeEventListener("pointerdown", onPointerDown);
  }, [editor, isEditorActive]);
  const resolveDraft = () => {
    if (!editor) return null;
    const docJson = editor.getJSON();
    const html = editor.getHTML();
    const plainText = editor.getText();
    if (entity?.content?.schemaVersion === 1 && entity.content.kind === "blocks") {
      const nextBlocks = entity.content.blocks.map((block) => {
        if (block.type !== "richtext") return block;
        if (block.engine !== "prosemirror") return block;
        return {
          ...block,
          doc: docJson,
          html
        };
      });
      const hasRichtext = nextBlocks.some((block) => block.type === "richtext");
      if (!hasRichtext) {
        nextBlocks.unshift({
          id: createKmindId("rt"),
          type: "richtext",
          region: "main",
          order: 0,
          engine: "prosemirror",
          doc: docJson,
          html
        });
      }
      return { content: { ...entity.content, blocks: nextBlocks }, plainText, html };
    }
    return { content: toKmind({ doc: docJson, html }), plainText, html };
  };
  const scheduleMeasure = () => {
    if (!editor) return;
    if (!isEditorActive) return;
    if (!measurer) return;
    if (measureRafRef.current !== null) return;
    const raf = typeof requestAnimationFrame === "function" ? requestAnimationFrame : (fn) => setTimeout(fn, 16);
    measureRafRef.current = raf(() => {
      measureRafRef.current = null;
      const draft = resolveDraft();
      if (!draft) return;
      const editableContent = (() => {
        const content = draft.content;
        if (!content || content.schemaVersion !== 1) return content;
        if (content.kind !== "blocks") return content;
        const blocks = content.blocks.filter((b2) => b2.type === "richtext");
        if (blocks.length === content.blocks.length) return content;
        return { ...content, blocks };
      })();
      const html = buildMeasureHtmlRef.current({ content: editableContent, plainText: draft.plainText });
      const baseSize = measurer({
        html,
        text: draft.plainText,
        maxWidth,
        options: toMeasurerOptions({ layout: tokens, cssText: nodeRichTextCssText })
      });
      const size = nodeBodyLayout === "card-v1" ? inflateCardV1NodeSizeForShape(baseSize, shape) : baseSize;
      const scaled = { width: fitWidth ? bounds.width : size.width * zoom, height: size.height * zoom };
      setMeasuredSize((prev) => prev.width === scaled.width && prev.height === scaled.height ? prev : scaled);
      if (layoutMode !== "live-preview") return;
      const last = lastDraftSizeRef.current;
      if (last && last.width === size.width && last.height === size.height) return;
      lastDraftSizeRef.current = size;
      onDraftSizeChange?.(size);
    });
  };
  (0, import_react23.useEffect)(() => {
    if (!isEditorActive) {
      setMeasuredSize({ width: bounds.width, height: bounds.height });
      return;
    }
    scheduleMeasure();
  }, [bounds.width, editor, fitWidth, isEditorActive, measurer, maxWidth, entityId, layoutMode, zoom]);
  (0, import_react23.useEffect)(() => {
    if (!isEditorActive || !editor || !measurer) {
      setMeasuredSize({ width: bounds.width, height: bounds.height });
      return;
    }
    scheduleMeasure();
  }, [bounds.height, bounds.width, editor, fitWidth, isEditorActive, measurer, zoom]);
  (0, import_react23.useEffect)(() => {
    if (!editor) return;
    if (!isEditorActive) return;
    scheduleMeasure();
    const onTransaction = () => scheduleMeasure();
    editor.on("transaction", onTransaction);
    return () => {
      editor.off("transaction", onTransaction);
      if (measureRafRef.current !== null) {
        const caf = typeof cancelAnimationFrame === "function" ? cancelAnimationFrame : clearTimeout;
        caf(measureRafRef.current);
        measureRafRef.current = null;
      }
    };
  }, [bounds.width, editor, fitWidth, isEditorActive, measurer, maxWidth, entityId, layoutMode]);
  const commit = () => {
    const draft = resolveDraft();
    if (!draft) {
      onCancel();
      return false;
    }
    if (editor) {
      const previousCounts = countPremiumNodes2(initialContent);
      const nextCounts = countPremiumNodes2(editor.getJSON());
      if (!effectivePremium.canInsertFormula && nextCounts.formula > previousCounts.formula) {
        notifyBlocked("formula");
        return false;
      }
      if (!effectivePremium.canInsertCloze && nextCounts.cloze > previousCounts.cloze) {
        notifyBlocked("cloze");
        return false;
      }
    }
    return onCommit({ content: draft.content, plainText: draft.plainText });
  };
  const focusCanvasSoon = () => {
    const canvas = canvasRef.current;
    if (!canvas) return;
    const raf = typeof requestAnimationFrame === "function" ? requestAnimationFrame : (fn) => setTimeout(fn, 0);
    raf(() => {
      try {
        canvas.focus();
      } catch {
      }
    });
  };
  const dismissAccessoryRef = (0, import_react23.useRef)(() => {
  });
  dismissAccessoryRef.current = () => {
    const ok = commit();
    if (ok) focusCanvasSoon();
  };
  (0, import_react23.useEffect)(() => {
    if (!editor) return;
    return bindMobileRichTextAccessorySession({
      id: `${accessoryContext}:${entityId}`,
      context: accessoryContext,
      editor,
      dismiss: () => dismissAccessoryRef.current()
    });
  }, [accessoryContext, editor, entityId]);
  (0, import_react23.useEffect)(() => {
    if (!editor) return;
    const notify = () => refreshMobileRichTextAccessory();
    editor.on("selectionUpdate", notify);
    editor.on("transaction", notify);
    editor.on("focus", notify);
    editor.on("blur", notify);
    notify();
    return () => {
      editor.off("selectionUpdate", notify);
      editor.off("transaction", notify);
      editor.off("focus", notify);
      editor.off("blur", notify);
      refreshMobileRichTextAccessory();
    };
  }, [editor]);
  const resolvedSlashMenuItems = (0, import_react23.useMemo)(() => {
    const q2 = slashMenuQuery.trim().toLowerCase();
    const matchesQuery = (item) => {
      if (!q2) return true;
      const keywords = Array.isArray(item.keywords) ? item.keywords.join(" ") : "";
      const haystack = `${item.title} ${item.description ?? ""} ${keywords}`.toLowerCase();
      return haystack.includes(q2);
    };
    return [
      ...baseSlashMenuItems.filter(matchesQuery),
      ...slashMenuDynamicItems
    ];
  }, [baseSlashMenuItems, slashMenuDynamicItems, slashMenuQuery]);
  (0, import_react23.useEffect)(() => {
    if (!slashMenuOpen) return;
    setSlashMenuSelectedIndex((prev) => {
      const max = Math.max(0, resolvedSlashMenuItems.length - 1);
      return Math.max(0, Math.min(max, prev));
    });
  }, [resolvedSlashMenuItems.length, slashMenuOpen]);
  (0, import_react23.useEffect)(() => {
    if (!slashMenuOpen) return;
    setSlashMenuSelectedIndex(0);
  }, [slashMenuOpen, slashMenuQuery]);
  (0, import_react23.useEffect)(() => {
    if (!slashMenuOpen) return;
    const selected = resolvedSlashMenuItems[slashMenuSelectedIndex];
    if (!selected) return;
    const container = slashMenuListRef.current;
    const item = slashMenuItemRefs.current.get(selected.id) ?? null;
    keepElementVerticallyVisible(container, item);
  }, [resolvedSlashMenuItems, slashMenuOpen, slashMenuSelectedIndex]);
  const resolveDraftForNavigation = () => {
    const draft = resolveDraft();
    return draft ? { content: draft.content, plainText: draft.plainText } : null;
  };
  const isAtDocumentTextBoundary = (direction) => {
    if (!editor) return false;
    const selection = editor.state.selection;
    if (!selection.empty) return false;
    const docSize = editor.state.doc.content.size;
    if (direction === "previous") {
      if (selection.from <= 1) return true;
      return editor.state.doc.textBetween(0, selection.from, "\n", "\n").length === 0;
    }
    if (selection.to >= docSize - 1) return true;
    return editor.state.doc.textBetween(selection.to, docSize, "\n", "\n").length === 0;
  };
  const onKeyDownCapture = (event) => {
    const native = event.nativeEvent;
    if ("isComposing" in native && native.isComposing) return;
    if (slashMenuOpen) {
      if (event.key === "Escape") {
        event.preventDefault();
        event.stopPropagation();
        setSlashMenuOpen(false);
        return;
      }
      if (event.key === "ArrowDown" || event.key === "ArrowUp") {
        event.preventDefault();
        event.stopPropagation();
        setSlashMenuSelectedIndex((prev) => {
          const next = event.key === "ArrowDown" ? prev + 1 : prev - 1;
          const max = Math.max(0, resolvedSlashMenuItems.length - 1);
          return Math.max(0, Math.min(max, next));
        });
        return;
      }
      if (event.key === "Enter" || event.key === "Tab") {
        event.preventDefault();
        event.stopPropagation();
        const item = resolvedSlashMenuItems[slashMenuSelectedIndex];
        if (!item) {
          setSlashMenuOpen(false);
          return;
        }
        executeSlashMenuItem(item);
        return;
      }
      return;
    }
    if ((event.key === "ArrowUp" || event.key === "ArrowDown") && onNavigateOut && editor) {
      if (!event.shiftKey && !event.metaKey && !event.ctrlKey && !event.altKey) {
        const direction = event.key === "ArrowUp" ? "previous" : "next";
        if (isAtDocumentTextBoundary(direction)) {
          const draft = resolveDraftForNavigation();
          if (draft && onNavigateOut(direction, draft)) {
            event.preventDefault();
            event.stopPropagation();
            return;
          }
        }
      }
    }
    if (event.key === "Escape") {
      event.preventDefault();
      event.stopPropagation();
      onCancel();
      focusCanvasSoon();
      return;
    }
    if (event.key.toLowerCase() === "m" && (event.metaKey || event.ctrlKey)) {
      if (!editor) return;
      event.preventDefault();
      event.stopPropagation();
      formulaAnchorKindRef.current = "selection";
      formulaAnchorPosRef.current = editor.state.selection.from;
      openFormulaPopover("open");
      return;
    }
    if (event.key === "/" && !event.metaKey && !event.ctrlKey && !event.altKey) {
      if (!editor) return;
      const selection = editor.state.selection;
      if (!selection || !selection.empty) return;
      if (editor.isActive("codeBlock")) return;
      const atLineStart = selection.$from.parentOffset === 0;
      const prevChar = selection.from > 1 ? editor.state.doc.textBetween(selection.from - 1, selection.from, "\n", "\n") : "";
      const afterWhitespace = prevChar.length === 0 || /\s/.test(prevChar);
      if (!atLineStart && !afterWhitespace) return;
      event.preventDefault();
      event.stopPropagation();
      const startPos = selection.from;
      editor.chain().focus().insertContent("/").run();
      slashMenuStartPosRef.current = startPos;
      setSlashMenuSelectedIndex(0);
      setSlashMenuQuery("");
      setSlashMenuOpen(true);
      setSlashMenuAnchorRect(resolveSlashMenuAnchorRect());
      return;
    }
    if (event.key === "Enter" && event.shiftKey) {
      if (!editor) return;
      event.preventDefault();
      event.stopPropagation();
      if (editor.isActive("codeBlock")) {
        editor.chain().focus().insertContent("\n").run();
        return;
      }
      editor.chain().focus().setHardBreak().run();
      return;
    }
    if (event.key === "Enter" && event.altKey) {
      if (!editor) return;
      if (editor.isActive("codeBlock")) return;
      event.preventDefault();
      event.stopPropagation();
      if (editor.can().splitBlock()) {
        editor.chain().focus().splitBlock().run();
      }
      return;
    }
    if (event.key === "Enter" && (event.metaKey || event.ctrlKey)) {
      event.preventDefault();
      event.stopPropagation();
      const ok = commit();
      if (ok) focusCanvasSoon();
      return;
    }
    if (event.key === "Enter") {
      event.preventDefault();
      event.stopPropagation();
      const ok = commit();
      if (!ok) return;
      if (tabEnterBehavior === "create-next") {
        onRequestAddSibling();
        return;
      }
      focusCanvasSoon();
      return;
    }
    if (event.key === "Tab") {
      event.preventDefault();
      event.stopPropagation();
      const ok = commit();
      if (!ok) return;
      if (tabEnterBehavior === "create-next") {
        onRequestAddChild();
        return;
      }
      focusCanvasSoon();
      return;
    }
  };
  const toolbarNode = !hideFloatingToolbar && toolbar.visible && editor ? /* @__PURE__ */ (0, import_jsx_runtime26.jsxs)(
    "div",
    {
      ref: toolbarRef,
      onPointerDownCapture: () => {
        lastToolbarPointerDownAtRef.current = Date.now();
      },
      style: {
        position: "absolute",
        left: toolbar.x,
        top: toolbar.y,
        transform: "translate(-50%, calc(-100% - 10px))",
        background: isDark ? "rgba(15, 23, 42, 0.92)" : "rgba(255, 255, 255, 0.96)",
        border: isDark ? "1px solid rgba(148, 163, 184, 0.22)" : "1px solid rgba(148, 163, 184, 0.38)",
        borderRadius: 10,
        padding: "6px 6px",
        display: "flex",
        gap: 4,
        alignItems: "center",
        boxShadow: "0 10px 24px rgba(15, 23, 42, 0.18)",
        zIndex: 50,
        userSelect: "none"
      },
      children: [
        (() => {
          const attrs = editor.getAttributes("kmindTextStyle");
          const activeColor = typeof attrs.color === "string" ? attrs.color : "";
          const activeBackground = typeof attrs.background === "string" ? attrs.background : "";
          const activeFontFamily = attrs.fontFamily === "sans" || attrs.fontFamily === "serif" || attrs.fontFamily === "mono" ? attrs.fontFamily : "";
          const activeFontSize = typeof attrs.fontSize === "number" ? attrs.fontSize : typeof attrs.fontSize === "string" ? Number.parseFloat(attrs.fontSize) : NaN;
          const displayColor = (activeColor.trim().length > 0 ? normalizeCssColorForInput2(activeColor) : null) ?? lastTextColor;
          const displayBackground = (activeBackground.trim().length > 0 ? normalizeCssColorForInput2(activeBackground) : null) ?? lastTextBackground;
          return /* @__PURE__ */ (0, import_jsx_runtime26.jsxs)(import_jsx_runtime26.Fragment, { children: [
            /* @__PURE__ */ (0, import_jsx_runtime26.jsx)(
              ToolbarButton2,
              {
                active: editor.isActive("bold"),
                label: "B",
                onClick: () => editor.chain().focus().toggleBold().run()
              }
            ),
            /* @__PURE__ */ (0, import_jsx_runtime26.jsx)(
              ToolbarButton2,
              {
                active: editor.isActive("italic"),
                label: "I",
                onClick: () => editor.chain().focus().toggleItalic().run()
              }
            ),
            /* @__PURE__ */ (0, import_jsx_runtime26.jsx)(
              ToolbarButton2,
              {
                active: editor.isActive("underline"),
                label: "U",
                onClick: () => editor.chain().focus().toggleMark("underline").run()
              }
            ),
            /* @__PURE__ */ (0, import_jsx_runtime26.jsx)(
              ToolbarButton2,
              {
                active: editor.isActive("strike"),
                label: "S",
                onClick: () => editor.chain().focus().toggleStrike().run()
              }
            ),
            /* @__PURE__ */ (0, import_jsx_runtime26.jsx)(
              ToolbarButton2,
              {
                active: editor.isActive("code"),
                label: "</>",
                onClick: () => editor.chain().focus().toggleCode().run()
              }
            ),
            /* @__PURE__ */ (0, import_jsx_runtime26.jsx)(
              ToolbarButton2,
              {
                active: editor.isActive("codeBlock"),
                label: "Block",
                onClick: () => editor.chain().focus().toggleCodeBlock().run()
              }
            ),
            /* @__PURE__ */ (0, import_jsx_runtime26.jsx)("span", { style: { height: 16, width: 1, background: isDark ? "rgba(148, 163, 184, 0.22)" : "rgba(148, 163, 184, 0.38)" } }),
            /* @__PURE__ */ (0, import_jsx_runtime26.jsxs)("div", { style: { display: "inline-flex", alignItems: "center", gap: 6 }, children: [
              /* @__PURE__ */ (0, import_jsx_runtime26.jsx)("div", { style: { fontSize: 11, color: "var(--km-muted)" }, children: "A" }),
              /* @__PURE__ */ (0, import_jsx_runtime26.jsx)(
                "input",
                {
                  onChange: (event) => {
                    const color = event.target.value;
                    setLastTextColor(color);
                    applyTextStyle({ color });
                  },
                  onPointerDown: tryOpenNativeColorPicker2,
                  style: {
                    width: 26,
                    height: 22,
                    padding: 0,
                    border: "1px solid rgba(148, 163, 184, 0.40)",
                    borderRadius: 8,
                    background: "transparent",
                    cursor: "pointer"
                  },
                  type: "color",
                  value: displayColor
                }
              ),
              /* @__PURE__ */ (0, import_jsx_runtime26.jsx)(ToolbarButton2, { active: activeColor.trim().length > 0, label: "\xD7", onClick: () => applyTextStyle({ color: null }) })
            ] }),
            /* @__PURE__ */ (0, import_jsx_runtime26.jsxs)("div", { style: { display: "inline-flex", alignItems: "center", gap: 6 }, children: [
              /* @__PURE__ */ (0, import_jsx_runtime26.jsx)("div", { style: { fontSize: 11, color: "var(--km-muted)" }, children: "Bg" }),
              /* @__PURE__ */ (0, import_jsx_runtime26.jsx)(
                "input",
                {
                  onChange: (event) => {
                    const background = event.target.value;
                    setLastTextBackground(background);
                    applyTextStyle({ background });
                  },
                  onPointerDown: tryOpenNativeColorPicker2,
                  style: {
                    width: 26,
                    height: 22,
                    padding: 0,
                    border: "1px solid rgba(148, 163, 184, 0.40)",
                    borderRadius: 8,
                    background: "transparent",
                    cursor: "pointer"
                  },
                  type: "color",
                  value: displayBackground
                }
              ),
              /* @__PURE__ */ (0, import_jsx_runtime26.jsx)(ToolbarButton2, { active: activeBackground.trim().length > 0, label: "\xD7", onClick: () => applyTextStyle({ background: null }) })
            ] }),
            /* @__PURE__ */ (0, import_jsx_runtime26.jsxs)("div", { style: { display: "inline-flex", alignItems: "center", gap: 6 }, children: [
              /* @__PURE__ */ (0, import_jsx_runtime26.jsx)("div", { style: { fontSize: 11, color: "var(--km-muted)" }, children: "Size" }),
              /* @__PURE__ */ (0, import_jsx_runtime26.jsxs)(
                "select",
                {
                  onChange: (event) => {
                    const value = event.target.value;
                    if (value.trim().length === 0) {
                      applyTextStyle({ fontSize: null });
                      return;
                    }
                    const num = Number.parseFloat(value);
                    applyTextStyle({ fontSize: Number.isFinite(num) ? num : null });
                  },
                  style: {
                    border: isDark ? "1px solid rgba(148, 163, 184, 0.22)" : "1px solid rgba(148, 163, 184, 0.38)",
                    background: "transparent",
                    color: "var(--km-text)",
                    borderRadius: 8,
                    fontSize: 12,
                    padding: "4px 6px",
                    cursor: "pointer"
                  },
                  value: Number.isFinite(activeFontSize) ? String(activeFontSize) : "",
                  children: [
                    /* @__PURE__ */ (0, import_jsx_runtime26.jsx)("option", { value: "", children: "auto" }),
                    [10, 11, 12, 13, 14, 16, 18, 20, 24, 28, 32].map((size) => /* @__PURE__ */ (0, import_jsx_runtime26.jsxs)("option", { value: String(size), children: [
                      size,
                      "px"
                    ] }, size))
                  ]
                }
              )
            ] }),
            /* @__PURE__ */ (0, import_jsx_runtime26.jsxs)("div", { style: { display: "inline-flex", alignItems: "center", gap: 6 }, children: [
              /* @__PURE__ */ (0, import_jsx_runtime26.jsx)("div", { style: { fontSize: 11, color: "var(--km-muted)" }, children: "Font" }),
              /* @__PURE__ */ (0, import_jsx_runtime26.jsxs)(
                "select",
                {
                  onChange: (event) => {
                    const value = event.target.value.trim();
                    if (value.length === 0) {
                      applyTextStyle({ fontFamily: null });
                      return;
                    }
                    if (value === "sans" || value === "serif" || value === "mono") {
                      applyTextStyle({ fontFamily: value });
                    }
                  },
                  style: {
                    border: isDark ? "1px solid rgba(148, 163, 184, 0.22)" : "1px solid rgba(148, 163, 184, 0.38)",
                    background: "transparent",
                    color: "var(--km-text)",
                    borderRadius: 8,
                    fontSize: 12,
                    padding: "4px 6px",
                    cursor: "pointer"
                  },
                  value: activeFontFamily,
                  children: [
                    /* @__PURE__ */ (0, import_jsx_runtime26.jsx)("option", { value: "", children: "inherit" }),
                    /* @__PURE__ */ (0, import_jsx_runtime26.jsx)("option", { value: "sans", children: "Sans" }),
                    /* @__PURE__ */ (0, import_jsx_runtime26.jsx)("option", { value: "serif", children: "Serif" }),
                    /* @__PURE__ */ (0, import_jsx_runtime26.jsx)("option", { value: "mono", children: "Mono" })
                  ]
                }
              )
            ] }),
            /* @__PURE__ */ (0, import_jsx_runtime26.jsx)("span", { style: { height: 16, width: 1, background: isDark ? "rgba(148, 163, 184, 0.22)" : "rgba(148, 163, 184, 0.38)" } }),
            /* @__PURE__ */ (0, import_jsx_runtime26.jsx)("span", { ref: linkAnchorRef, style: { display: "inline-flex" }, children: /* @__PURE__ */ (0, import_jsx_runtime26.jsx)(
              ToolbarButton2,
              {
                active: editor.isActive("link"),
                label: "Link",
                onClick: () => {
                  if (!editor) return;
                  const attrs2 = editor.getAttributes("link");
                  const currentHref = typeof attrs2.href === "string" ? attrs2.href : "";
                  setLinkHrefDraft(currentHref);
                  const selection = editor.state.selection;
                  linkRangeRef.current = selection && !selection.empty ? { from: selection.from, to: selection.to } : lastSelectionRef.current;
                  setClozePopoverOpen(false);
                  setLinkPopoverOpen((prev) => !prev);
                }
              }
            ) }),
            /* @__PURE__ */ (0, import_jsx_runtime26.jsx)("span", { ref: clozeAnchorRef, style: { display: "inline-flex" }, children: /* @__PURE__ */ (0, import_jsx_runtime26.jsx)(
              ToolbarButton2,
              {
                active: editor.isActive("kmindCloze"),
                label: "Cloze",
                onClick: () => {
                  if (!editor) return;
                  if (!effectivePremium.canInsertCloze && !editor.isActive("kmindCloze")) {
                    notifyBlocked("cloze");
                    return;
                  }
                  setLinkPopoverOpen(false);
                  setClozePopoverOpen(false);
                  toggleClozeFixed();
                }
              }
            ) }),
            /* @__PURE__ */ (0, import_jsx_runtime26.jsx)("span", { ref: formulaAnchorRef, style: { display: "inline-flex" }, children: /* @__PURE__ */ (0, import_jsx_runtime26.jsx)(
              ToolbarButton2,
              {
                active: editor.isActive("kmindFormula") || editor.isActive("kmindFormulaBlock"),
                label: "Fx",
                onClick: () => {
                  if (!effectivePremium.canInsertFormula && !(editor.isActive("kmindFormula") || editor.isActive("kmindFormulaBlock"))) {
                    notifyBlocked("formula");
                    return;
                  }
                  formulaAnchorKindRef.current = "toolbar";
                  formulaAnchorPosRef.current = editor.state.selection.from;
                  openFormulaPopover("toggle");
                }
              }
            ) })
          ] });
        })(),
        linkPopoverOpen && linkAnchorRect ? /* @__PURE__ */ (0, import_jsx_runtime26.jsxs)(
          "div",
          {
            ref: linkPopoverRef,
            onPointerDownCapture: (event) => event.stopPropagation(),
            style: {
              position: "absolute",
              left: (() => {
                const toolbarRect = toolbarRef.current?.getBoundingClientRect();
                if (!toolbarRect) return 0;
                return linkAnchorRect.left - toolbarRect.left + linkAnchorRect.width / 2;
              })(),
              top: (() => {
                const toolbarRect = toolbarRef.current?.getBoundingClientRect();
                if (!toolbarRect) return 0;
                return linkAnchorRect.bottom - toolbarRect.top + 10;
              })(),
              transform: "translate(-50%, 0)",
              width: 320,
              padding: 10,
              borderRadius: 12,
              border: isDark ? "1px solid rgba(148, 163, 184, 0.22)" : "1px solid rgba(148, 163, 184, 0.38)",
              background: isDark ? "rgba(15, 23, 42, 0.96)" : "rgba(255, 255, 255, 0.98)",
              boxShadow: "0 18px 36px rgba(15, 23, 42, 0.18)",
              zIndex: 80
            },
            children: [
              /* @__PURE__ */ (0, import_jsx_runtime26.jsx)("div", { style: { fontSize: 11, color: "var(--km-muted)", marginBottom: 8 }, children: "Link" }),
              /* @__PURE__ */ (0, import_jsx_runtime26.jsx)(
                "input",
                {
                  ref: linkInputRef,
                  onChange: (event) => setLinkHrefDraft(event.target.value),
                  onKeyDown: (event) => {
                    if (event.key === "Escape") {
                      event.preventDefault();
                      event.stopPropagation();
                      setLinkPopoverOpen(false);
                      return;
                    }
                    if (event.key === "Enter") {
                      event.preventDefault();
                      event.stopPropagation();
                      applyLink();
                    }
                  },
                  placeholder: "https://...",
                  style: {
                    width: "100%",
                    border: isDark ? "1px solid rgba(148, 163, 184, 0.22)" : "1px solid rgba(148, 163, 184, 0.38)",
                    background: "transparent",
                    color: "var(--km-text)",
                    borderRadius: 10,
                    padding: "8px 10px",
                    outline: "none"
                  },
                  value: linkHrefDraft
                }
              ),
              /* @__PURE__ */ (0, import_jsx_runtime26.jsxs)("div", { style: { display: "flex", justifyContent: "flex-end", gap: 8, marginTop: 10 }, children: [
                /* @__PURE__ */ (0, import_jsx_runtime26.jsx)(
                  "button",
                  {
                    onClick: removeLink,
                    style: {
                      border: "1px solid rgba(148, 163, 184, 0.34)",
                      background: "transparent",
                      borderRadius: 10,
                      padding: "6px 10px",
                      fontSize: 12,
                      color: "var(--km-text)",
                      cursor: "pointer",
                      opacity: editor.isActive("link") ? 1 : 0.55
                    },
                    type: "button",
                    children: "Remove"
                  }
                ),
                /* @__PURE__ */ (0, import_jsx_runtime26.jsx)(
                  "button",
                  {
                    onClick: applyLink,
                    style: {
                      border: "1px solid rgba(59, 130, 246, 0.85)",
                      background: "rgba(59, 130, 246, 0.18)",
                      borderRadius: 10,
                      padding: "6px 10px",
                      fontSize: 12,
                      color: "var(--km-text)",
                      cursor: "pointer"
                    },
                    type: "button",
                    children: "Apply"
                  }
                )
              ] })
            ]
          }
        ) : null,
        CLOZE_ADVANCED_UI_ENABLED2 && clozePopoverOpen && clozeAnchorRect ? /* @__PURE__ */ (0, import_jsx_runtime26.jsxs)(
          "div",
          {
            ref: clozePopoverRef,
            onPointerDownCapture: (event) => event.stopPropagation(),
            style: {
              position: "absolute",
              left: (() => {
                const toolbarRect = toolbarRef.current?.getBoundingClientRect();
                if (!toolbarRect) return 0;
                return clozeAnchorRect.left - toolbarRect.left + clozeAnchorRect.width / 2;
              })(),
              top: (() => {
                const toolbarRect = toolbarRef.current?.getBoundingClientRect();
                if (!toolbarRect) return 0;
                return clozeAnchorRect.bottom - toolbarRect.top + 10;
              })(),
              transform: "translate(-50%, 0)",
              width: 360,
              padding: 10,
              borderRadius: 12,
              border: isDark ? "1px solid rgba(148, 163, 184, 0.22)" : "1px solid rgba(148, 163, 184, 0.38)",
              background: isDark ? "rgba(15, 23, 42, 0.96)" : "rgba(255, 255, 255, 0.98)",
              boxShadow: "0 18px 36px rgba(15, 23, 42, 0.18)",
              zIndex: 80
            },
            children: [
              /* @__PURE__ */ (0, import_jsx_runtime26.jsx)("div", { style: { fontSize: 11, color: "var(--km-muted)", marginBottom: 8 }, children: "Cloze" }),
              /* @__PURE__ */ (0, import_jsx_runtime26.jsxs)("div", { style: { display: "flex", gap: 8, flexWrap: "wrap" }, children: [
                /* @__PURE__ */ (0, import_jsx_runtime26.jsxs)("label", { style: { display: "flex", flexDirection: "column", gap: 6, flex: "1 1 120px" }, children: [
                  /* @__PURE__ */ (0, import_jsx_runtime26.jsx)("div", { style: { fontSize: 11, color: "var(--km-muted)" }, children: "Style" }),
                  /* @__PURE__ */ (0, import_jsx_runtime26.jsxs)(
                    "select",
                    {
                      onChange: (event) => setClozeStyleDraft(event.target.value === "blur" ? "blur" : "hole"),
                      style: {
                        border: isDark ? "1px solid rgba(148, 163, 184, 0.22)" : "1px solid rgba(148, 163, 184, 0.38)",
                        background: "transparent",
                        color: "var(--km-text)",
                        borderRadius: 10,
                        padding: "8px 10px",
                        cursor: "pointer"
                      },
                      value: clozeStyleDraft,
                      children: [
                        /* @__PURE__ */ (0, import_jsx_runtime26.jsx)("option", { value: "hole", children: "hole" }),
                        /* @__PURE__ */ (0, import_jsx_runtime26.jsx)("option", { value: "blur", children: "blur" })
                      ]
                    }
                  )
                ] }),
                /* @__PURE__ */ (0, import_jsx_runtime26.jsxs)("label", { style: { display: "flex", flexDirection: "column", gap: 6, flex: "1 1 120px" }, children: [
                  /* @__PURE__ */ (0, import_jsx_runtime26.jsx)("div", { style: { fontSize: 11, color: "var(--km-muted)" }, children: "Reveal" }),
                  /* @__PURE__ */ (0, import_jsx_runtime26.jsxs)(
                    "select",
                    {
                      onChange: (event) => {
                        const value = event.target.value;
                        setClozeRevealModeDraft(value === "hover" ? "hover" : value === "manual" ? "manual" : "click");
                      },
                      style: {
                        border: isDark ? "1px solid rgba(148, 163, 184, 0.22)" : "1px solid rgba(148, 163, 184, 0.38)",
                        background: "transparent",
                        color: "var(--km-text)",
                        borderRadius: 10,
                        padding: "8px 10px",
                        cursor: "pointer"
                      },
                      value: clozeRevealModeDraft,
                      children: [
                        /* @__PURE__ */ (0, import_jsx_runtime26.jsx)("option", { value: "click", children: "click" }),
                        /* @__PURE__ */ (0, import_jsx_runtime26.jsx)("option", { value: "hover", children: "hover" }),
                        /* @__PURE__ */ (0, import_jsx_runtime26.jsx)("option", { value: "manual", children: "manual" })
                      ]
                    }
                  )
                ] })
              ] }),
              /* @__PURE__ */ (0, import_jsx_runtime26.jsxs)("label", { style: { display: "flex", flexDirection: "column", gap: 6, marginTop: 10 }, children: [
                /* @__PURE__ */ (0, import_jsx_runtime26.jsx)("div", { style: { fontSize: 11, color: "var(--km-muted)" }, children: "Hint" }),
                /* @__PURE__ */ (0, import_jsx_runtime26.jsx)(
                  "input",
                  {
                    ref: clozeHintRef,
                    onChange: (event) => setClozeHintDraft(event.target.value),
                    onKeyDown: (event) => {
                      if (event.key === "Escape") {
                        event.preventDefault();
                        event.stopPropagation();
                        setClozePopoverOpen(false);
                        return;
                      }
                      if (event.key === "Enter") {
                        event.preventDefault();
                        event.stopPropagation();
                        applyCloze();
                      }
                    },
                    placeholder: "optional",
                    style: {
                      width: "100%",
                      border: isDark ? "1px solid rgba(148, 163, 184, 0.22)" : "1px solid rgba(148, 163, 184, 0.38)",
                      background: "transparent",
                      color: "var(--km-text)",
                      borderRadius: 10,
                      padding: "8px 10px",
                      outline: "none"
                    },
                    value: clozeHintDraft
                  }
                )
              ] }),
              /* @__PURE__ */ (0, import_jsx_runtime26.jsxs)("div", { style: { display: "flex", justifyContent: "flex-end", gap: 8, marginTop: 10 }, children: [
                /* @__PURE__ */ (0, import_jsx_runtime26.jsx)(
                  "button",
                  {
                    onClick: removeCloze,
                    style: {
                      border: "1px solid rgba(148, 163, 184, 0.34)",
                      background: "transparent",
                      borderRadius: 10,
                      padding: "6px 10px",
                      fontSize: 12,
                      color: "var(--km-text)",
                      cursor: "pointer",
                      opacity: editor.isActive("kmindCloze") ? 1 : 0.55
                    },
                    type: "button",
                    children: "Remove"
                  }
                ),
                /* @__PURE__ */ (0, import_jsx_runtime26.jsx)(
                  "button",
                  {
                    onClick: applyCloze,
                    style: {
                      border: "1px solid rgba(59, 130, 246, 0.85)",
                      background: "rgba(59, 130, 246, 0.18)",
                      borderRadius: 10,
                      padding: "6px 10px",
                      fontSize: 12,
                      color: "var(--km-text)",
                      cursor: "pointer"
                    },
                    type: "button",
                    children: "Apply"
                  }
                )
              ] })
            ]
          }
        ) : null
      ]
    }
  ) : null;
  const slashMenuNode = slashMenuOpen && slashMenuAnchorRect ? /* @__PURE__ */ (0, import_jsx_runtime26.jsxs)(
    "div",
    {
      ref: slashMenuRef,
      onPointerDownCapture: (event) => event.stopPropagation(),
      style: {
        position: "absolute",
        left: (() => {
          const canvas = canvasRef.current;
          if (!canvas) return 0;
          const canvasRect = canvas.getBoundingClientRect();
          const width = 320;
          const margin = 12;
          const raw = slashMenuAnchorRect.left - canvasRect.left;
          const maxX = Math.max(margin, canvasRect.width - width - margin);
          return Math.max(margin, Math.min(maxX, raw));
        })(),
        top: (() => {
          const canvas = canvasRef.current;
          if (!canvas) return 0;
          const canvasRect = canvas.getBoundingClientRect();
          return slashMenuAnchorRect.bottom - canvasRect.top + 8;
        })(),
        width: 320,
        padding: 6,
        borderRadius: 12,
        border: isDark ? "1px solid rgba(148, 163, 184, 0.22)" : "1px solid rgba(148, 163, 184, 0.38)",
        background: isDark ? "rgba(15, 23, 42, 0.96)" : "rgba(255, 255, 255, 0.98)",
        boxShadow: "0 18px 36px rgba(15, 23, 42, 0.18)",
        zIndex: 95
      },
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime26.jsxs)("div", { style: { display: "flex", alignItems: "center", gap: 10, padding: "2px 6px 6px" }, children: [
          /* @__PURE__ */ (0, import_jsx_runtime26.jsx)("div", { style: { fontSize: 11, color: "var(--km-muted)" }, children: "Commands" }),
          /* @__PURE__ */ (0, import_jsx_runtime26.jsx)(
            "div",
            {
              style: {
                marginLeft: "auto",
                fontSize: 11,
                color: "var(--km-muted)",
                fontFamily: 'ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace',
                whiteSpace: "nowrap",
                overflow: "hidden",
                textOverflow: "ellipsis",
                maxWidth: 180
              },
              title: `/${slashMenuQuery}`,
              children: `/${slashMenuQuery}`
            }
          )
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime26.jsx)("div", { ref: slashMenuListRef, style: { display: "flex", flexDirection: "column", gap: 2, maxHeight: 320, overflowY: "auto" }, children: resolvedSlashMenuItems.length === 0 ? /* @__PURE__ */ (0, import_jsx_runtime26.jsx)("div", { style: { padding: "8px 10px", fontSize: 12, color: "var(--km-muted)" }, children: "No results" }) : resolvedSlashMenuItems.map((item, index) => {
          const icon = (() => {
            if (!item.icon) return null;
            if (item.icon.kind === "image") {
              return /* @__PURE__ */ (0, import_jsx_runtime26.jsx)(
                "img",
                {
                  alt: "",
                  src: item.icon.src,
                  style: { width: 18, height: 18, borderRadius: 5, objectFit: "cover", flex: "0 0 auto" }
                }
              );
            }
            if (item.icon.kind === "text") {
              return /* @__PURE__ */ (0, import_jsx_runtime26.jsx)(
                "div",
                {
                  style: {
                    width: 18,
                    height: 18,
                    borderRadius: 6,
                    display: "inline-flex",
                    alignItems: "center",
                    justifyContent: "center",
                    background: isDark ? "rgba(226, 232, 240, 0.08)" : "rgba(15, 23, 42, 0.06)",
                    color: "var(--km-text)",
                    fontSize: 12,
                    lineHeight: "18px",
                    flex: "0 0 auto"
                  },
                  children: item.icon.text
                }
              );
            }
            if (item.icon.kind === "builtin") {
              const svg = getBuiltinIconSvg(item.icon.iconId) ?? "";
              if (!svg) return null;
              return /* @__PURE__ */ (0, import_jsx_runtime26.jsx)(
                "div",
                {
                  style: {
                    width: 18,
                    height: 18,
                    borderRadius: 6,
                    display: "inline-flex",
                    alignItems: "center",
                    justifyContent: "center",
                    background: isDark ? "rgba(226, 232, 240, 0.08)" : "rgba(15, 23, 42, 0.06)",
                    color: "var(--km-text)",
                    flex: "0 0 auto"
                  },
                  children: /* @__PURE__ */ (0, import_jsx_runtime26.jsx)(
                    "span",
                    {
                      dangerouslySetInnerHTML: { __html: svg },
                      style: { width: 14, height: 14, display: "inline-flex", alignItems: "center", justifyContent: "center" }
                    }
                  )
                }
              );
            }
            return null;
          })();
          return /* @__PURE__ */ (0, import_jsx_runtime26.jsxs)(
            "button",
            {
              ref: (node) => {
                if (node) slashMenuItemRefs.current.set(item.id, node);
                else slashMenuItemRefs.current.delete(item.id);
              },
              onMouseDown: (event) => event.preventDefault(),
              onMouseEnter: () => setSlashMenuSelectedIndex(index),
              onClick: () => executeSlashMenuItem(item),
              style: {
                width: "100%",
                display: "flex",
                justifyContent: "space-between",
                alignItems: "center",
                gap: 10,
                border: "1px solid transparent",
                background: slashMenuSelectedIndex === index ? "rgba(59, 130, 246, 0.14)" : "transparent",
                borderRadius: 10,
                padding: "8px 10px",
                color: "var(--km-text)",
                cursor: "pointer",
                textAlign: "left"
              },
              type: "button",
              children: [
                /* @__PURE__ */ (0, import_jsx_runtime26.jsxs)("div", { style: { display: "flex", alignItems: "center", gap: 10, minWidth: 0 }, children: [
                  icon,
                  /* @__PURE__ */ (0, import_jsx_runtime26.jsxs)("div", { style: { minWidth: 0 }, children: [
                    /* @__PURE__ */ (0, import_jsx_runtime26.jsx)("div", { style: { fontSize: 12, color: "var(--km-text)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }, children: item.title }),
                    item.description ? /* @__PURE__ */ (0, import_jsx_runtime26.jsx)("div", { style: { marginTop: 1, fontSize: 11, color: "var(--km-muted)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }, children: item.description }) : null
                  ] })
                ] }),
                /* @__PURE__ */ (0, import_jsx_runtime26.jsx)("span", { style: { fontSize: 11, color: "var(--km-muted)", flex: "0 0 auto" }, children: "Enter" })
              ]
            },
            item.id
          );
        }) })
      ]
    }
  ) : null;
  const formulaPopoverNode = formulaPopoverOpen && formulaAnchorRect ? /* @__PURE__ */ (0, import_jsx_runtime26.jsx)(
    RichTextFormulaPopover,
    {
      inputRef: formulaInputRef,
      ref: formulaPopoverRef,
      latex: formulaLatexDraft,
      mode: formulaTargetRef.current?.mode ?? "insert",
      onPointerDownCapture: (event) => event.stopPropagation(),
      onApply: applyFormula,
      onClose: () => setFormulaPopoverOpen(false),
      onLatexChange: setFormulaLatexDraft,
      onRemove: removeFormula,
      onVariantChange: setFormulaVariantDraft,
      style: {
        "--km-border": isDark ? "rgba(148, 163, 184, 0.22)" : "rgba(148, 163, 184, 0.38)",
        "--km-panel": isDark ? "rgba(15, 23, 42, 0.96)" : "rgba(255, 255, 255, 0.98)"
      },
      variant: formulaVariantDraft,
      x: (() => {
        const canvas = canvasRef.current;
        if (!canvas) return 0;
        const canvasRect = canvas.getBoundingClientRect();
        return formulaAnchorRect.left - canvasRect.left + formulaAnchorRect.width / 2;
      })(),
      y: (() => {
        const canvas = canvasRef.current;
        if (!canvas) return 0;
        const canvasRect = canvas.getBoundingClientRect();
        return formulaAnchorRect.bottom - canvasRect.top + 10;
      })()
    }
  ) : null;
  return /* @__PURE__ */ (0, import_jsx_runtime26.jsxs)(import_jsx_runtime26.Fragment, { children: [
    /* @__PURE__ */ (0, import_jsx_runtime26.jsxs)(
      "div",
      {
        ref: rootRef,
        onKeyDownCapture,
        style: {
          display: isEditorActive ? void 0 : "none",
          position: "absolute",
          left: bounds.left,
          top: bounds.top,
          width: measuredSize.width,
          height: measuredSize.height,
          boxSizing: "border-box",
          padding: isInline2 ? 0 : `${scaledSafePaddingY}px ${scaledSafePaddingX}px`,
          borderRadius: isInline2 ? 0 : scaledBorderRadius,
          border: isInline2 ? "none" : `${scaledStrokeWidth}px solid ${paint?.nodeStrokeSelected ?? "var(--km-node-stroke-selected)"}`,
          boxShadow: isInline2 ? "none" : "0 6px 16px rgba(15, 23, 42, 0.12)",
          outline: "none",
          background: isInline2 ? "transparent" : editorFill,
          color: paint?.text ?? "var(--km-text)",
          fontFamily: layoutFontFamily,
          fontSize: scaledFontSize,
          fontWeight: layoutFontWeight,
          lineHeight: String(layoutLineHeight),
          textAlign: layoutTextAlign,
          "--km-code-bg": isDark ? "rgba(0, 0, 0, 0.24)" : "rgba(15, 23, 42, 0.06)",
          "--km-code-border": isDark ? "rgba(226, 232, 240, 0.14)" : "rgba(148, 163, 184, 0.35)",
          "--km-code-token-keyword": isDark ? "rgba(196, 181, 253, 0.95)" : "rgba(124, 58, 237, 0.95)",
          "--km-code-token-string": isDark ? "rgba(125, 211, 252, 0.95)" : "rgba(2, 132, 199, 0.95)",
          "--km-code-token-number": isDark ? "rgba(253, 186, 116, 0.95)" : "rgba(234, 88, 12, 0.95)",
          "--km-code-token-comment": isDark ? "rgba(148, 163, 184, 0.78)" : "rgba(100, 116, 139, 0.85)",
          "--km-code-token-property": isDark ? "rgba(147, 197, 253, 0.95)" : "rgba(29, 78, 216, 0.95)",
          "--km-code-token-punct": isDark ? "rgba(226, 232, 240, 0.92)" : "rgba(51, 65, 85, 0.88)",
          overflow: "hidden",
          zIndex: 20
        },
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime26.jsx)("style", { children: nodeRichTextCssText }),
          editor ? /* @__PURE__ */ (0, import_jsx_runtime26.jsx)(EditorContent, { editor }) : null
        ]
      }
    ),
    canvasRef.current ? (0, import_react_dom5.createPortal)(
      /* @__PURE__ */ (0, import_jsx_runtime26.jsxs)(import_jsx_runtime26.Fragment, { children: [
        toolbarNode,
        slashMenuNode,
        formulaPopoverNode
      ] }),
      canvasRef.current
    ) : /* @__PURE__ */ (0, import_jsx_runtime26.jsxs)(import_jsx_runtime26.Fragment, { children: [
      toolbarNode,
      slashMenuNode,
      formulaPopoverNode
    ] })
  ] });
}
function ToolbarButton2(props) {
  return /* @__PURE__ */ (0, import_jsx_runtime26.jsx)(
    "button",
    {
      onMouseDown: (event) => {
        event.preventDefault();
      },
      onClick: (event) => {
        event.preventDefault();
        props.onClick();
      },
      style: {
        border: props.active ? "1px solid rgba(59, 130, 246, 0.85)" : "1px solid transparent",
        background: props.active ? "rgba(59, 130, 246, 0.18)" : "transparent",
        color: "var(--km-text)",
        borderRadius: 8,
        fontSize: 12,
        padding: "4px 8px",
        cursor: "pointer",
        lineHeight: "16px"
      },
      type: "button",
      children: props.label
    }
  );
}
function normalizeCssColorForInput2(input) {
  const value = input.trim();
  if (value.length === 0) return null;
  const hex3 = value.match(/^#([0-9a-f]{3})$/i);
  if (hex3) {
    const [r2, g, b2] = hex3[1].split("");
    return `#${r2}${r2}${g}${g}${b2}${b2}`.toLowerCase();
  }
  const hex6 = value.match(/^#([0-9a-f]{6})$/i);
  if (hex6) return `#${hex6[1]}`.toLowerCase();
  const rgb = value.match(/^rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(,\s*(0|1|0?\.\d+)\s*)?\)$/i);
  if (rgb) {
    const r2 = clampByte2(Number(rgb[1]));
    const g = clampByte2(Number(rgb[2]));
    const b2 = clampByte2(Number(rgb[3]));
    return `#${toHex2(r2)}${toHex2(g)}${toHex2(b2)}`;
  }
  return null;
}
function clampByte2(value) {
  if (!Number.isFinite(value)) return 0;
  return Math.max(0, Math.min(255, Math.round(value)));
}
function toHex2(value) {
  return value.toString(16).padStart(2, "0");
}

// ../react/src/mindmap-editor/overlays/relation-label-editor-overlay.tsx
var import_react25 = __toESM(require_react(), 1);
var import_jsx_runtime27 = __toESM(require_jsx_runtime(), 1);
function RelationLabelEditorOverlay(props) {
  const [value, setValue] = (0, import_react25.useState)(props.initialValue);
  const inputRef = (0, import_react25.useRef)(null);
  const ignoreBlurRef = (0, import_react25.useRef)(false);
  (0, import_react25.useEffect)(() => {
    const input = inputRef.current;
    if (!input) return;
    try {
      input.focus();
      input.select();
    } catch {
    }
  }, []);
  const placement = (0, import_react25.useMemo)(() => {
    const { viewBox, viewportSize, anchor } = props;
    const scaleX = viewBox.width > 0 ? viewportSize.width / viewBox.width : 1;
    const scaleY = viewBox.height > 0 ? viewportSize.height / viewBox.height : 1;
    const zoom = Number.isFinite(scaleX) && Number.isFinite(scaleY) ? Math.max(0.1, Math.min(4, Math.min(scaleX, scaleY))) : 1;
    const left = (anchor.x - viewBox.x) * scaleX;
    const top = (anchor.y - viewBox.y) * scaleY;
    const baseWidth = Math.max(140, Math.min(360, value.length * 8 + 60));
    return { left, top, zoom, baseWidth };
  }, [props.anchor.x, props.anchor.y, props.viewBox.height, props.viewBox.width, props.viewBox.x, props.viewBox.y, props.viewportSize.height, props.viewportSize.width, value.length]);
  return /* @__PURE__ */ (0, import_jsx_runtime27.jsx)(
    "div",
    {
      "data-export-exclude": "true",
      onPointerDownCapture: (event) => {
        event.stopPropagation();
      },
      style: {
        position: "absolute",
        left: placement.left,
        top: placement.top,
        transform: `translate(-50%, -50%) scale(${placement.zoom})`,
        transformOrigin: "center",
        zIndex: 40,
        pointerEvents: "auto"
      },
      children: /* @__PURE__ */ (0, import_jsx_runtime27.jsx)(
        "input",
        {
          ref: inputRef,
          onBlur: () => {
            if (ignoreBlurRef.current) {
              ignoreBlurRef.current = false;
              return;
            }
            props.onCommit(value);
          },
          onChange: (event) => setValue(event.target.value),
          onKeyDown: (event) => {
            if (event.key === "Escape") {
              event.preventDefault();
              event.stopPropagation();
              ignoreBlurRef.current = true;
              props.onCancel();
              return;
            }
            if (event.key === "Enter") {
              event.preventDefault();
              event.stopPropagation();
              ignoreBlurRef.current = true;
              props.onCommit(value);
            }
          },
          style: {
            width: placement.baseWidth,
            maxWidth: 420,
            height: 32,
            boxSizing: "border-box",
            padding: "4px 10px",
            borderRadius: 8,
            border: "1px solid var(--km-border)",
            background: "var(--km-panel)",
            color: "var(--km-text)",
            boxShadow: "0 8px 22px rgba(15, 23, 42, 0.18)",
            outline: "none",
            fontSize: 12,
            lineHeight: "20px"
          },
          type: "text",
          value
        }
      )
    }
  );
}

// ../react/src/mindmap-editor/overlays/selection-toolbar-overlay.tsx
var import_react28 = __toESM(require_react(), 1);
var import_react_dom6 = __toESM(require_react_dom(), 1);
init_src();

// ../react/src/mindmap-editor/utils/hit-test.ts
function clientToWorldPoint(args) {
  const rect = args.svg.getBoundingClientRect();
  if (!rect.width || !rect.height) return null;
  const x5 = args.viewBox.x + (args.clientX - rect.left) / rect.width * args.viewBox.width;
  const y = args.viewBox.y + (args.clientY - rect.top) / rect.height * args.viewBox.height;
  if (!Number.isFinite(x5) || !Number.isFinite(y)) return null;
  return { x: x5, y };
}
function hitTestNodeId(args) {
  const { x: x5, y } = args.world;
  let best = null;
  for (const [nodeIdRaw, rect] of Object.entries(args.layout.nodes)) {
    const nodeId = nodeIdRaw;
    if (args.hiddenNodeIds?.has(nodeId)) continue;
    if (args.ignoreNodeIds?.has(nodeId)) continue;
    if (x5 < rect.x || y < rect.y) continue;
    if (x5 > rect.x + rect.width || y > rect.y + rect.height) continue;
    const area = Math.max(1, rect.width * rect.height);
    if (!best || area < best.area) best = { id: nodeId, area };
  }
  return best?.id ?? null;
}
function hitTestSummaryId(args) {
  const { x: x5, y } = args.world;
  let best = null;
  for (const [summaryIdRaw, rect] of Object.entries(args.layout.summaries)) {
    const summaryId = summaryIdRaw;
    if (args.hiddenSummaryIds?.has(summaryId)) continue;
    if (x5 < rect.x || y < rect.y) continue;
    if (x5 > rect.x + rect.width || y > rect.y + rect.height) continue;
    const area = Math.max(1, rect.width * rect.height);
    if (!best || area < best.area) best = { id: summaryId, area };
  }
  return best?.id ?? null;
}

// ../react/src/mindmap-editor/ui/icon-button.tsx
var import_jsx_runtime28 = __toESM(require_jsx_runtime(), 1);
function IconButton(props) {
  const { iconId, label, size: sizeProp, iconSize: iconSizeProp, showChevron: showChevronProp, type, style: styleProp, ...buttonProps } = props;
  const size = sizeProp ?? 34;
  const iconSize = iconSizeProp ?? 18;
  const showChevron = Boolean(showChevronProp);
  const style2 = {
    height: size,
    width: showChevron ? void 0 : size,
    padding: showChevron ? "0 10px" : 0,
    borderRadius: 10,
    border: "1px solid var(--km-border)",
    background: "var(--km-panel)",
    color: "var(--km-text)",
    fontSize: 12,
    cursor: buttonProps.disabled ? "not-allowed" : "pointer",
    userSelect: "none",
    whiteSpace: "nowrap",
    flexShrink: 0,
    opacity: buttonProps.disabled ? 0.55 : 1,
    display: "inline-flex",
    alignItems: "center",
    justifyContent: "center",
    gap: showChevron ? 6 : 0,
    ...styleProp ?? null
  };
  return /* @__PURE__ */ (0, import_jsx_runtime28.jsxs)(
    "button",
    {
      "aria-label": label,
      title: label,
      ...buttonProps,
      style: style2,
      type: type ?? "button",
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime28.jsx)(Icon, { iconId, size: iconSize }),
        showChevron ? /* @__PURE__ */ (0, import_jsx_runtime28.jsx)("span", { style: { fontSize: 11, opacity: 0.8 }, children: "\u25BE" }) : null
      ]
    }
  );
}

// ../react/src/mindmap-editor/overlays/tags-panel.tsx
var import_react26 = __toESM(require_react(), 1);
var import_jsx_runtime29 = __toESM(require_jsx_runtime(), 1);
var tagsPanelCssText = `
  .km-tags-panel .km-popover-scroll {
    scrollbar-width: thin;
    scrollbar-color: rgba(148, 163, 184, 0.58) transparent;
  }
  .km-tags-panel .km-popover-scroll::-webkit-scrollbar {
    width: 12px;
    height: 12px;
  }
  .km-tags-panel .km-popover-scroll::-webkit-scrollbar-track {
    background: transparent;
  }
  .km-tags-panel .km-popover-scroll::-webkit-scrollbar-thumb {
    background-color: rgba(148, 163, 184, 0.5);
    border-radius: 999px;
    border: 3px solid transparent;
    background-clip: content-box;
  }
  .km-tags-panel .km-popover-scroll:hover::-webkit-scrollbar-thumb {
    background-color: rgba(148, 163, 184, 0.72);
  }
`;
function getNodeTags(doc3, nodeId) {
  const node = doc3?.nodes?.[nodeId];
  if (!node) return [];
  const content = node.content;
  if (!content || content.schemaVersion !== 1) return [];
  if (content.kind !== "blocks") return [];
  const block = content.blocks.find((item) => item.type === "tags") ?? null;
  if (!block) return [];
  return block.tags.map((tag) => ({
    id: typeof tag.id === "string" ? tag.id : "",
    text: typeof tag.text === "string" ? tag.text : "",
    color: typeof tag.color === "string" ? tag.color : void 0
  })).filter((tag) => tag.id.trim().length > 0 && tag.text.trim().length > 0);
}
function TagsPanel(props) {
  const t = useT();
  const rootRef = (0, import_react26.useRef)(null);
  const inputRef = (0, import_react26.useRef)(null);
  const [draftTag, setDraftTag] = (0, import_react26.useState)("");
  const variant = props.variant ?? "floating";
  const showCloseButton = props.showCloseButton ?? variant === "floating";
  const node = props.doc.nodes[props.nodeId] ?? null;
  const readOnly = Boolean(props.readOnly);
  const canEditNode = Boolean(!readOnly && props.dispatchCommand && node && !node.attrs?.locked && !node.attrs?.readonly);
  const canAddTag = Boolean(
    canEditNode && (props.isCommandEnabled ? props.isCommandEnabled("node.tag.add", { nodeId: props.nodeId }) : true)
  );
  const canRemoveTag = Boolean(
    canEditNode && (props.isCommandEnabled ? props.isCommandEnabled("node.tag.remove", { nodeId: props.nodeId }) : true)
  );
  const tags = getNodeTags(props.doc, props.nodeId);
  const duplicateDraft = tags.some((tag) => tag.text.trim() === draftTag.trim());
  const canSubmitDraft = canAddTag && draftTag.trim().length > 0 && !duplicateDraft;
  (0, import_react26.useEffect)(() => {
    if (variant !== "floating") return;
    const win = resolveOwnerWindow(rootRef.current) ?? (typeof window !== "undefined" ? window : null);
    if (!win) return;
    const onPointerDown = (event) => {
      const target2 = event.target;
      if (!isNodeLike(target2)) return;
      const root = rootRef.current;
      if (root && root.contains(target2)) return;
      props.onClose();
    };
    win.addEventListener("pointerdown", onPointerDown, true);
    return () => win.removeEventListener("pointerdown", onPointerDown, true);
  }, [props.onClose, variant]);
  (0, import_react26.useEffect)(() => {
    if (!canAddTag) return;
    const raf = typeof requestAnimationFrame === "function" ? requestAnimationFrame : (fn) => window.setTimeout(fn, 0);
    const caf = typeof cancelAnimationFrame === "function" ? cancelAnimationFrame : (id) => window.clearTimeout(id);
    const handle = raf(() => {
      try {
        inputRef.current?.focus();
      } catch {
      }
    });
    return () => caf(handle);
  }, [canAddTag, props.nodeId]);
  const dispatch = async (commandId, args) => {
    if (!props.dispatchCommand) return;
    await props.dispatchCommand(commandId, args);
  };
  const submitDraft = () => {
    const text5 = draftTag.trim();
    if (!canSubmitDraft || text5.length === 0) return;
    void dispatch("node.tag.add", { nodeId: props.nodeId, text: text5 }).then(() => {
      setDraftTag("");
      try {
        inputRef.current?.focus();
      } catch {
      }
    });
  };
  const cardStyle = variant === "embedded" ? {
    position: "relative",
    left: 0,
    top: 0,
    width: "100%",
    maxHeight: "none",
    overflow: "hidden",
    borderRadius: 0,
    border: "none",
    background: "transparent",
    boxShadow: "none",
    pointerEvents: "auto",
    display: "flex",
    flexDirection: "column",
    minHeight: 0
  } : {
    position: "absolute",
    left: props.x,
    top: props.y,
    width: props.width,
    maxHeight: props.maxHeight,
    overflow: "hidden",
    borderRadius: 14,
    border: "1px solid var(--km-border)",
    background: "var(--km-panel)",
    boxShadow: "0 18px 36px rgba(15, 23, 42, 0.18)",
    pointerEvents: "auto",
    zIndex: 70,
    display: "flex",
    flexDirection: "column",
    minHeight: 0
  };
  const buttonStyle2 = {
    border: "1px solid var(--km-border)",
    background: "transparent",
    borderRadius: 10,
    padding: "6px 10px",
    fontSize: 12,
    color: "var(--km-text)",
    cursor: "pointer"
  };
  const disabledButtonStyle = {
    ...buttonStyle2,
    cursor: "not-allowed",
    opacity: 0.5
  };
  return /* @__PURE__ */ (0, import_jsx_runtime29.jsxs)(
    "div",
    {
      "data-export-exclude": "true",
      className: "km-tags-panel",
      ref: rootRef,
      onPointerEnter: () => props.onHoverChange(true),
      onPointerLeave: () => props.onHoverChange(false),
      style: cardStyle,
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime29.jsx)("style", { children: tagsPanelCssText }),
        /* @__PURE__ */ (0, import_jsx_runtime29.jsxs)(
          "div",
          {
            style: {
              display: "flex",
              alignItems: "center",
              justifyContent: "space-between",
              gap: 10,
              padding: 12,
              borderBottom: "1px solid var(--km-border)",
              background: "rgba(255,255,255,0.04)"
            },
            children: [
              /* @__PURE__ */ (0, import_jsx_runtime29.jsx)("div", { style: { fontSize: 12, fontWeight: 650, color: "var(--km-text)" }, children: t("editor.tags.title") }),
              showCloseButton ? /* @__PURE__ */ (0, import_jsx_runtime29.jsx)("button", { onClick: props.onClose, style: buttonStyle2, type: "button", children: t("editor.meta.action.close") }) : null
            ]
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime29.jsxs)("div", { className: "km-popover-scroll", style: { overflow: "auto", flex: 1, minHeight: 0, maxHeight: variant === "floating" ? props.maxHeight - 54 : void 0 }, children: [
          /* @__PURE__ */ (0, import_jsx_runtime29.jsx)("div", { style: { padding: 10, display: "flex", flexWrap: "wrap", gap: 8 }, children: tags.length === 0 ? /* @__PURE__ */ (0, import_jsx_runtime29.jsx)("div", { style: { fontSize: 12, color: "var(--km-muted)" }, children: t("editor.tags.empty") }) : tags.map((tag) => /* @__PURE__ */ (0, import_jsx_runtime29.jsxs)(
            "div",
            {
              style: {
                display: "inline-flex",
                alignItems: "center",
                gap: 8,
                padding: "0 10px",
                height: 30,
                borderRadius: 999,
                border: "1px solid var(--km-border)",
                background: tag.color ?? "rgba(148,163,184,0.10)",
                color: "var(--km-text)",
                fontSize: 12,
                maxWidth: 240
              },
              children: [
                /* @__PURE__ */ (0, import_jsx_runtime29.jsx)("span", { style: { overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }, children: tag.text }),
                canRemoveTag ? /* @__PURE__ */ (0, import_jsx_runtime29.jsx)(
                  "button",
                  {
                    onClick: () => {
                      void dispatch("node.tag.remove", { nodeId: props.nodeId, tagId: tag.id });
                    },
                    style: {
                      width: 18,
                      height: 18,
                      borderRadius: 999,
                      border: "1px solid var(--km-border)",
                      background: "rgba(255,255,255,0.75)",
                      color: "var(--km-muted)",
                      cursor: "pointer",
                      display: "inline-flex",
                      alignItems: "center",
                      justifyContent: "center",
                      lineHeight: 1
                    },
                    tabIndex: -1,
                    type: "button",
                    children: "x"
                  }
                ) : null
              ]
            },
            tag.id
          )) }),
          canAddTag ? /* @__PURE__ */ (0, import_jsx_runtime29.jsxs)(import_jsx_runtime29.Fragment, { children: [
            /* @__PURE__ */ (0, import_jsx_runtime29.jsx)("div", { style: { height: 1, background: "var(--km-border)" } }),
            /* @__PURE__ */ (0, import_jsx_runtime29.jsxs)("div", { style: { padding: 10, display: "flex", gap: 8 }, children: [
              /* @__PURE__ */ (0, import_jsx_runtime29.jsx)(
                "input",
                {
                  ref: inputRef,
                  onChange: (event) => setDraftTag(event.target.value),
                  onKeyDown: (event) => {
                    if (event.key !== "Enter") return;
                    event.preventDefault();
                    submitDraft();
                  },
                  placeholder: t("editor.tags.input.placeholder"),
                  style: {
                    flex: 1,
                    height: 34,
                    padding: "0 10px",
                    borderRadius: 10,
                    border: "1px solid var(--km-border)",
                    background: "var(--km-panel)",
                    color: "var(--km-text)",
                    fontSize: 12,
                    outline: "none",
                    minWidth: 0
                  },
                  value: draftTag
                }
              ),
              /* @__PURE__ */ (0, import_jsx_runtime29.jsx)(
                "button",
                {
                  disabled: !canSubmitDraft,
                  onClick: submitDraft,
                  style: canSubmitDraft ? buttonStyle2 : disabledButtonStyle,
                  tabIndex: -1,
                  type: "button",
                  children: t("editor.tags.action.add")
                }
              )
            ] })
          ] }) : null
        ] })
      ]
    }
  );
}

// ../react/src/localized-labels.ts
var LAYOUT_LABEL_KEYS = {
  "logical-right": "kmind.label.layout.logical-right",
  "logical-left": "kmind.label.layout.logical-left",
  "tree-down": "kmind.label.layout.tree-down",
  "tree-up": "kmind.label.layout.tree-up",
  "mindmap-both": "kmind.label.layout.mindmap-both",
  "mindmap-both-auto": "kmind.label.layout.mindmap-both-auto",
  "timeline-right": "kmind.label.layout.timeline-right",
  "timeline-down": "kmind.label.layout.timeline-down",
  "fishbone-left": "kmind.label.layout.fishbone-left",
  "fishbone-right": "kmind.label.layout.fishbone-right"
};
var EDGE_ROUTE_LABEL_KEYS = {
  cubic: "kmind.label.edgeRoute.cubic",
  quadratic: "kmind.label.edgeRoute.quadratic",
  "center-quadratic": "kmind.label.edgeRoute.center-quadratic",
  "center-quadratic-tapered": "kmind.label.edgeRoute.center-quadratic-tapered",
  "edge-lead-quadratic": "kmind.label.edgeRoute.edge-lead-quadratic",
  "edge-lead-quadratic-tapered": "kmind.label.edgeRoute.edge-lead-quadratic-tapered",
  "cubic-tail": "kmind.label.edgeRoute.cubic-tail",
  "baseline-fork": "kmind.label.edgeRoute.baseline-fork",
  straight: "kmind.label.edgeRoute.straight",
  orthogonal: "kmind.label.edgeRoute.orthogonal",
  "orthogonal-rounded": "kmind.label.edgeRoute.orthogonal-rounded",
  tapered: "kmind.label.edgeRoute.tapered"
};
var THEME_LABEL_KEYS = {
  "kmind-default": "kmind.label.theme.kmind-default",
  "kmind-material-3-slate": "kmind.label.theme.kmind-material-3-slate",
  "kmind-material-3": "kmind.label.theme.kmind-material-3",
  "kmind-candy-pop": "kmind.label.theme.kmind-candy-pop",
  "kmind-midnight-neon": "kmind.label.theme.kmind-midnight-neon",
  "kmind-rainbow-breeze": "kmind.label.theme.kmind-rainbow-breeze",
  "kmind-baseline-fork-ink": "kmind.label.theme.kmind-baseline-fork-ink",
  "kmind-material-3-rounded-orthogonal-violet": "kmind.label.theme.kmind-material-3-rounded-orthogonal-violet",
  "kmind-material-3-rounded-orthogonal-ocean": "kmind.label.theme.kmind-material-3-rounded-orthogonal-ocean",
  "kmind-material-3-rounded-orthogonal-forest": "kmind.label.theme.kmind-material-3-rounded-orthogonal-forest",
  "kmind-material-3-rounded-orthogonal-citrus": "kmind.label.theme.kmind-material-3-rounded-orthogonal-citrus",
  "kmind-material-3-rounded-orthogonal-rose": "kmind.label.theme.kmind-material-3-rounded-orthogonal-rose",
  "kmind-material-3-rounded-orthogonal-aqua": "kmind.label.theme.kmind-material-3-rounded-orthogonal-aqua"
};
function resolveLocalizedLayoutLabel(t, layout) {
  const key = LAYOUT_LABEL_KEYS[layout];
  return key ? t(key) : String(layout);
}
function resolveLocalizedEdgeRouteLabel(t, route) {
  const key = EDGE_ROUTE_LABEL_KEYS[route];
  return key ? t(key) : String(route);
}
function resolveLocalizedThemePresetName(t, preset) {
  const key = THEME_LABEL_KEYS[preset.id];
  return key ? t(key) : preset.name;
}

// ../react/src/previews/edge-route-preview-svg.tsx
var import_react27 = __toESM(require_react(), 1);
var import_jsx_runtime30 = __toESM(require_jsx_runtime(), 1);
var VIEWBOX_WIDTH = 140;
var VIEWBOX_HEIGHT = 92;
var ROOT_RECT = { x: 28, y: 34, width: 34, height: 24 };
var CHILD_RECTS = [
  { x: 78, y: 14, width: 30, height: 18 },
  { x: 78, y: 60, width: 30, height: 18 }
];
var ROUTE_OPTIONS = {
  quadratic: { lead: 18, tension: 0.58 },
  "edge-lead-quadratic": { lead: 22 },
  "orthogonal-rounded": { radius: 12 },
  "cubic-tail": { gap: 22, offsetScale: 1 },
  "baseline-fork": { lead: 28, baselineOffset: 5, diagonalAngle: 43 }
};
function center(rect) {
  return { x: rect.x + rect.width / 2, y: rect.y + rect.height / 2 };
}
function round22(value) {
  return Math.round(value * 100) / 100;
}
function routeCompactLogicalRightPreviewEdge(from2, to) {
  const start = { x: from2.x + from2.width, y: from2.y + from2.height / 2 };
  const end = { x: to.x, y: to.y + to.height / 2 };
  const lead = Math.max(18, Math.abs(end.x - start.x) * 0.45);
  return `M ${start.x} ${start.y} C ${start.x + lead} ${start.y}, ${end.x - lead} ${end.y}, ${end.x} ${end.y}`;
}
function cubicPoint2(p0, p1, p2, p3, t) {
  const mt = 1 - t;
  const mt2 = mt * mt;
  const t2 = t * t;
  const a2 = mt2 * mt;
  const b2 = 3 * mt2 * t;
  const c = 3 * mt * t2;
  const d2 = t * t2;
  return {
    x: a2 * p0.x + b2 * p1.x + c * p2.x + d2 * p3.x,
    y: a2 * p0.y + b2 * p1.y + c * p2.y + d2 * p3.y
  };
}
function cubicDerivative2(p0, p1, p2, p3, t) {
  const mt = 1 - t;
  return {
    x: 3 * mt * mt * (p1.x - p0.x) + 6 * mt * t * (p2.x - p1.x) + 3 * t * t * (p3.x - p2.x),
    y: 3 * mt * mt * (p1.y - p0.y) + 6 * mt * t * (p2.y - p1.y) + 3 * t * t * (p3.y - p2.y)
  };
}
function routeCompactLogicalRightTaperedPreviewEdge(args) {
  const p0 = { x: args.from.x + args.from.width, y: args.from.y + args.from.height / 2 };
  const p3 = { x: args.to.x, y: args.to.y + args.to.height / 2 };
  const lead = Math.max(18, Math.abs(p3.x - p0.x) * 0.45);
  const p1 = { x: p0.x + lead, y: p0.y };
  const p2 = { x: p3.x - lead, y: p3.y };
  const left = [];
  const right = [];
  for (let i = 0; i <= 18; i += 1) {
    const t = i / 18;
    const point = cubicPoint2(p0, p1, p2, p3, t);
    const d2 = cubicDerivative2(p0, p1, p2, p3, t);
    const len = Math.hypot(d2.x, d2.y) || 1;
    const nx = -d2.y / len;
    const ny = d2.x / len;
    const width = args.startWidth * (1 - t) + args.endWidth * t;
    const half = Math.max(0, width) / 2;
    left.push({ x: point.x + nx * half, y: point.y + ny * half });
    right.push({ x: point.x - nx * half, y: point.y - ny * half });
  }
  const first2 = left[0];
  if (!first2) return "";
  const parts = [`M ${round22(first2.x)} ${round22(first2.y)}`];
  for (let i = 1; i < left.length; i += 1) {
    const point = left[i];
    parts.push(`L ${round22(point.x)} ${round22(point.y)}`);
  }
  for (let i = right.length - 1; i >= 0; i -= 1) {
    const point = right[i];
    parts.push(`L ${round22(point.x)} ${round22(point.y)}`);
  }
  parts.push("Z");
  return parts.join(" ");
}
function routePreviewPath(args) {
  const anchors = resolveEdgeAnchorsForLayout("logical-right", args.from, args.to);
  const startWidth = 4.6;
  const endWidth = 1.2;
  if (args.route === "cubic") {
    return {
      path: routeCompactLogicalRightPreviewEdge(args.from, args.to),
      renderMode: "stroke"
    };
  }
  if (args.route === "tapered") {
    return {
      path: routeCompactLogicalRightTaperedPreviewEdge({
        from: args.from,
        to: args.to,
        startWidth,
        endWidth
      }),
      renderMode: "fill"
    };
  }
  if (args.route === "center-quadratic-tapered") {
    return {
      path: routeCenterQuadraticTaperedEdgePath({
        from: args.from,
        to: args.to,
        anchors,
        containerWidth: VIEWBOX_WIDTH,
        containerHeight: VIEWBOX_HEIGHT,
        startWidth,
        endWidth
      }),
      renderMode: "fill"
    };
  }
  if (args.route === "edge-lead-quadratic-tapered") {
    return {
      path: routeEdgeLeadQuadraticTaperedEdgePath({
        from: args.from,
        to: args.to,
        anchors,
        startWidth,
        endWidth,
        options: ROUTE_OPTIONS["edge-lead-quadratic"]
      }),
      renderMode: "fill"
    };
  }
  if (args.route === "center-quadratic") {
    return {
      path: routeCenterQuadraticEdgePath({
        from: args.from,
        to: args.to,
        anchors,
        containerWidth: VIEWBOX_WIDTH,
        containerHeight: VIEWBOX_HEIGHT
      }),
      renderMode: "stroke"
    };
  }
  if (args.route === "cubic-tail") {
    return {
      path: routeCubicTailEdgePath({
        from: args.from,
        to: args.to,
        anchors,
        startFromCenter: args.childIndex === 0,
        options: ROUTE_OPTIONS["cubic-tail"]
      }),
      renderMode: "stroke"
    };
  }
  if (args.route === "baseline-fork") {
    return {
      path: routeBaselineForkEdgePath({
        from: args.from,
        to: args.to,
        anchors,
        fromIsRoot: true,
        options: ROUTE_OPTIONS["baseline-fork"]
      }),
      renderMode: "stroke"
    };
  }
  return {
    path: routeEdgePath(args.route, args.from, args.to, anchors, ROUTE_OPTIONS),
    renderMode: "stroke"
  };
}
function NodeGlyph(props) {
  const c = center(props.rect);
  return /* @__PURE__ */ (0, import_jsx_runtime30.jsxs)("g", { children: [
    /* @__PURE__ */ (0, import_jsx_runtime30.jsx)(
      "rect",
      {
        fill: props.root ? "#172033" : "#ffffff",
        height: props.rect.height,
        rx: props.root ? 8 : 7,
        stroke: props.root ? "#172033" : "#cbd5e1",
        strokeWidth: "2",
        width: props.rect.width,
        x: props.rect.x,
        y: props.rect.y
      }
    ),
    /* @__PURE__ */ (0, import_jsx_runtime30.jsx)(
      "path",
      {
        d: `M ${c.x - props.rect.width * 0.2} ${c.y} H ${c.x + props.rect.width * 0.2}`,
        stroke: props.root ? "#f8fafc" : "#64748b",
        strokeLinecap: "round",
        strokeWidth: "2"
      }
    )
  ] });
}
function EdgeRoutePreviewSvg({ route, title, ...svgProps }) {
  const reactId = (0, import_react27.useId)();
  const isHidden = svgProps["aria-hidden"] === true || svgProps["aria-hidden"] === "true";
  const label = title ?? `Edge route preview: ${route}`;
  const titleId = isHidden || svgProps["aria-labelledby"] ? void 0 : `${reactId}-edge-route-preview-title`;
  const gradientId = `${reactId}-edge-route-preview-gradient`.replace(/[^a-zA-Z0-9_-]/g, "-");
  const clipId = `${reactId}-edge-route-preview-clip`.replace(/[^a-zA-Z0-9_-]/g, "-");
  return /* @__PURE__ */ (0, import_jsx_runtime30.jsxs)(
    "svg",
    {
      role: isHidden ? "presentation" : "img",
      viewBox: `0 0 ${VIEWBOX_WIDTH} ${VIEWBOX_HEIGHT}`,
      xmlns: "http://www.w3.org/2000/svg",
      ...svgProps,
      "aria-label": isHidden ? void 0 : svgProps["aria-label"] ?? (titleId ? void 0 : label),
      "aria-labelledby": isHidden ? void 0 : svgProps["aria-labelledby"] ?? titleId,
      children: [
        titleId ? /* @__PURE__ */ (0, import_jsx_runtime30.jsx)("title", { id: titleId, children: label }) : null,
        /* @__PURE__ */ (0, import_jsx_runtime30.jsxs)("defs", { children: [
          /* @__PURE__ */ (0, import_jsx_runtime30.jsxs)("linearGradient", { id: gradientId, x1: "28", x2: "108", y1: "46", y2: "46", gradientUnits: "userSpaceOnUse", children: [
            /* @__PURE__ */ (0, import_jsx_runtime30.jsx)("stop", { stopColor: "#2563eb" }),
            /* @__PURE__ */ (0, import_jsx_runtime30.jsx)("stop", { offset: "1", stopColor: "#0f766e" })
          ] }),
          /* @__PURE__ */ (0, import_jsx_runtime30.jsx)("clipPath", { id: clipId, children: /* @__PURE__ */ (0, import_jsx_runtime30.jsx)("rect", { height: VIEWBOX_HEIGHT, rx: "12", width: VIEWBOX_WIDTH, x: "0", y: "0" }) })
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime30.jsxs)("g", { clipPath: `url(#${clipId})`, children: [
          /* @__PURE__ */ (0, import_jsx_runtime30.jsx)("rect", { fill: "#f8fafc", height: VIEWBOX_HEIGHT, width: VIEWBOX_WIDTH }),
          /* @__PURE__ */ (0, import_jsx_runtime30.jsx)("g", { strokeLinecap: "round", strokeLinejoin: "round", children: CHILD_RECTS.map((child, index) => {
            const routed = routePreviewPath({ route, from: ROOT_RECT, to: child, childIndex: index });
            return routed.renderMode === "fill" ? /* @__PURE__ */ (0, import_jsx_runtime30.jsx)("path", { d: routed.path, fill: `url(#${gradientId})`, opacity: "0.9" }, index) : /* @__PURE__ */ (0, import_jsx_runtime30.jsx)(
              "path",
              {
                d: routed.path,
                fill: "none",
                opacity: "0.94",
                stroke: `url(#${gradientId})`,
                strokeWidth: "2.4"
              },
              index
            );
          }) }),
          /* @__PURE__ */ (0, import_jsx_runtime30.jsx)(NodeGlyph, { rect: ROOT_RECT, root: true }),
          CHILD_RECTS.map((rect, index) => /* @__PURE__ */ (0, import_jsx_runtime30.jsx)(NodeGlyph, { rect }, index))
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime30.jsx)("rect", { fill: "none", height: VIEWBOX_HEIGHT - 1, rx: "12", stroke: "rgba(15, 23, 42, 0.12)", width: VIEWBOX_WIDTH - 1, x: "0.5", y: "0.5" })
      ]
    }
  );
}

// ../react/src/previews/layout-preview-svg.tsx
var React5 = __toESM(require_react(), 1);
var import_jsx_runtime31 = __toESM(require_jsx_runtime(), 1);
var { useId: useId2 } = React5;
var VIEWBOX_WIDTH2 = 140;
var VIEWBOX_HEIGHT2 = 92;
function boxCenter(box) {
  return { x: box.x + box.width / 2, y: box.y + box.height / 2 };
}
function resolveAnchor(box, side) {
  const center3 = boxCenter(box);
  if (side === "left") return { x: box.x, y: center3.y };
  if (side === "right") return { x: box.x + box.width, y: center3.y };
  if (side === "top") return { x: center3.x, y: box.y };
  return { x: center3.x, y: box.y + box.height };
}
function pathForLayout(layout, from2, to) {
  if (layout === "tree-down" || layout === "tree-up") {
    const start2 = resolveAnchor(from2, layout === "tree-up" ? "top" : "bottom");
    const end2 = resolveAnchor(to, layout === "tree-up" ? "bottom" : "top");
    const midY = (start2.y + end2.y) / 2;
    return `M ${start2.x} ${start2.y} C ${start2.x} ${midY}, ${end2.x} ${midY}, ${end2.x} ${end2.y}`;
  }
  const toCenter = boxCenter(to);
  const fromCenter = boxCenter(from2);
  const side = toCenter.x < fromCenter.x ? "left" : "right";
  const start = resolveAnchor(from2, side);
  const end = resolveAnchor(to, side === "left" ? "right" : "left");
  const dir = side === "left" ? -1 : 1;
  const lead = Math.max(18, Math.abs(end.x - start.x) * 0.45);
  return `M ${start.x} ${start.y} C ${start.x + dir * lead} ${start.y}, ${end.x - dir * lead} ${end.y}, ${end.x} ${end.y}`;
}
function getLayoutScene(layout) {
  if (layout === "logical-left") {
    return {
      nodes: [
        { id: "root", x: 78, y: 34, width: 34, height: 24, root: true },
        { id: "a", x: 28, y: 14, width: 30, height: 18 },
        { id: "b", x: 28, y: 60, width: 30, height: 18 }
      ],
      edges: [
        { from: "root", to: "a" },
        { from: "root", to: "b" }
      ]
    };
  }
  if (layout === "tree-down") {
    return {
      nodes: [
        { id: "root", x: 53, y: 10, width: 34, height: 22, root: true },
        { id: "a", x: 15, y: 58, width: 30, height: 18 },
        { id: "b", x: 55, y: 58, width: 30, height: 18 },
        { id: "c", x: 95, y: 58, width: 30, height: 18 }
      ],
      edges: [
        { from: "root", to: "a" },
        { from: "root", to: "b" },
        { from: "root", to: "c" }
      ]
    };
  }
  if (layout === "tree-up") {
    return {
      nodes: [
        { id: "root", x: 53, y: 60, width: 34, height: 22, root: true },
        { id: "a", x: 15, y: 16, width: 30, height: 18 },
        { id: "b", x: 55, y: 16, width: 30, height: 18 },
        { id: "c", x: 95, y: 16, width: 30, height: 18 }
      ],
      edges: [
        { from: "root", to: "a" },
        { from: "root", to: "b" },
        { from: "root", to: "c" }
      ]
    };
  }
  if (layout === "mindmap-both" || layout === "mindmap-both-auto") {
    return {
      nodes: [
        { id: "root", x: 53, y: 34, width: 34, height: 24, root: true },
        { id: "l1", x: 12, y: 16, width: 28, height: 17 },
        { id: "l2", x: 12, y: 61, width: 28, height: 17 },
        { id: "r1", x: 100, y: 16, width: 28, height: 17 },
        { id: "r2", x: 100, y: 61, width: 28, height: 17 }
      ],
      edges: [
        { from: "root", to: "l1" },
        { from: "root", to: "l2" },
        { from: "root", to: "r1" },
        { from: "root", to: "r2" }
      ],
      autoMarkers: layout === "mindmap-both-auto" ? [
        { id: "m1", x: 45, y: 10, width: 6, height: 6 },
        { id: "m2", x: 89, y: 76, width: 6, height: 6 }
      ] : void 0
    };
  }
  return {
    nodes: [
      { id: "root", x: 28, y: 34, width: 34, height: 24, root: true },
      { id: "a", x: 78, y: 14, width: 30, height: 18 },
      { id: "b", x: 78, y: 60, width: 30, height: 18 }
    ],
    edges: [
      { from: "root", to: "a" },
      { from: "root", to: "b" }
    ]
  };
}
function LayoutPreviewSvg({ layout, title, ...svgProps }) {
  const reactId = useId2();
  const scene = getLayoutScene(layout);
  const nodeById = new Map(scene.nodes.map((node) => [node.id, node]));
  const isHidden = svgProps["aria-hidden"] === true || svgProps["aria-hidden"] === "true";
  const label = title ?? `Layout preview: ${layout}`;
  const titleId = isHidden || svgProps["aria-labelledby"] ? void 0 : `${reactId}-layout-preview-title`;
  return /* @__PURE__ */ (0, import_jsx_runtime31.jsxs)(
    "svg",
    {
      role: isHidden ? "presentation" : "img",
      viewBox: `0 0 ${VIEWBOX_WIDTH2} ${VIEWBOX_HEIGHT2}`,
      xmlns: "http://www.w3.org/2000/svg",
      ...svgProps,
      "aria-label": isHidden ? void 0 : svgProps["aria-label"] ?? (titleId ? void 0 : label),
      "aria-labelledby": isHidden ? void 0 : svgProps["aria-labelledby"] ?? titleId,
      children: [
        titleId ? /* @__PURE__ */ (0, import_jsx_runtime31.jsx)("title", { id: titleId, children: label }) : null,
        /* @__PURE__ */ (0, import_jsx_runtime31.jsx)("rect", { width: VIEWBOX_WIDTH2, height: VIEWBOX_HEIGHT2, rx: "12", fill: "#f8fafc" }),
        /* @__PURE__ */ (0, import_jsx_runtime31.jsx)("g", { fill: "none", stroke: "#64748b", strokeLinecap: "round", strokeLinejoin: "round", strokeWidth: "2.4", children: scene.edges.map((edge) => {
          const from2 = nodeById.get(edge.from);
          const to = nodeById.get(edge.to);
          if (!from2 || !to) return null;
          return /* @__PURE__ */ (0, import_jsx_runtime31.jsx)("path", { d: pathForLayout(layout, from2, to) }, `${edge.from}-${edge.to}`);
        }) }),
        /* @__PURE__ */ (0, import_jsx_runtime31.jsx)("g", { children: scene.nodes.map((node) => /* @__PURE__ */ (0, import_jsx_runtime31.jsx)(
          "rect",
          {
            fill: node.root ? "#334155" : "#ffffff",
            height: node.height,
            rx: node.root ? 8 : 6,
            stroke: node.root ? "#334155" : "#cbd5e1",
            strokeWidth: "1.8",
            width: node.width,
            x: node.x,
            y: node.y
          },
          node.id
        )) }),
        /* @__PURE__ */ (0, import_jsx_runtime31.jsx)("g", { strokeLinecap: "round", strokeWidth: "1.8", children: scene.nodes.map((node) => {
          const center3 = boxCenter(node);
          const stroke = node.root ? "#f8fafc" : "#94a3b8";
          return /* @__PURE__ */ (0, import_jsx_runtime31.jsx)(
            "path",
            {
              d: `M ${center3.x - node.width * 0.22} ${center3.y} H ${center3.x + node.width * 0.22}`,
              stroke
            },
            `${node.id}-line`
          );
        }) }),
        scene.autoMarkers ? /* @__PURE__ */ (0, import_jsx_runtime31.jsx)("g", { fill: "#0ea5e9", children: scene.autoMarkers.map((marker) => /* @__PURE__ */ (0, import_jsx_runtime31.jsx)(
          "circle",
          {
            cx: marker.x + marker.width / 2,
            cy: marker.y + marker.height / 2,
            r: marker.width / 2
          },
          marker.id
        )) }) : null
      ]
    }
  );
}

// ../react/src/previews/theme-preview-svg.tsx
var React6 = __toESM(require_react(), 1);
var import_jsx_runtime32 = __toESM(require_jsx_runtime(), 1);
var { useId: useId3 } = React6;
var VIEWBOX_WIDTH3 = 244;
var VIEWBOX_HEIGHT3 = 96;
var HALF_WIDTH = VIEWBOX_WIDTH3 / 2;
var NODE_RECTS = {
  root: { x: 10, y: 36, width: 38, height: 24 },
  topic: { x: 66, y: 18, width: 36, height: 19 },
  note: { x: 66, y: 58, width: 36, height: 19 }
};
var COMPACT_LOGICAL_RIGHT_EDGE_THEME_IDS = /* @__PURE__ */ new Set(["kmind-default", "kmind-candy-pop"]);
var EDGES = [
  { from: "root", to: "topic" },
  { from: "root", to: "note" }
];
function makePreviewDocument(theme, variantId) {
  return {
    version: "1.0.0",
    roots: ["root"],
    nodes: {
      root: { id: "root", text: "Root", children: ["topic", "note"], layout: "logical-right" },
      topic: { id: "topic", parentId: "root", text: "Topic", children: [] },
      note: { id: "note", parentId: "root", text: "Note", children: [] }
    },
    summaries: [],
    relations: [],
    assets: {},
    theme: {
      ...createDefaultDocumentThemeState({ source: "inline", value: theme }),
      appearance: { mode: "fixed", fixed: variantId }
    }
  };
}
function clampNumber3(value, min, max) {
  if (value < min) return min;
  if (value > max) return max;
  return value;
}
function round1(value) {
  return Math.round(value * 10) / 10;
}
function center2(rect) {
  return { x: rect.x + rect.width / 2, y: rect.y + rect.height / 2 };
}
function sanitizePaint(value, fallback) {
  if (!value || value.trim().length === 0) return fallback;
  return value;
}
function routeCompactLogicalRightPreviewEdge2(from2, to) {
  const start = { x: from2.x + from2.width, y: from2.y + from2.height / 2 };
  const end = { x: to.x, y: to.y + to.height / 2 };
  const lead = Math.max(18, Math.abs(end.x - start.x) * 0.45);
  return `M ${start.x} ${start.y} C ${start.x + lead} ${start.y}, ${end.x - lead} ${end.y}, ${end.x} ${end.y}`;
}
function routePreviewEdge(args) {
  if (args.compactLogicalRight) {
    return {
      path: routeCompactLogicalRightPreviewEdge2(args.from, args.to),
      renderMode: "stroke"
    };
  }
  const anchors = resolveEdgeAnchorsForLayout("logical-right", args.from, args.to);
  const containerWidth = HALF_WIDTH;
  const containerHeight = VIEWBOX_HEIGHT3;
  const startWidth = Math.max(1, args.strokeWidth * 2);
  const endWidth = Math.max(0.6, args.strokeWidth * 0.5);
  if (args.routeType === "tapered") {
    return {
      path: routeTaperedEdgePath({
        from: args.from,
        to: args.to,
        startWidth,
        endWidth,
        anchorsOverride: anchors
      }),
      renderMode: "fill"
    };
  }
  if (args.routeType === "center-quadratic-tapered") {
    return {
      path: routeCenterQuadraticTaperedEdgePath({
        from: args.from,
        to: args.to,
        anchors,
        containerWidth,
        containerHeight,
        startWidth,
        endWidth
      }),
      renderMode: "fill"
    };
  }
  if (args.routeType === "edge-lead-quadratic-tapered") {
    return {
      path: routeEdgeLeadQuadraticTaperedEdgePath({
        from: args.from,
        to: args.to,
        anchors,
        startWidth,
        endWidth,
        options: args.routeOptions?.["edge-lead-quadratic"]
      }),
      renderMode: "fill"
    };
  }
  if (args.routeType === "center-quadratic") {
    return {
      path: routeCenterQuadraticEdgePath({
        from: args.from,
        to: args.to,
        anchors,
        containerWidth,
        containerHeight
      }),
      renderMode: "stroke"
    };
  }
  if (args.routeType === "cubic-tail") {
    return {
      path: routeCubicTailEdgePath({
        from: args.from,
        to: args.to,
        anchors,
        startFromCenter: args.edge.to === "topic",
        options: args.routeOptions?.["cubic-tail"]
      }),
      renderMode: "stroke"
    };
  }
  if (args.routeType === "baseline-fork") {
    return {
      path: routeBaselineForkEdgePath({
        from: args.from,
        to: args.to,
        anchors,
        fromIsRoot: args.edge.from === "root",
        options: args.routeOptions?.["baseline-fork"]
      }),
      renderMode: "stroke"
    };
  }
  return {
    path: routeEdgePath(args.routeType, args.from, args.to, anchors, args.routeOptions),
    renderMode: "stroke"
  };
}
function nodeShapeElement(args) {
  const { rect, resolved } = args;
  const shape = resolved.nodeShape;
  const strokeWidth = Math.max(0, Math.min(4, shape?.strokeWidth ?? 1.4));
  const fill = sanitizePaint(resolved.paint.nodeFill, "#ffffff");
  const stroke = strokeWidth <= 0 ? "transparent" : sanitizePaint(resolved.paint.nodeStroke, "transparent");
  const common = {
    fill,
    stroke,
    strokeDasharray: shape?.dasharray,
    strokeWidth
  };
  if (shape?.type === "ellipse") {
    return /* @__PURE__ */ (0, import_jsx_runtime32.jsx)(
      "ellipse",
      {
        ...common,
        cx: rect.x + rect.width / 2,
        cy: rect.y + rect.height / 2,
        rx: rect.width / 2,
        ry: rect.height / 2
      },
      args.id
    );
  }
  if (shape?.type === "diamond") {
    const c = center2(rect);
    return /* @__PURE__ */ (0, import_jsx_runtime32.jsx)(
      "path",
      {
        ...common,
        d: `M ${c.x} ${rect.y} L ${rect.x + rect.width} ${c.y} L ${c.x} ${rect.y + rect.height} L ${rect.x} ${c.y} Z`
      },
      args.id
    );
  }
  const radius = shape?.type === "pill" ? rect.height / 2 : shape?.type === "rect" ? 0 : Math.min(rect.height / 2, shape?.radius ?? 7);
  return /* @__PURE__ */ (0, import_jsx_runtime32.jsx)(
    "rect",
    {
      ...common,
      height: rect.height,
      rx: radius,
      ry: radius,
      width: rect.width,
      x: rect.x,
      y: rect.y
    },
    args.id
  );
}
function renderVariantPreview(theme, variantId, offsetX, idPrefix) {
  const doc3 = makePreviewDocument(theme, variantId);
  const documentTheme = resolveDocumentTheme(doc3);
  const depthIndex = buildNodeDepthIndex(doc3);
  const resolvedByNode = Object.fromEntries(
    Object.keys(doc3.nodes).map((nodeId) => [nodeId, resolveNodeTheme(doc3, nodeId, {}, { depthIndex })])
  );
  const background = documentTheme.background?.color ?? documentTheme.paint.bg;
  const clipId = `${idPrefix}-${variantId}-theme-preview-clip`;
  const compactLogicalRight = COMPACT_LOGICAL_RIGHT_EDGE_THEME_IDS.has(theme.id);
  return /* @__PURE__ */ (0, import_jsx_runtime32.jsxs)("g", { transform: `translate(${offsetX} 0)`, children: [
    /* @__PURE__ */ (0, import_jsx_runtime32.jsx)("clipPath", { id: clipId, children: /* @__PURE__ */ (0, import_jsx_runtime32.jsx)("rect", { height: VIEWBOX_HEIGHT3, width: HALF_WIDTH, x: "0", y: "0" }) }),
    /* @__PURE__ */ (0, import_jsx_runtime32.jsxs)("g", { clipPath: `url(#${clipId})`, children: [
      /* @__PURE__ */ (0, import_jsx_runtime32.jsx)("rect", { fill: background, height: VIEWBOX_HEIGHT3, width: HALF_WIDTH, x: "0", y: "0" }),
      /* @__PURE__ */ (0, import_jsx_runtime32.jsx)("g", { fill: "none", strokeLinecap: documentTheme.edges?.cap ?? "round", strokeLinejoin: documentTheme.edges?.join ?? "round", children: EDGES.map((edge) => {
        const from2 = NODE_RECTS[edge.from];
        const to = NODE_RECTS[edge.to];
        const resolved = resolvedByNode[edge.to];
        if (!from2 || !to || !resolved) return null;
        const incoming = resolved.incomingEdge;
        const routeType = incoming?.routeType ?? resolved.edges?.routeType ?? documentTheme.edges?.routeType ?? "cubic";
        const routeOptions = incoming?.routeOptions ?? resolved.edges?.routeOptions ?? documentTheme.edges?.routeOptions;
        const strokeWidth = clampNumber3((incoming?.strokeWidth ?? resolved.edges?.strokeWidth ?? documentTheme.edges?.strokeWidth ?? 2) * 0.55, 1.1, 3.8);
        const routed = routePreviewEdge({ edge, from: from2, to, routeType, routeOptions, strokeWidth, compactLogicalRight });
        const stroke = sanitizePaint(incoming?.strokeColor ?? resolved.paint.edgeStroke, "#94a3b8");
        return routed.renderMode === "fill" ? /* @__PURE__ */ (0, import_jsx_runtime32.jsx)(
          "path",
          {
            d: routed.path,
            fill: stroke,
            opacity: "0.92"
          },
          `${edge.from}-${edge.to}`
        ) : /* @__PURE__ */ (0, import_jsx_runtime32.jsx)(
          "path",
          {
            d: routed.path,
            stroke,
            strokeDasharray: incoming?.dasharray ?? resolved.edges?.dasharray,
            strokeWidth
          },
          `${edge.from}-${edge.to}`
        );
      }) }),
      /* @__PURE__ */ (0, import_jsx_runtime32.jsx)("g", { children: Object.keys(NODE_RECTS).map((nodeId) => {
        const rect = NODE_RECTS[nodeId];
        const resolved = resolvedByNode[nodeId];
        if (!rect || !resolved) return null;
        return nodeShapeElement({ id: nodeId, rect, resolved });
      }) }),
      /* @__PURE__ */ (0, import_jsx_runtime32.jsx)("g", { strokeLinecap: "round", children: Object.keys(NODE_RECTS).map((nodeId) => {
        const rect = NODE_RECTS[nodeId];
        const resolved = resolvedByNode[nodeId];
        if (!rect || !resolved) return null;
        const c = center2(rect);
        const length = Math.max(7, rect.width * 0.34);
        return /* @__PURE__ */ (0, import_jsx_runtime32.jsx)(
          "path",
          {
            d: `M ${round1(c.x - length / 2)} ${round1(c.y)} H ${round1(c.x + length / 2)}`,
            opacity: "0.72",
            stroke: sanitizePaint(resolved.paint.text, "#0f172a"),
            strokeWidth: "1.5"
          },
          `${nodeId}-text`
        );
      }) }),
      variantId === "light" ? /* @__PURE__ */ (0, import_jsx_runtime32.jsx)(SunGlyph, {}) : /* @__PURE__ */ (0, import_jsx_runtime32.jsx)(MoonGlyph, { x: HALF_WIDTH - 17 })
    ] })
  ] }, variantId);
}
function SunGlyph() {
  return /* @__PURE__ */ (0, import_jsx_runtime32.jsxs)("g", { fill: "none", opacity: "0.74", stroke: "#f59e0b", strokeLinecap: "round", strokeWidth: "1.2", transform: "translate(11 10)", children: [
    /* @__PURE__ */ (0, import_jsx_runtime32.jsx)("circle", { cx: "0", cy: "0", r: "3.2", fill: "#f59e0b", stroke: "none" }),
    /* @__PURE__ */ (0, import_jsx_runtime32.jsx)("path", { d: "M 0 -7 V -5.2 M 0 5.2 V 7 M -7 0 H -5.2 M 5.2 0 H 7 M -5 -5 L -3.8 -3.8 M 5 -5 L 3.8 -3.8 M -5 5 L -3.8 3.8 M 5 5 L 3.8 3.8" })
  ] });
}
function MoonGlyph({ x: x5 }) {
  return /* @__PURE__ */ (0, import_jsx_runtime32.jsx)("g", { opacity: "0.82", transform: `translate(${x5} 10)`, children: /* @__PURE__ */ (0, import_jsx_runtime32.jsx)(
    "path",
    {
      d: "M 5.8 -5.8 C 3.2 -4.9 1.4 -2.4 1.4 0.4 C 1.4 4.2 4.4 7.2 8.2 7.2 C 10.2 7.2 12 6.4 13.2 5.1 C 12.4 5.4 11.5 5.5 10.6 5.5 C 6.8 5.5 3.8 2.5 3.8 -1.3 C 3.8 -3 4.5 -4.6 5.8 -5.8 Z",
      fill: "#cbd5e1"
    }
  ) });
}
function ThemePreviewSvg({ theme, title, ...svgProps }) {
  const reactId = useId3();
  const idPrefix = `${reactId}-${theme.id}`.replace(/[^a-zA-Z0-9_-]/g, "-");
  const isHidden = svgProps["aria-hidden"] === true || svgProps["aria-hidden"] === "true";
  const label = title ?? `Theme preview: ${theme.name}`;
  const titleId = isHidden || svgProps["aria-labelledby"] ? void 0 : `${idPrefix}-theme-preview-title`;
  const cardClipId = `${idPrefix}-theme-preview-card-clip`;
  return /* @__PURE__ */ (0, import_jsx_runtime32.jsxs)(
    "svg",
    {
      role: isHidden ? "presentation" : "img",
      viewBox: `0 0 ${VIEWBOX_WIDTH3} ${VIEWBOX_HEIGHT3}`,
      xmlns: "http://www.w3.org/2000/svg",
      ...svgProps,
      "aria-label": isHidden ? void 0 : svgProps["aria-label"] ?? (titleId ? void 0 : label),
      "aria-labelledby": isHidden ? void 0 : svgProps["aria-labelledby"] ?? titleId,
      children: [
        titleId ? /* @__PURE__ */ (0, import_jsx_runtime32.jsx)("title", { id: titleId, children: label }) : null,
        /* @__PURE__ */ (0, import_jsx_runtime32.jsx)("defs", { children: /* @__PURE__ */ (0, import_jsx_runtime32.jsx)("clipPath", { id: cardClipId, children: /* @__PURE__ */ (0, import_jsx_runtime32.jsx)("rect", { height: VIEWBOX_HEIGHT3, rx: "12", width: VIEWBOX_WIDTH3, x: "0", y: "0" }) }) }),
        /* @__PURE__ */ (0, import_jsx_runtime32.jsxs)("g", { clipPath: `url(#${cardClipId})`, children: [
          renderVariantPreview(theme, "light", 0, idPrefix),
          renderVariantPreview(theme, "dark", HALF_WIDTH, idPrefix),
          /* @__PURE__ */ (0, import_jsx_runtime32.jsx)("path", { d: `M ${HALF_WIDTH} 8 V ${VIEWBOX_HEIGHT3 - 8}`, opacity: "0.22", stroke: "#94a3b8", strokeWidth: "1" })
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime32.jsx)("rect", { fill: "none", height: VIEWBOX_HEIGHT3 - 1, rx: "12", stroke: "rgba(15, 23, 42, 0.12)", width: VIEWBOX_WIDTH3 - 1, x: "0.5", y: "0.5" })
      ]
    }
  );
}

// ../react/src/mindmap-editor/overlays/selection-toolbar-overlay.tsx
var import_jsx_runtime33 = __toESM(require_jsx_runtime(), 1);
var TRANSPARENT_PIXEL_DATA_URL2 = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==";
var CHANGE_THEME_EDGE_ROUTES = WEBAPP_OPEN_EDGE_ROUTE_TYPES;
function resolveLayoutPreviewKind(layout) {
  if (layout === "logical-right" || layout === "logical-left" || layout === "tree-down" || layout === "tree-up" || layout === "mindmap-both" || layout === "mindmap-both-auto") return layout;
  return void 0;
}
function resolveGrowthDirection(args) {
  const anchor = args.activationAnchor;
  if (!anchor) return args.fallbackHorizontal;
  const nodeCenterX = args.nodeRect.x + args.nodeRect.width / 2;
  const nodeCenterY = args.nodeRect.y + args.nodeRect.height / 2;
  const dx = anchor.x - nodeCenterX;
  const dy = anchor.y - nodeCenterY;
  if (Math.abs(dx) >= Math.abs(dy)) return dx >= 0 ? "right" : "left";
  return dy >= 0 ? "down" : "up";
}
function hasContentBlock(doc3, nodeId, type) {
  const node = doc3?.nodes?.[nodeId];
  if (!node) return false;
  const content = node.content;
  if (!content || content.schemaVersion !== 1) return false;
  if (content.kind !== "blocks") return false;
  return content.blocks.some((block) => block?.type === type);
}
function getNodeIconValues(doc3, nodeId) {
  const node = doc3?.nodes?.[nodeId];
  if (!node) return [];
  const content = node.content;
  if (!content || content.schemaVersion !== 1) return [];
  if (content.kind !== "blocks") return [];
  const block = content.blocks.find((item) => item.type === "icons") ?? null;
  if (!block) return [];
  return block.icons.map((icon) => String(icon.value ?? "").trim()).filter((value) => value.length > 0);
}
function BuiltinIconPreview(props) {
  const normalized = normalizeBuiltinIconId(props.iconId);
  const svg = getBuiltinIconSvg(normalized);
  const size = props.size ?? 18;
  if (!svg) {
    return /* @__PURE__ */ (0, import_jsx_runtime33.jsx)("span", { style: { fontSize: 10, color: "var(--km-muted)" }, children: normalized.replace("kmind-icon://builtin/", "") });
  }
  return /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(
    "span",
    {
      style: {
        width: size,
        height: size,
        display: "inline-flex",
        alignItems: "center",
        justifyContent: "center",
        lineHeight: 0,
        color: "var(--km-text)"
      },
      dangerouslySetInnerHTML: { __html: svg }
    }
  );
}
function normalizeIconValue(value) {
  const trimmed = value.trim();
  if (trimmed.startsWith("kmind-icon://")) return normalizeBuiltinIconId(trimmed);
  return trimmed;
}
function buildNodeStyleMergePatchFromResolvedTheme(resolved) {
  if (!resolved) return null;
  const patch = {};
  const layout = {};
  if (typeof resolved.layout.fontSize === "number") layout.fontSize = resolved.layout.fontSize;
  if (typeof resolved.layout.fontWeight === "number") layout.fontWeight = resolved.layout.fontWeight;
  if (typeof resolved.layout.textAlign === "string") layout.textAlign = resolved.layout.textAlign;
  if (Object.keys(layout).length > 0) patch.layout = layout;
  const paint = {};
  if (typeof resolved.paint.nodeFill === "string") paint.nodeFill = resolved.paint.nodeFill;
  if (typeof resolved.paint.nodeStroke === "string") paint.nodeStroke = resolved.paint.nodeStroke;
  if (typeof resolved.paint.text === "string") paint.text = resolved.paint.text;
  if (Object.keys(paint).length > 0) patch.paint = paint;
  if (resolved.nodeShape) {
    const nodeShape = {};
    const type = resolved.nodeShape.type;
    if (type === "rounded-rect" || type === "pill" || type === "rect" || type === "diamond" || type === "ellipse") {
      nodeShape.type = type;
    }
    if (typeof resolved.nodeShape.radius === "number") nodeShape.radius = resolved.nodeShape.radius;
    if (typeof resolved.nodeShape.strokeWidth === "number") nodeShape.strokeWidth = resolved.nodeShape.strokeWidth;
    if (typeof resolved.nodeShape.dasharray === "string") nodeShape.dasharray = resolved.nodeShape.dasharray;
    if (Object.keys(nodeShape).length > 0) patch.nodeShape = nodeShape;
  }
  return Object.keys(patch).length > 0 ? patch : null;
}
function SelectionToolbarOverlay(props) {
  const interactionRootRef = (0, import_react28.useRef)(null);
  const shellRef = (0, import_react28.useRef)(null);
  const overlayPortalContainer = useOverlayPortalContainer();
  const overlayPortalTarget = resolveOverlayPortalTarget(overlayPortalContainer);
  const scopedOverlayPortal = hasScopedOverlayPortal(overlayPortalContainer);
  const t = useT();
  const [openId, setOpenId] = (0, import_react28.useState)(null);
  const [openAnchor, setOpenAnchor] = (0, import_react28.useState)(null);
  const [expanded, setExpanded] = (0, import_react28.useState)(false);
  const [linksMode, setLinksMode] = (0, import_react28.useState)("preview");
  const [notesMode, setNotesMode] = (0, import_react28.useState)("preview");
  const [commentsMode, setCommentsMode] = (0, import_react28.useState)("preview");
  const metaPopoverCommitRef = (0, import_react28.useRef)(null);
  const [lockedPosition, setLockedPosition] = (0, import_react28.useState)(null);
  const [formatPainter, setFormatPainter] = (0, import_react28.useState)(null);
  const [formatPainterCursor, setFormatPainterCursor] = (0, import_react28.useState)(null);
  const [relationPickerCursor, setRelationPickerCursor] = (0, import_react28.useState)(null);
  const [linkPickerCursor, setLinkPickerCursor] = (0, import_react28.useState)(null);
  const [iconPickerSlot, setIconPickerSlot] = (0, import_react28.useState)(null);
  const [imageLightbox, setImageLightbox] = (0, import_react28.useState)(null);
  const imageSizeRafRef = (0, import_react28.useRef)(null);
  const pendingImageSizeRef = (0, import_react28.useRef)(null);
  const iconGroups = (0, import_react28.useMemo)(() => listBuiltinIconPickerGroups({ surface: "node-content" }), []);
  const selectionPopoverItemById = (0, import_react28.useMemo)(() => {
    const next = /* @__PURE__ */ new Map();
    for (const item of props.selectionToolbar) {
      if (item.kind !== "popover") continue;
      next.set(item.id, item);
    }
    return next;
  }, [props.selectionToolbar]);
  (0, import_react28.useEffect)(() => {
    if (!openId) return;
    const win = resolveOwnerWindow(interactionRootRef.current ?? props.svgRef.current) ?? (typeof window !== "undefined" ? window : null);
    if (!win) return;
    const onPointerDown = (event) => {
      const target2 = event.target;
      if (!isNodeLike(target2)) return;
      if (isElementLike(target2) && target2.closest("[data-km-meta-popover-toolbar]")) return;
      if (interactionRootRef.current?.contains(target2)) return;
      try {
        metaPopoverCommitRef.current?.();
      } catch {
      }
      setOpenId(null);
      setOpenAnchor(null);
    };
    win.addEventListener("pointerdown", onPointerDown, true);
    return () => win.removeEventListener("pointerdown", onPointerDown, true);
  }, [openId]);
  (0, import_react28.useEffect)(() => {
    if (!lockedPosition) return;
    const win = resolveOwnerWindow(interactionRootRef.current ?? props.svgRef.current) ?? (typeof window !== "undefined" ? window : null);
    if (!win) return;
    const release = () => setLockedPosition(null);
    win.addEventListener("pointerup", release, true);
    win.addEventListener("mouseup", release, true);
    win.addEventListener("touchend", release, true);
    win.addEventListener("touchcancel", release, true);
    win.addEventListener("blur", release, true);
    return () => {
      win.removeEventListener("pointerup", release, true);
      win.removeEventListener("mouseup", release, true);
      win.removeEventListener("touchend", release, true);
      win.removeEventListener("touchcancel", release, true);
      win.removeEventListener("blur", release, true);
    };
  }, [lockedPosition]);
  (0, import_react28.useEffect)(() => {
    if (!props.visible) setLockedPosition(null);
  }, [props.visible]);
  (0, import_react28.useEffect)(() => {
    if (openId !== "builtin.image") setLockedPosition(null);
  }, [openId]);
  (0, import_react28.useEffect)(() => {
    const win = resolveOwnerWindow(interactionRootRef.current ?? props.svgRef.current) ?? (typeof window !== "undefined" ? window : null);
    if (!win) return;
    const onKeyDown = (event) => {
      if (event.key !== "Escape") return;
      try {
        metaPopoverCommitRef.current?.();
      } catch {
      }
      setOpenId(null);
      setOpenAnchor(null);
      setFormatPainter(null);
      setImageLightbox(null);
    };
    win.addEventListener("keydown", onKeyDown, true);
    return () => win.removeEventListener("keydown", onKeyDown, true);
  }, []);
  (0, import_react28.useEffect)(() => {
    if (!props.visible) {
      try {
        metaPopoverCommitRef.current?.();
      } catch {
      }
      setOpenId(null);
      setOpenAnchor(null);
      props.onSetHighlightNodeId(null);
      setExpanded(false);
      setFormatPainter(null);
      setImageLightbox(null);
    }
  }, [props.onSetHighlightNodeId, props.visible]);
  (0, import_react28.useEffect)(() => {
    const request = props.popoverRequest;
    if (!request) return;
    if (!props.visible) return;
    if (request.nodeId !== props.nodeId) return;
    const resolveMode = (mode) => mode === "edit" ? "edit" : "preview";
    if (request.popoverId === "builtin.links" && props.onOpenLinksPanel) {
      try {
        metaPopoverCommitRef.current?.();
      } catch {
      }
      setOpenId(null);
      setOpenAnchor(null);
      props.onOpenLinksPanel({ nodeId: request.nodeId, mode: resolveMode(request.mode) });
      props.onPopoverRequestHandled?.(request.requestId);
      return;
    }
    if (request.popoverId === "builtin.notes" && props.onOpenMetaPopover) {
      try {
        metaPopoverCommitRef.current?.();
      } catch {
      }
      setOpenId(null);
      setOpenAnchor(null);
      props.onOpenMetaPopover({ kind: "notes", nodeId: request.nodeId, mode: resolveMode(request.mode) });
      props.onPopoverRequestHandled?.(request.requestId);
      return;
    }
    if (request.popoverId === "builtin.comments" && props.onOpenMetaPopover) {
      try {
        metaPopoverCommitRef.current?.();
      } catch {
      }
      setOpenId(null);
      setOpenAnchor(null);
      props.onOpenMetaPopover({ kind: "comments", nodeId: request.nodeId, mode: resolveMode(request.mode) });
      props.onPopoverRequestHandled?.(request.requestId);
      return;
    }
    const supportsInlinePopover = request.popoverId === "builtin.image" || request.popoverId === "builtin.icons" || request.popoverId === "builtin.tags" || request.popoverId === "builtin.links" || request.popoverId === "builtin.notes" || request.popoverId === "builtin.comments" || selectionPopoverItemById.has(request.popoverId);
    if (!supportsInlinePopover) return;
    const rootRect = shellRef.current?.getBoundingClientRect() ?? null;
    const rect = request.anchorClientRect;
    const anchor = rootRect && rect ? {
      id: request.popoverId,
      left: rect.left - rootRect.left,
      top: rect.top - rootRect.top,
      width: rect.width,
      height: rect.height
    } : { id: request.popoverId, left: 0, top: 0, width: 0, height: 0 };
    try {
      metaPopoverCommitRef.current?.();
    } catch {
    }
    if (request.popoverId === "builtin.links") {
      setLinksMode(request.mode === "edit" ? "edit" : "preview");
    } else if (request.popoverId === "builtin.notes") {
      setNotesMode(request.mode === "edit" ? "edit" : "preview");
    } else if (request.popoverId === "builtin.comments") {
      setCommentsMode(request.mode === "edit" ? "edit" : "preview");
    }
    setOpenId(request.popoverId);
    setOpenAnchor(anchor);
    props.onPopoverRequestHandled?.(request.requestId);
  }, [props.nodeId, props.onOpenLinksPanel, props.onOpenMetaPopover, props.onPopoverRequestHandled, props.popoverRequest, props.visible, selectionPopoverItemById]);
  (0, import_react28.useEffect)(() => {
    if (openId === "builtin.icons") return;
    setIconPickerSlot(null);
  }, [openId]);
  (0, import_react28.useEffect)(() => {
    setIconPickerSlot(null);
  }, [props.nodeId]);
  (0, import_react28.useEffect)(() => {
    setExpanded(false);
    setOpenId(null);
    setOpenAnchor(null);
  }, [props.nodeId]);
  (0, import_react28.useEffect)(() => {
    if (!props.contextMenuOpen) return;
    setExpanded(false);
    setOpenId(null);
    setOpenAnchor(null);
  }, [props.contextMenuOpen]);
  if (!props.visible) return null;
  const doc3 = props.doc;
  const presentation = useWorkspacePresentation({ compactMaxWidth: 920, compactCoarseMaxWidth: 1180 });
  const compactChrome = presentation.isCompact;
  const hostChromeSafeZIndex = compactChrome && presentation.coarsePointer ? 40 : 75;
  const panelGap = compactChrome ? 12 : 10;
  const panelPadding = 6;
  const panelHeight = compactChrome ? 50 : 46;
  const moreButtonWidth = 36;
  const panelActionGap = 8;
  const availableRight = props.viewport.width - (props.nodeRect.x + props.nodeRect.width) - 8;
  const availableLeft = props.nodeRect.x - 8;
  const fallbackHorizontal = availableRight >= Math.max(160, availableLeft) ? "right" : "left";
  const growthDirection = resolveGrowthDirection({
    activationAnchor: props.activationAnchor,
    nodeRect: props.nodeRect,
    fallbackHorizontal
  });
  const activationAnchor = props.activationAnchor ?? {
    x: fallbackHorizontal === "right" ? props.nodeRect.x + props.nodeRect.width + 10 : props.nodeRect.x - 10,
    y: props.nodeRect.y + props.nodeRect.height / 2
  };
  const chevronCenter = activationAnchor;
  const activationWidth = 8;
  const activationHeight = 8;
  const desiredShellLeft = chevronCenter.x - activationWidth / 2;
  const desiredShellTop = chevronCenter.y - activationHeight / 2;
  const left = lockedPosition?.left ?? Math.max(8, Math.min(desiredShellLeft, props.viewport.width - activationWidth - 8));
  const top = lockedPosition?.top ?? Math.max(8, Math.min(desiredShellTop, props.viewport.height - activationHeight - 8));
  const panelOriginX = chevronCenter.x + (growthDirection === "right" ? panelGap : growthDirection === "left" ? -panelGap : 0);
  const panelOriginY = chevronCenter.y + (growthDirection === "down" ? panelGap : growthDirection === "up" ? -panelGap : 0);
  const availablePanelWidth = growthDirection === "right" ? Math.max(0, props.viewport.width - panelOriginX - 8) : growthDirection === "left" ? Math.max(0, panelOriginX - 8) : Math.max(0, props.viewport.width - 16);
  const maxToolbarWidth = Math.max(0, Math.min(760, availablePanelWidth));
  const { visible: visibleQuickActions, overflow: overflowQuickActions } = partitionSelectionQuickActions({
    actions: props.quickActions,
    availableWidth: maxToolbarWidth,
    gap: panelActionGap,
    moreButtonWidth
  });
  const visibleQuickActionIds = new Set(visibleQuickActions.map((action) => action.id));
  const visibleRegistryItems = props.selectionToolbar.filter((item) => visibleQuickActionIds.has(item.id));
  const visibleAreaAItems = visibleRegistryItems.filter((item) => item.area === "A");
  const visibleAreaCItems = visibleRegistryItems.filter((item) => item.area === "C");
  const hasVisibleBuiltinActions = props.quickActions.some((action) => action.source === "builtin" && visibleQuickActionIds.has(action.id));
  const isQuickActionVisible = (id) => visibleQuickActionIds.has(id);
  const visibleAreaAActions = visibleQuickActions.filter((action) => action.source === "registry" && action.item.area === "A");
  const trailingQuickActions = visibleQuickActions.filter((action) => !(action.source === "registry" && action.item.area === "A"));
  const measureActionRowWidth = (actions) => actions.reduce((sum, action) => sum + action.estimatedWidth, 0) + Math.max(0, actions.length - 1) * panelActionGap;
  const visibleAreaAWidth = measureActionRowWidth(visibleAreaAActions);
  const trailingQuickActionsWidth = measureActionRowWidth(trailingQuickActions);
  const areaCWidth = trailingQuickActionsWidth + (trailingQuickActions.length > 0 ? panelActionGap : 0) + moreButtonWidth;
  const showPanelDivider = visibleAreaAActions.length > 0 && trailingQuickActions.length > 0;
  const outerGapWidth = visibleAreaAActions.length > 0 ? showPanelDivider ? 20 : 10 : 0;
  const panelWidth = Math.max(
    46,
    Math.min(
      maxToolbarWidth,
      visibleAreaAWidth + areaCWidth + outerGapWidth + (showPanelDivider ? 1 : 0) + panelPadding * 2 + 4
    )
  );
  const desiredPanelLeft = growthDirection === "right" ? panelOriginX : growthDirection === "left" ? panelOriginX - panelWidth : chevronCenter.x - panelWidth / 2;
  const desiredPanelTop = growthDirection === "down" ? panelOriginY : growthDirection === "up" ? panelOriginY - panelHeight : chevronCenter.y - panelHeight / 2;
  const panelLeft = Math.max(8, Math.min(desiredPanelLeft, props.viewport.width - panelWidth - 8)) - left;
  const panelTop = Math.max(8, Math.min(desiredPanelTop, props.viewport.height - panelHeight - 8)) - top;
  const areaCStartOffset = panelLeft + panelPadding + visibleAreaAWidth + (visibleAreaAActions.length > 0 ? showPanelDivider ? 21 : 10 : 0);
  const moreButtonLeft = areaCStartOffset + trailingQuickActionsWidth + (trailingQuickActions.length > 0 ? panelActionGap : 0);
  const buttonStyle2 = {
    height: compactChrome ? 38 : 34,
    padding: compactChrome ? "0 12px" : "0 10px",
    borderRadius: 10,
    border: "1px solid var(--km-border)",
    background: "var(--km-panel)",
    color: "var(--km-text)",
    fontSize: compactChrome ? 13 : 12,
    cursor: "pointer",
    userSelect: "none",
    whiteSpace: "nowrap",
    flexShrink: 0
  };
  const disabledButtonStyle = {
    ...buttonStyle2,
    opacity: 0.55,
    cursor: "not-allowed"
  };
  const readOnly = Boolean(props.snapshot.editor.viewModes.readOnly.value);
  const iconValues = getNodeIconValues(doc3, props.nodeId);
  const iconSlots = [
    iconValues[0] ? normalizeIconValue(iconValues[0]) : null,
    iconValues[1] ? normalizeIconValue(iconValues[1]) : null,
    iconValues[2] ? normalizeIconValue(iconValues[2]) : null
  ];
  const canEditIcons = props.isCommandEnabled("node.icon.set", { nodeId: props.nodeId });
  const image = (() => {
    const node = doc3.nodes[props.nodeId];
    if (!node) return null;
    const content = node.content;
    if (!content || content.schemaVersion !== 1 || content.kind !== "blocks") return null;
    const block = content.blocks.find((item) => item.type === "image") ?? null;
    if (!block) return null;
    const asset = doc3.assets?.[block.assetId] ?? null;
    const resolved = (() => {
      if (!asset || asset.kind !== "image" && asset.kind !== "blob") return { src: null, placeholder: true };
      const url = asset.dataUrl ?? "";
      if (url.startsWith("kmind-asset://")) {
        const storedId = url.slice("kmind-asset://".length).trim() || block.assetId;
        const objectUrl = props.assetObjectUrlById?.get(storedId) ?? null;
        return objectUrl ? { src: objectUrl, placeholder: false } : { src: null, placeholder: true };
      }
      return url.length > 0 ? { src: url, placeholder: false } : { src: null, placeholder: true };
    })();
    const fallbackWidth = asset && asset.kind === "image" ? asset.width ?? 240 : 240;
    const fallbackHeight = asset && asset.kind === "image" ? asset.height ?? 160 : 160;
    const width = Math.max(20, Math.round(block.width ?? fallbackWidth));
    const height = Math.max(20, Math.round(block.height ?? fallbackHeight));
    const fit = block.fit ?? "contain";
    const alt = typeof block.alt === "string" ? block.alt : "";
    return { block, width, height, fit, alt, ...resolved };
  })();
  const onToolbarButtonPointerDown = (event) => {
    event.preventDefault();
    event.stopPropagation();
  };
  (0, import_react28.useEffect)(() => {
    if (!props.pendingRelationFromId) {
      setRelationPickerCursor(null);
      return;
    }
    const win = resolveOwnerWindow(interactionRootRef.current ?? props.svgRef.current) ?? (typeof window !== "undefined" ? window : null);
    if (!win) return;
    const onMove = (event) => {
      setRelationPickerCursor({ x: event.clientX, y: event.clientY });
    };
    win.addEventListener("pointermove", onMove, true);
    return () => win.removeEventListener("pointermove", onMove, true);
  }, [props.pendingRelationFromId]);
  const renderCursorIconBadge = (args) => {
    const portalPosition = toOverlayPortalPoint(overlayPortalContainer, {
      x: args.cursor.x + 10,
      y: args.cursor.y + 10
    });
    const node = /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(
      "div",
      {
        "aria-hidden": "true",
        style: {
          position: scopedOverlayPortal ? "absolute" : "fixed",
          left: portalPosition.x,
          top: portalPosition.y,
          width: 28,
          height: 28,
          borderRadius: 10,
          border: "1px solid rgba(148, 163, 184, 0.45)",
          background: "rgba(255,255,255,0.92)",
          boxShadow: "0 18px 36px rgba(15, 23, 42, 0.18)",
          pointerEvents: "none",
          display: "flex",
          alignItems: "center",
          justifyContent: "center",
          zIndex: 120
        },
        title: args.label,
        children: /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(BuiltinIconPreview, { iconId: args.iconId, size: 16 })
      }
    );
    return overlayPortalTarget ? (0, import_react_dom6.createPortal)(node, overlayPortalTarget) : node;
  };
  const commitIconSlots = (nextSlots) => {
    const visited = /* @__PURE__ */ new Set();
    const nextIcons = [];
    for (const value of nextSlots) {
      if (!value) continue;
      const normalized = normalizeIconValue(value);
      if (normalized.length === 0) continue;
      if (visited.has(normalized)) continue;
      visited.add(normalized);
      nextIcons.push(normalized);
      if (nextIcons.length >= 3) break;
    }
    void props.dispatchCommand("node.icon.set", { nodeId: props.nodeId, icons: nextIcons });
  };
  const setIconSlotValue = (slotIndex, nextValue) => {
    const nextSlots = iconSlots.slice();
    if (!nextSlots[slotIndex] && !nextValue) return;
    if (nextValue) {
      const normalized = normalizeIconValue(nextValue);
      for (let i = 0; i < nextSlots.length; i++) {
        if (i === slotIndex) continue;
        if (nextSlots[i] === normalized) nextSlots[i] = null;
      }
      nextSlots[slotIndex] = normalized;
    } else {
      nextSlots[slotIndex] = null;
    }
    commitIconSlots(nextSlots);
  };
  const scheduleSetImageSize = (0, import_react28.useCallback)((next) => {
    pendingImageSizeRef.current = next;
    if (imageSizeRafRef.current) return;
    const raf = typeof requestAnimationFrame === "function" ? requestAnimationFrame : (fn) => setTimeout(fn, 0);
    imageSizeRafRef.current = raf(() => {
      imageSizeRafRef.current = null;
      const pending = pendingImageSizeRef.current;
      pendingImageSizeRef.current = null;
      if (!pending) return;
      void props.dispatchCommand("node.image.setSize", { nodeId: props.nodeId, blockId: pending.blockId, width: pending.width, height: pending.height });
    });
  }, [props.dispatchCommand, props.nodeId]);
  (0, import_react28.useEffect)(() => {
    const caf = typeof cancelAnimationFrame === "function" ? cancelAnimationFrame : clearTimeout;
    return () => {
      if (!imageSizeRafRef.current) return;
      try {
        caf(imageSizeRafRef.current);
      } finally {
        imageSizeRafRef.current = null;
      }
    };
  }, []);
  const formatPainterSourcePatch = (0, import_react28.useMemo)(() => {
    if (!doc3) return null;
    const resolved = resolveNodeTheme(doc3, props.nodeId);
    return buildNodeStyleMergePatchFromResolvedTheme(resolved);
  }, [doc3, props.nodeId]);
  const canStartFormatPainter = Boolean(formatPainterSourcePatch);
  const renderDivider = () => /* @__PURE__ */ (0, import_jsx_runtime33.jsx)("div", { style: { width: 1, height: 26, background: "var(--km-border)", opacity: 0.6 } });
  const selectionToolbarPopoverCssText = `
    [data-km-selection-toolbar-popover="true"],
    [data-km-selection-toolbar-popover="true"] .km-popover-scroll {
      scrollbar-width: thin;
      scrollbar-color: rgba(148, 163, 184, 0.65) transparent;
    }
    [data-km-selection-toolbar-popover="true"]::-webkit-scrollbar,
    [data-km-selection-toolbar-popover="true"] .km-popover-scroll::-webkit-scrollbar {
      width: 10px;
    }
    [data-km-selection-toolbar-popover="true"]::-webkit-scrollbar-track,
    [data-km-selection-toolbar-popover="true"] .km-popover-scroll::-webkit-scrollbar-track {
      background: transparent;
    }
    [data-km-selection-toolbar-popover="true"]::-webkit-scrollbar-thumb,
    [data-km-selection-toolbar-popover="true"] .km-popover-scroll::-webkit-scrollbar-thumb {
      background-color: rgba(148, 163, 184, 0.50);
      border-radius: 999px;
      border: 3px solid transparent;
      background-clip: content-box;
    }
    [data-km-selection-toolbar-popover="true"]:hover::-webkit-scrollbar-thumb,
    [data-km-selection-toolbar-popover="true"] .km-popover-scroll:hover::-webkit-scrollbar-thumb {
      background-color: rgba(148, 163, 184, 0.72);
    }
  `;
  const popoverStickyTitleStyle = {
    position: "sticky",
    top: 0,
    zIndex: 3,
    background: "var(--km-panel)",
    boxShadow: "inset 0 -1px 0 var(--km-border)"
  };
  const renderPopoverPanel = (args) => {
    const anchor = openAnchor?.id === args.anchorId ? openAnchor : null;
    const desiredWidth = args.width ?? 360;
    const width = Math.max(220, Math.min(desiredWidth, props.viewport.width - 16));
    const gap = 8;
    const triggerLeft = anchor?.left ?? 0;
    const triggerTop = anchor?.top ?? 0;
    const triggerHeight = anchor?.height ?? 0;
    const desiredLeftInCanvas = left + triggerLeft;
    const clampedLeftInCanvas = Math.max(8, Math.min(desiredLeftInCanvas, Math.max(8, props.viewport.width - width - 8)));
    const panelLeft2 = clampedLeftInCanvas;
    const belowStart = top + triggerTop + triggerHeight + gap;
    const aboveStart = top + triggerTop - gap;
    const availableBelow = props.viewport.height - belowStart - 8;
    const availableAbove = aboveStart - 8;
    const placeAbove = availableBelow < 240 && availableAbove > availableBelow;
    const maxHeight = Math.min(
      args.maxHeight ?? 420,
      Math.max(140, placeAbove ? availableAbove : availableBelow)
    );
    const nodeSidePlacement = (() => {
      if (anchor?.placement !== "node-side") return null;
      const padding = 12;
      const preferRight = props.nodeRect.x + props.nodeRect.width + 10 + width + padding <= props.viewport.width;
      const leftPos = Math.max(
        padding,
        Math.min(
          preferRight ? props.nodeRect.x + props.nodeRect.width + 10 : props.nodeRect.x - width - 10,
          Math.max(padding, props.viewport.width - padding - width)
        )
      );
      const topPos = Math.max(
        padding,
        Math.min(props.nodeRect.y, Math.max(padding, props.viewport.height - padding - maxHeight))
      );
      return { left: leftPos, top: topPos };
    })();
    const placementStyle = nodeSidePlacement ? { top: nodeSidePlacement.top } : placeAbove ? { bottom: props.viewport.height - (top + triggerTop) + gap } : { top: top + triggerTop + triggerHeight + gap };
    return /* @__PURE__ */ (0, import_jsx_runtime33.jsxs)(
      "div",
      {
        "data-km-selection-toolbar-popover": "true",
        "data-km-selection-toolbar-popover-root": "true",
        onPointerDown: (event) => event.stopPropagation(),
        style: {
          position: "absolute",
          left: nodeSidePlacement?.left ?? panelLeft2,
          width,
          maxHeight,
          borderRadius: 14,
          border: "1px solid var(--km-border)",
          background: "var(--km-panel)",
          boxShadow: "0 18px 36px rgba(15, 23, 42, 0.18)",
          pointerEvents: "auto",
          overflowY: "auto",
          overflowX: "hidden",
          scrollbarGutter: "stable",
          zIndex: 80,
          ...placementStyle
        },
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime33.jsx)("style", { children: selectionToolbarPopoverCssText }),
          args.children
        ]
      }
    );
  };
  const resolveAnchorFromTriggerRect = (0, import_react28.useCallback)((id, triggerRect) => {
    const rootRect = shellRef.current?.getBoundingClientRect() ?? null;
    if (!rootRect) {
      return { id, left: 0, top: 0, width: triggerRect.width, height: triggerRect.height, placement: "trigger" };
    }
    return {
      id,
      left: triggerRect.left - rootRect.left,
      top: triggerRect.top - rootRect.top,
      width: triggerRect.width,
      height: triggerRect.height,
      placement: "trigger"
    };
  }, []);
  const resolveNodeSidePopoverAnchor = (0, import_react28.useCallback)((id) => {
    return {
      id,
      left: props.nodeRect.x + props.nodeRect.width + 10 - left,
      top: props.nodeRect.y - top,
      width: 34,
      height: 34,
      placement: "node-side"
    };
  }, [left, props.nodeRect.height, props.nodeRect.width, props.nodeRect.x, props.nodeRect.y, top]);
  const resolveSyntheticQuickActionAnchor = (0, import_react28.useCallback)((id) => {
    const visibleAreaAIndex = visibleAreaAActions.findIndex((action) => action.id === id);
    if (visibleAreaAIndex >= 0) {
      const precedingWidth = visibleAreaAActions.slice(0, visibleAreaAIndex).reduce((sum, action) => sum + action.estimatedWidth, 0) + Math.max(0, visibleAreaAIndex) * panelActionGap;
      return {
        id,
        left: panelLeft + panelPadding + precedingWidth,
        top: panelTop + panelPadding,
        width: visibleAreaAActions[visibleAreaAIndex]?.estimatedWidth ?? 34,
        height: 34,
        placement: "trigger"
      };
    }
    const trailingIndex = trailingQuickActions.findIndex((action) => action.id === id);
    if (trailingIndex >= 0) {
      const precedingWidth = trailingQuickActions.slice(0, trailingIndex).reduce((sum, action) => sum + action.estimatedWidth, 0) + Math.max(0, trailingIndex) * panelActionGap;
      return {
        id,
        left: areaCStartOffset + precedingWidth,
        top: panelTop + panelPadding,
        width: trailingQuickActions[trailingIndex]?.estimatedWidth ?? 34,
        height: 34,
        placement: "trigger"
      };
    }
    return {
      id,
      left: moreButtonLeft,
      top: panelTop + panelPadding,
      width: moreButtonWidth,
      height: 34,
      placement: "trigger"
    };
  }, [areaCStartOffset, moreButtonLeft, moreButtonWidth, panelActionGap, panelLeft, panelPadding, panelTop, trailingQuickActions, visibleAreaAActions]);
  const closeQuickActionPopover = (0, import_react28.useCallback)(() => {
    setOpenId(null);
    setOpenAnchor(null);
  }, []);
  const renderSection = (args) => /* @__PURE__ */ (0, import_jsx_runtime33.jsxs)("div", { style: { padding: 10 }, children: [
    /* @__PURE__ */ (0, import_jsx_runtime33.jsx)("div", { style: { fontSize: 11, fontWeight: 700, color: "var(--km-muted)", letterSpacing: "0.04em", textTransform: "uppercase" }, children: args.title }),
    /* @__PURE__ */ (0, import_jsx_runtime33.jsx)("div", { style: { marginTop: 8, display: "flex", flexWrap: "wrap", gap: 8 }, children: args.children })
  ] });
  const renderSeparator = () => /* @__PURE__ */ (0, import_jsx_runtime33.jsx)("div", { style: { height: 1, background: "var(--km-border)", opacity: 0.9 } });
  const renderChipButton = (args) => {
    const disabled = Boolean(args.disabled);
    const active = Boolean(args.active);
    return /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(
      "button",
      {
        disabled,
        onClick: () => {
          if (disabled) return;
          args.onClick();
        },
        style: {
          height: 30,
          padding: "0 10px",
          borderRadius: 999,
          border: "1px solid var(--km-border)",
          background: active ? "rgba(148,163,184,0.16)" : "transparent",
          color: disabled ? "rgba(100,116,139,0.7)" : "var(--km-text)",
          fontSize: 12,
          cursor: disabled ? "not-allowed" : "pointer"
        },
        tabIndex: -1,
        type: "button",
        children: args.title
      },
      args.id ?? args.title
    );
  };
  const renderPreviewCard = (args) => {
    const disabled = Boolean(args.disabled);
    const active = Boolean(args.active);
    return /* @__PURE__ */ (0, import_jsx_runtime33.jsxs)(
      "button",
      {
        "aria-pressed": active,
        disabled,
        onClick: () => {
          if (disabled) return;
          args.onClick();
        },
        style: {
          position: "relative",
          minHeight: args.minHeight ?? 108,
          borderRadius: 8,
          border: active ? "2px solid var(--kmind-zen-primary-bg, #1d4ed8)" : "1px solid var(--km-border)",
          background: "var(--km-panel)",
          color: disabled ? "rgba(100,116,139,0.7)" : "var(--km-text)",
          padding: active ? 7 : 8,
          cursor: disabled ? "not-allowed" : "pointer",
          opacity: disabled ? 0.55 : 1,
          boxShadow: active ? "0 10px 28px rgba(37, 99, 235, 0.13)" : "0 1px 2px rgba(15, 23, 42, 0.04)",
          overflow: "hidden"
        },
        tabIndex: -1,
        title: args.title,
        type: "button",
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime33.jsx)("div", { style: { height: args.minHeight && args.minHeight > 118 ? 76 : 66, display: "flex", alignItems: "center", justifyContent: "center" }, children: args.preview }),
          /* @__PURE__ */ (0, import_jsx_runtime33.jsx)("div", { style: { marginTop: 7, minWidth: 0, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap", fontSize: 12, fontWeight: 650 }, children: args.title }),
          active ? /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(
            "span",
            {
              "aria-hidden": "true",
              style: {
                position: "absolute",
                right: 7,
                top: 7,
                width: 20,
                height: 20,
                borderRadius: 999,
                display: "inline-flex",
                alignItems: "center",
                justifyContent: "center",
                background: "var(--kmind-zen-primary-bg, #1d4ed8)",
                color: "var(--kmind-zen-primary-text, #ffffff)"
              },
              children: /* @__PURE__ */ (0, import_jsx_runtime33.jsx)("svg", { fill: "none", height: "13", viewBox: "0 0 16 16", width: "13", xmlns: "http://www.w3.org/2000/svg", children: /* @__PURE__ */ (0, import_jsx_runtime33.jsx)("path", { d: "M3.5 8.2 6.6 11 12.5 4.8", stroke: "currentColor", strokeLinecap: "round", strokeLinejoin: "round", strokeWidth: "2" }) })
            }
          ) : null
        ]
      },
      args.id ?? args.title
    );
  };
  const renderPreviewGrid = (children, minCardWidth = 128) => /* @__PURE__ */ (0, import_jsx_runtime33.jsx)("div", { style: { marginTop: 8, display: "grid", gridTemplateColumns: `repeat(auto-fit, minmax(${minCardWidth}px, 1fr))`, gap: 8 }, children });
  const renderChangeThemePopover = (variant) => {
    const capabilities = props.snapshot.capabilities;
    const allowChildLayoutOverride = capabilities.layout.allowChildLayoutOverride;
    const rootLayoutAllowlist = capabilities.layout.rootLayoutAllowlist;
    const layoutEngine = props.snapshot.editor.layoutEngine;
    const showLayoutSection = variant === "root" || allowChildLayoutOverride;
    const allowedLayouts = (() => {
      if (!doc3) return ["logical-right"];
      if (variant === "root") {
        const supported = layoutEngine === "tidy" ? ALL_LAYOUT_TYPES : ALL_LAYOUT_TYPES.filter((layout) => !isTidyOnlyLayout(layout));
        return rootLayoutAllowlist ? supported.filter((layout) => rootLayoutAllowlist.includes(layout)) : supported;
      }
      if (!allowChildLayoutOverride) return [];
      const direction = buildOutwardDirectionByNodeId(doc3).get(props.nodeId) ?? "unknown";
      return resolveAllowedNodeLayouts({ direction, layoutEngine });
    })();
    const applyLayout = (layout) => {
      void props.dispatchCommand("layout.node.setLayout", { nodeId: props.nodeId, layout });
      setOpenId(null);
    };
    const applyTheme = (theme) => {
      if (theme.source !== "official" && theme.themePackage) {
        void props.dispatchCommand("theme.applyPackage", { themePackage: theme.themePackage, scope: "root" });
      } else {
        void props.dispatchCommand("theme.applyPreset", { presetId: theme.id, scope: "root" });
      }
      setOpenId(null);
    };
    const applyEdgeRoute = (routeType) => {
      void props.dispatchCommand("theme.edgeRoute.applyToRootSubtree", { rootNodeId: props.nodeId, routeType });
      setOpenId(null);
    };
    const applyEdgeDasharray = (dasharray) => {
      void props.dispatchCommand("theme.edgeDasharray.applyToSubtree", { nodeId: props.nodeId, dasharray });
      setOpenId(null);
    };
    const applyEdgeStrokeWidth = (strokeWidth) => {
      void props.dispatchCommand("theme.edgeStrokeWidth.applyToSubtree", { nodeId: props.nodeId, strokeWidth });
      setOpenId(null);
    };
    const rainbowEnabled = (() => {
      if (!doc3) return false;
      const rootId = doc3.roots.includes(props.nodeId) ? props.nodeId : getNodeRootId(doc3, props.nodeId) ?? props.nodeId;
      const projectEnabled = Boolean(doc3.theme?.rainbow?.enabled);
      const override = doc3.theme?.rootRainbowEdges?.[rootId];
      return typeof override === "boolean" ? override : projectEnabled;
    })();
    const canClearChildLayouts = props.isCommandEnabled("layout.node.clearActiveRootSubtreeLayouts");
    const activeLayout = doc3?.nodes?.[props.nodeId]?.layout ?? null;
    const rootLayoutSource = doc3?.nodes?.[props.nodeId]?.data?.[ROOT_LAYOUT_SOURCE_KEY_V1];
    const layoutInheritsProjectDefault = variant === "root" && rootLayoutSource === "project-default";
    const activeThemeId = (() => {
      if (variant !== "root") return null;
      if (!doc3) return null;
      const rootId = doc3.roots.includes(props.nodeId) ? props.nodeId : getNodeRootId(doc3, props.nodeId) ?? props.nodeId;
      const themeRef = doc3.theme?.rootThemes?.[rootId] ?? doc3.theme?.defaultTheme;
      if (!themeRef) return null;
      const definition = resolveThemeDefinition(themeRef, doc3.assets) ?? null;
      if (!definition) return null;
      return definition.id;
    })();
    const themeCatalog = (() => {
      const custom = props.themeCatalog?.() ?? [];
      if (custom.length > 0) return custom;
      return THEME_PRESETS_APP.map((preset) => ({
        catalogKey: `official:${preset.id}`,
        id: preset.id,
        name: preset.name,
        theme: preset.theme,
        source: "official"
      }));
    })();
    const activeEdgeRoute = (() => {
      if (variant !== "root") return null;
      if (!doc3) return null;
      const rootId = doc3.roots.includes(props.nodeId) ? props.nodeId : getNodeRootId(doc3, props.nodeId) ?? props.nodeId;
      const stored = doc3.theme?.rootEdgeRoutes?.[rootId];
      if (stored === "cubic" || stored === "quadratic" || stored === "center-quadratic" || stored === "center-quadratic-tapered" || stored === "edge-lead-quadratic" || stored === "edge-lead-quadratic-tapered" || stored === "cubic-tail" || stored === "baseline-fork" || stored === "straight" || stored === "orthogonal" || stored === "orthogonal-rounded" || stored === "tapered") return stored;
      const subtreeIds = collectSubtreeNodeIds(doc3, rootId);
      let selection = null;
      for (const nodeId of subtreeIds) {
        if (nodeId === rootId) continue;
        const patch = doc3.theme?.overrides?.nodes?.[nodeId]?.incomingEdge?.routeType;
        const routeType = patch === "cubic" || patch === "quadratic" || patch === "center-quadratic" || patch === "center-quadratic-tapered" || patch === "edge-lead-quadratic" || patch === "edge-lead-quadratic-tapered" || patch === "cubic-tail" || patch === "baseline-fork" || patch === "straight" || patch === "orthogonal" || patch === "orthogonal-rounded" || patch === "tapered" ? patch : "inherit";
        if (!selection) {
          selection = routeType;
          continue;
        }
        if (selection !== routeType) return null;
      }
      return selection ?? "inherit";
    })();
    const activeEdgeDash = (() => {
      if (!doc3) return null;
      const rootId = variant === "root" ? doc3.roots.includes(props.nodeId) ? props.nodeId : getNodeRootId(doc3, props.nodeId) ?? props.nodeId : props.nodeId;
      const patch = doc3.theme?.edgeStyleScopes?.[rootId]?.dasharray;
      return typeof patch === "string" && patch.trim().length > 0 ? patch.trim() : "inherit";
    })();
    const activeEdgeStrokeWidth = (() => {
      if (variant !== "root") return null;
      if (!doc3) return null;
      const rootId = doc3.roots.includes(props.nodeId) ? props.nodeId : getNodeRootId(doc3, props.nodeId) ?? props.nodeId;
      const patch = doc3.theme?.edgeStyleScopes?.[rootId]?.strokeWidth;
      return typeof patch === "number" && Number.isFinite(patch) ? patch : "inherit";
    })();
    return /* @__PURE__ */ (0, import_jsx_runtime33.jsxs)(import_jsx_runtime33.Fragment, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime33.jsx)("div", { style: { padding: 12, fontSize: 12, fontWeight: 650, color: "var(--km-text)", ...popoverStickyTitleStyle }, children: t("app.selectionToolbar.changeTheme") }),
      showLayoutSection ? /* @__PURE__ */ (0, import_jsx_runtime33.jsxs)("div", { style: { padding: 10 }, children: [
        /* @__PURE__ */ (0, import_jsx_runtime33.jsx)("div", { style: { fontSize: 11, fontWeight: 700, color: "var(--km-muted)", letterSpacing: "0.04em", textTransform: "uppercase" }, children: t("editor.changeTheme.section.layout") }),
        renderPreviewGrid(
          /* @__PURE__ */ (0, import_jsx_runtime33.jsxs)(import_jsx_runtime33.Fragment, { children: [
            renderPreviewCard({
              title: t("editor.changeTheme.option.inherit"),
              active: variant === "root" ? layoutInheritsProjectDefault : activeLayout === null,
              preview: /* @__PURE__ */ (0, import_jsx_runtime33.jsx)("div", { style: { width: "100%", height: "100%", borderRadius: 8, border: "1px dashed var(--km-border)", display: "flex", alignItems: "center", justifyContent: "center", color: "var(--km-muted)", fontSize: 12 }, children: t("editor.changeTheme.option.inherit") }),
              onClick: () => applyLayout("inherit")
            }),
            allowedLayouts.map((layout) => {
              const preview = resolveLayoutPreviewKind(layout);
              const layoutLabel = resolveLocalizedLayoutLabel(t, layout);
              return renderPreviewCard({
                title: layoutLabel,
                active: variant === "root" ? !layoutInheritsProjectDefault && activeLayout === layout : activeLayout === layout,
                preview: preview ? /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(LayoutPreviewSvg, { "aria-hidden": "true", layout: preview, style: { width: "100%", height: "100%", display: "block" } }) : /* @__PURE__ */ (0, import_jsx_runtime33.jsx)("div", { style: { width: "100%", height: "100%", borderRadius: 8, border: "1px dashed var(--km-border)", display: "flex", alignItems: "center", justifyContent: "center", color: "var(--km-muted)", fontSize: 12 }, children: layoutLabel }),
                onClick: () => applyLayout(layout)
              });
            })
          ] })
        )
      ] }) : null,
      variant === "root" ? /* @__PURE__ */ (0, import_jsx_runtime33.jsxs)(import_jsx_runtime33.Fragment, { children: [
        allowChildLayoutOverride ? /* @__PURE__ */ (0, import_jsx_runtime33.jsxs)(import_jsx_runtime33.Fragment, { children: [
          renderSeparator(),
          renderSection({
            title: t("editor.changeTheme.section.reset"),
            children: /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(import_jsx_runtime33.Fragment, { children: renderChipButton({
              title: t("editor.changeTheme.action.clearChildLayouts"),
              disabled: !canClearChildLayouts,
              onClick: () => {
                void props.dispatchCommand("layout.node.clearActiveRootSubtreeLayouts");
                setOpenId(null);
              }
            }) })
          })
        ] }) : null,
        renderSeparator(),
        /* @__PURE__ */ (0, import_jsx_runtime33.jsxs)("div", { style: { padding: 10 }, children: [
          /* @__PURE__ */ (0, import_jsx_runtime33.jsx)("div", { style: { fontSize: 11, fontWeight: 700, color: "var(--km-muted)", letterSpacing: "0.04em", textTransform: "uppercase" }, children: t("editor.changeTheme.section.edgeRoute") }),
          renderPreviewGrid(
            /* @__PURE__ */ (0, import_jsx_runtime33.jsxs)(import_jsx_runtime33.Fragment, { children: [
              renderPreviewCard({
                title: t("editor.changeTheme.option.inherit"),
                active: activeEdgeRoute === "inherit",
                preview: /* @__PURE__ */ (0, import_jsx_runtime33.jsx)("div", { style: { width: "100%", height: "100%", borderRadius: 8, border: "1px dashed var(--km-border)", display: "flex", alignItems: "center", justifyContent: "center", color: "var(--km-muted)", fontSize: 12 }, children: t("editor.changeTheme.option.inherit") }),
                onClick: () => applyEdgeRoute("inherit")
              }),
              CHANGE_THEME_EDGE_ROUTES.map((route) => {
                const routeLabel = resolveLocalizedEdgeRouteLabel(t, route);
                return renderPreviewCard({
                  title: routeLabel,
                  active: activeEdgeRoute === route,
                  preview: /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(EdgeRoutePreviewSvg, { "aria-hidden": "true", route, style: { width: "100%", height: "100%", display: "block" } }),
                  onClick: () => applyEdgeRoute(route)
                });
              })
            ] }),
            118
          )
        ] }),
        renderSeparator(),
        renderSection({
          title: t("editor.changeTheme.section.edgeStyle"),
          children: /* @__PURE__ */ (0, import_jsx_runtime33.jsxs)(import_jsx_runtime33.Fragment, { children: [
            renderChipButton({ title: t("editor.changeTheme.edgeStyle.solid"), active: activeEdgeDash === "inherit", onClick: () => applyEdgeDasharray("inherit") }),
            renderChipButton({ title: t("editor.changeTheme.edgeStyle.dashed"), active: activeEdgeDash === "6 4", onClick: () => applyEdgeDasharray("6 4") })
          ] })
        }),
        renderSeparator(),
        renderSection({
          title: t("editor.changeTheme.section.edgeWidth"),
          children: /* @__PURE__ */ (0, import_jsx_runtime33.jsxs)(import_jsx_runtime33.Fragment, { children: [
            renderChipButton({ title: t("editor.changeTheme.option.inherit"), active: activeEdgeStrokeWidth === "inherit", onClick: () => applyEdgeStrokeWidth("inherit") }),
            [1, 2, 3, 4].map(
              (width) => renderChipButton({ id: String(width), title: `${width}`, active: activeEdgeStrokeWidth === width, onClick: () => applyEdgeStrokeWidth(width) })
            )
          ] })
        }),
        renderSeparator(),
        /* @__PURE__ */ (0, import_jsx_runtime33.jsxs)("div", { style: { padding: 10 }, children: [
          /* @__PURE__ */ (0, import_jsx_runtime33.jsx)("div", { style: { fontSize: 11, fontWeight: 700, color: "var(--km-muted)", letterSpacing: "0.04em", textTransform: "uppercase" }, children: t("editor.changeTheme.section.theme") }),
          renderPreviewGrid(
            /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(import_jsx_runtime33.Fragment, { children: themeCatalog.map(
              (theme) => renderPreviewCard({
                id: theme.catalogKey ?? `${theme.source ?? "theme"}:${theme.id}`,
                title: theme.source === "official" ? resolveLocalizedThemePresetName(t, theme) : theme.name,
                active: Boolean(activeThemeId && theme.theme.id === activeThemeId),
                minHeight: 128,
                preview: /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(ThemePreviewSvg, { "aria-hidden": "true", style: { width: "100%", height: "auto", display: "block", borderRadius: 6 }, theme: theme.theme }),
                onClick: () => applyTheme(theme)
              })
            ) }),
            162
          )
        ] }),
        renderSeparator(),
        /* @__PURE__ */ (0, import_jsx_runtime33.jsxs)("div", { style: { padding: 10, display: "flex", alignItems: "center", justifyContent: "space-between", gap: 10 }, children: [
          /* @__PURE__ */ (0, import_jsx_runtime33.jsx)("div", { style: { fontSize: 12, color: "var(--km-text)" }, children: t("editor.changeTheme.rainbowEdges") }),
          /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(
            "button",
            {
              onClick: () => {
                void props.dispatchCommand("theme.rainbow.toggleForRoot", { rootNodeId: props.nodeId });
                setOpenId(null);
              },
              style: {
                height: 30,
                padding: "0 10px",
                borderRadius: 999,
                border: "1px solid var(--km-border)",
                background: rainbowEnabled ? "rgba(34,197,94,0.14)" : "transparent",
                color: "var(--km-text)",
                fontSize: 12,
                cursor: "pointer"
              },
              tabIndex: -1,
              type: "button",
              children: rainbowEnabled ? t("editor.changeTheme.toggle.on") : t("editor.changeTheme.toggle.off")
            }
          )
        ] })
      ] }) : /* @__PURE__ */ (0, import_jsx_runtime33.jsxs)(import_jsx_runtime33.Fragment, { children: [
        allowChildLayoutOverride ? /* @__PURE__ */ (0, import_jsx_runtime33.jsxs)(import_jsx_runtime33.Fragment, { children: [
          renderSeparator(),
          renderSection({
            title: t("editor.changeTheme.section.reset"),
            children: /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(import_jsx_runtime33.Fragment, { children: renderChipButton({
              title: t("editor.changeTheme.action.clearChildLayouts"),
              disabled: !canClearChildLayouts,
              onClick: () => {
                void props.dispatchCommand("layout.node.clearActiveRootSubtreeLayouts");
                setOpenId(null);
              }
            }) })
          })
        ] }) : null,
        renderSeparator(),
        renderSection({
          title: t("editor.changeTheme.section.edgeStyle"),
          children: /* @__PURE__ */ (0, import_jsx_runtime33.jsxs)(import_jsx_runtime33.Fragment, { children: [
            renderChipButton({ title: t("editor.changeTheme.edgeStyle.solid"), active: activeEdgeDash === "inherit", onClick: () => applyEdgeDasharray("inherit") }),
            renderChipButton({ title: t("editor.changeTheme.edgeStyle.dashed"), active: activeEdgeDash === "6 4", onClick: () => applyEdgeDasharray("6 4") })
          ] })
        })
      ] })
    ] });
  };
  const renderNodeStylePopover = () => {
    const override = doc3?.theme?.overrides?.nodes?.[props.nodeId] ?? void 0;
    const resolved = doc3 ? resolveNodeTheme(doc3, props.nodeId) : null;
    const shape = resolved?.nodeShape;
    const shapeType = shape?.type ?? "rounded-rect";
    const nodeFill = resolved?.paint.nodeFill ?? "rgba(148,163,184,0.12)";
    const nodeStroke = resolved?.paint.nodeStroke ?? "rgba(148,163,184,0.65)";
    const nodeTextColor = resolved?.paint.text ?? "var(--km-text)";
    const strokeDasharray = typeof shape?.dasharray === "string" && shape.dasharray.trim().length > 0 ? shape.dasharray.trim() : null;
    const strokeWidth = resolveNodeStrokeWidth(shape);
    const fontSizeOverride = typeof override?.layout?.fontSize === "number" ? override.layout.fontSize : null;
    const fontWeightOverride = typeof override?.layout?.fontWeight === "number" ? override.layout.fontWeight : null;
    const textAlignOverride = typeof override?.layout?.textAlign === "string" ? override.layout.textAlign : null;
    const textColorOverride = typeof override?.paint?.text === "string" ? override.paint.text : null;
    const resolvedFontSize = resolved?.layout.fontSize ?? 14;
    const resolvedFontWeight = resolved?.layout.fontWeight ?? 400;
    const resolvedTextAlign = resolved?.layout.textAlign ?? "left";
    const previewTextAnchor = resolvedTextAlign === "left" ? "start" : resolvedTextAlign === "right" ? "end" : "middle";
    const previewTextX = resolvedTextAlign === "left" ? 12 : resolvedTextAlign === "right" ? 108 : 60;
    const previewFontWeight = resolvedFontWeight >= 600 ? 700 : 400;
    const resolvedFontWeightLabel = resolvedFontWeight >= 600 ? t("editor.nodeStyle.text.fontWeight.bold") : t("editor.nodeStyle.text.fontWeight.normal");
    const resolvedTextAlignLabel = resolvedTextAlign === "left" ? t("editor.nodeStyle.text.align.left") : resolvedTextAlign === "right" ? t("editor.nodeStyle.text.align.right") : t("editor.nodeStyle.text.align.center");
    const applyOverride = (patch) => {
      void props.dispatchCommand("theme.nodeOverride.merge", { nodeId: props.nodeId, patch });
    };
    const listOverrideKeys = (value) => {
      if (!value || typeof value !== "object" || Array.isArray(value)) return [];
      const keys3 = [];
      for (const [key, rawValue] of Object.entries(value)) {
        if (rawValue === void 0) continue;
        keys3.push(key);
      }
      keys3.sort((a2, b2) => a2.localeCompare(b2));
      return keys3;
    };
    const overrideLayoutKeys = listOverrideKeys(override?.layout);
    const overridePaintKeys = listOverrideKeys(override?.paint);
    const overrideNodeShapeKeys = listOverrideKeys(override?.nodeShape);
    const overrideIncomingEdgeKeys = listOverrideKeys(override?.incomingEdge);
    const overrideBadges = [
      ...overrideLayoutKeys.map((key) => `layout.${key}`),
      ...overridePaintKeys.map((key) => `paint.${key}`),
      ...overrideNodeShapeKeys.map((key) => `nodeShape.${key}`),
      ...overrideIncomingEdgeKeys.map((key) => `incomingEdge.${key}`)
    ];
    const hasAnyOverride = overrideBadges.length > 0;
    const applyShapeType = (type) => {
      applyOverride({ nodeShape: { type, ...type === "rounded-rect" ? { radius: 12 } : {} } });
    };
    const applyStrokeDash = (dash) => {
      applyOverride({ nodeShape: { dasharray: dash } });
    };
    const applyStrokeWidth = (value) => {
      applyOverride({ nodeShape: { strokeWidth: value } });
    };
    const applyStrokeColor = (color) => {
      applyOverride({ paint: { nodeStroke: color } });
    };
    const applyFillColor = (color) => {
      applyOverride({ paint: { nodeFill: color } });
    };
    const applyFontSize = (value) => {
      applyOverride({ layout: { fontSize: value } });
    };
    const applyFontWeight = (value) => {
      applyOverride({ layout: { fontWeight: value } });
    };
    const applyTextAlign = (value) => {
      applyOverride({ layout: { textAlign: value } });
    };
    const applyTextColor = (value) => {
      applyOverride({ paint: { text: value } });
    };
    const applyToSiblingsDisabled = !props.isCommandEnabled("theme.nodeStyle.applyToSiblings", { nodeId: props.nodeId });
    const palette = ["#0ea5e9", "#22c55e", "#f59e0b", "#ef4444", "#a855f7", "#0f172a", "#ffffff"];
    const normalizedStroke = nodeStroke.toLowerCase();
    const normalizedFill = nodeFill.toLowerCase();
    const normalizedTextOverride = textColorOverride ? textColorOverride.toLowerCase() : null;
    return /* @__PURE__ */ (0, import_jsx_runtime33.jsxs)(import_jsx_runtime33.Fragment, { children: [
      /* @__PURE__ */ (0, import_jsx_runtime33.jsxs)("div", { style: { ...popoverStickyTitleStyle, zIndex: 4 }, children: [
        /* @__PURE__ */ (0, import_jsx_runtime33.jsxs)("div", { style: { padding: 12, display: "flex", alignItems: "center", justifyContent: "space-between", gap: 10 }, children: [
          /* @__PURE__ */ (0, import_jsx_runtime33.jsx)("div", { style: { fontSize: 12, fontWeight: 650, color: "var(--km-text)" }, children: t("app.selectionToolbar.nodeStyle") }),
          renderChipButton({
            id: "node-style.reset",
            title: t("editor.nodeStyle.action.reset"),
            disabled: !hasAnyOverride,
            onClick: () => applyOverride(null)
          })
        ] }),
        renderSeparator(),
        /* @__PURE__ */ (0, import_jsx_runtime33.jsxs)("div", { style: { padding: 12 }, children: [
          /* @__PURE__ */ (0, import_jsx_runtime33.jsx)("div", { style: { fontSize: 11, fontWeight: 700, color: "var(--km-muted)", letterSpacing: "0.04em", textTransform: "uppercase" }, children: t("editor.nodeStyle.preview.title") }),
          /* @__PURE__ */ (0, import_jsx_runtime33.jsx)("div", { style: { marginTop: 10, display: "flex", justifyContent: "center" }, children: /* @__PURE__ */ (0, import_jsx_runtime33.jsxs)("svg", { height: 56, style: { display: "block" }, viewBox: "0 0 120 56", width: 120, children: [
            renderNodeShape({
              x: 0,
              y: 4,
              width: 120,
              height: 48,
              shape,
              fill: nodeFill,
              stroke: nodeStroke,
              strokeWidth
            }),
            /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(
              "text",
              {
                dominantBaseline: "middle",
                fill: nodeTextColor,
                fontFamily: "ui-sans-serif, system-ui, sans-serif",
                fontSize: resolvedFontSize,
                fontWeight: previewFontWeight,
                textAnchor: previewTextAnchor,
                x: previewTextX,
                y: 28,
                children: t("editor.nodeStyle.preview.nodeLabel")
              }
            )
          ] }) })
        ] })
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime33.jsxs)("div", { style: { padding: 10 }, children: [
        /* @__PURE__ */ (0, import_jsx_runtime33.jsx)("div", { style: { fontSize: 11, fontWeight: 700, color: "var(--km-muted)", letterSpacing: "0.04em", textTransform: "uppercase" }, children: t("editor.nodeStyle.section.text") }),
        /* @__PURE__ */ (0, import_jsx_runtime33.jsxs)("div", { style: { marginTop: 8, display: "flex", flexWrap: "wrap", gap: 8 }, children: [
          renderChipButton({
            title: t("editor.nodeStyle.text.fontSize.inherit", { size: resolvedFontSize }),
            active: fontSizeOverride == null,
            onClick: () => applyFontSize(null)
          }),
          [12, 14, 16, 18, 20, 24].map(
            (size) => renderChipButton({ title: `${size}px`, active: fontSizeOverride === size, onClick: () => applyFontSize(size) })
          )
        ] }),
        renderSeparator(),
        /* @__PURE__ */ (0, import_jsx_runtime33.jsxs)("div", { style: { marginTop: 10, display: "flex", flexWrap: "wrap", gap: 8 }, children: [
          renderChipButton({
            id: "fontWeight:inherit",
            title: t("editor.nodeStyle.text.fontWeight.inherit", { weight: resolvedFontWeightLabel }),
            active: fontWeightOverride == null,
            onClick: () => applyFontWeight(null)
          }),
          renderChipButton({
            id: "fontWeight:normal",
            title: t("editor.nodeStyle.text.fontWeight.normal"),
            active: typeof fontWeightOverride === "number" && fontWeightOverride < 600,
            onClick: () => applyFontWeight(400)
          }),
          renderChipButton({
            id: "fontWeight:bold",
            title: t("editor.nodeStyle.text.fontWeight.bold"),
            active: typeof fontWeightOverride === "number" && fontWeightOverride >= 600,
            onClick: () => applyFontWeight(700)
          })
        ] }),
        renderSeparator(),
        /* @__PURE__ */ (0, import_jsx_runtime33.jsxs)("div", { style: { marginTop: 10, display: "flex", flexWrap: "wrap", gap: 8 }, children: [
          renderChipButton({
            title: t("editor.nodeStyle.text.align.inherit", { align: resolvedTextAlignLabel }),
            active: textAlignOverride == null,
            onClick: () => applyTextAlign(null)
          }),
          ["left", "center", "right"].map(
            (align) => renderChipButton({
              title: align === "left" ? t("editor.nodeStyle.text.align.left") : align === "right" ? t("editor.nodeStyle.text.align.right") : t("editor.nodeStyle.text.align.center"),
              active: textAlignOverride === align,
              onClick: () => applyTextAlign(align)
            })
          )
        ] }),
        renderSeparator(),
        /* @__PURE__ */ (0, import_jsx_runtime33.jsxs)("div", { style: { marginTop: 10, display: "flex", flexWrap: "wrap", gap: 8 }, children: [
          palette.map((color) => /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(
            "button",
            {
              onClick: () => applyTextColor(color),
              style: {
                width: 22,
                height: 22,
                borderRadius: 999,
                border: color.toLowerCase() === normalizedTextOverride ? "2px solid var(--km-text)" : "1px solid var(--km-border)",
                background: color,
                boxSizing: "border-box",
                cursor: "pointer"
              },
              tabIndex: -1,
              type: "button"
            },
            `text:${color}`
          )),
          renderChipButton({ title: t("editor.nodeStyle.text.color.inherit"), active: textColorOverride == null, onClick: () => applyTextColor(null) })
        ] })
      ] }),
      renderSeparator(),
      renderSection({
        title: t("editor.nodeStyle.section.shape"),
        children: /* @__PURE__ */ (0, import_jsx_runtime33.jsxs)(import_jsx_runtime33.Fragment, { children: [
          renderChipButton({ title: t("editor.nodeStyle.shape.rounded"), active: shapeType === "rounded-rect", onClick: () => applyShapeType("rounded-rect") }),
          renderChipButton({ title: t("editor.nodeStyle.shape.rect"), active: shapeType === "rect", onClick: () => applyShapeType("rect") }),
          renderChipButton({ title: t("editor.nodeStyle.shape.diamond"), active: shapeType === "diamond", onClick: () => applyShapeType("diamond") }),
          renderChipButton({ title: t("editor.nodeStyle.shape.ellipse"), active: shapeType === "ellipse", onClick: () => applyShapeType("ellipse") }),
          renderChipButton({ title: t("editor.nodeStyle.shape.pill"), active: shapeType === "pill", onClick: () => applyShapeType("pill") })
        ] })
      }),
      renderSeparator(),
      /* @__PURE__ */ (0, import_jsx_runtime33.jsxs)("div", { style: { padding: 10 }, children: [
        /* @__PURE__ */ (0, import_jsx_runtime33.jsx)("div", { style: { fontSize: 11, fontWeight: 700, color: "var(--km-muted)", letterSpacing: "0.04em", textTransform: "uppercase" }, children: t("editor.nodeStyle.section.border") }),
        /* @__PURE__ */ (0, import_jsx_runtime33.jsxs)("div", { style: { marginTop: 8, display: "flex", flexWrap: "wrap", gap: 8 }, children: [
          renderChipButton({ title: t("editor.nodeStyle.border.solid"), active: !strokeDasharray, onClick: () => applyStrokeDash(null) }),
          renderChipButton({ title: t("editor.nodeStyle.border.dashed"), active: Boolean(strokeDasharray), onClick: () => applyStrokeDash("6 4") })
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime33.jsxs)("div", { style: { marginTop: 10, display: "flex", alignItems: "center", gap: 10 }, children: [
          /* @__PURE__ */ (0, import_jsx_runtime33.jsx)("div", { style: { fontSize: 12, color: "var(--km-muted)" }, children: t("editor.nodeStyle.border.width") }),
          /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(
            "input",
            {
              "aria-label": t("editor.nodeStyle.border.width.aria"),
              max: 12,
              min: 0,
              onChange: (event) => applyStrokeWidth(Number(event.target.value)),
              step: 0.5,
              type: "range",
              value: strokeWidth
            }
          )
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime33.jsxs)("div", { style: { marginTop: 10, display: "flex", flexWrap: "wrap", gap: 8 }, children: [
          palette.map((color) => /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(
            "button",
            {
              onClick: () => applyStrokeColor(color),
              style: {
                width: 22,
                height: 22,
                borderRadius: 999,
                border: color.toLowerCase() === normalizedStroke ? "2px solid var(--km-text)" : "1px solid var(--km-border)",
                background: color,
                boxSizing: "border-box",
                cursor: "pointer"
              },
              tabIndex: -1,
              type: "button"
            },
            color
          )),
          /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(
            "button",
            {
              onClick: () => applyStrokeColor(null),
              style: {
                height: 22,
                padding: "0 10px",
                borderRadius: 999,
                border: "1px solid var(--km-border)",
                background: "transparent",
                color: "var(--km-muted)",
                fontSize: 12,
                cursor: "pointer"
              },
              tabIndex: -1,
              type: "button",
              children: t("editor.nodeStyle.border.clear")
            }
          )
        ] })
      ] }),
      renderSeparator(),
      /* @__PURE__ */ (0, import_jsx_runtime33.jsxs)("div", { style: { padding: 10 }, children: [
        /* @__PURE__ */ (0, import_jsx_runtime33.jsx)("div", { style: { fontSize: 11, fontWeight: 700, color: "var(--km-muted)", letterSpacing: "0.04em", textTransform: "uppercase" }, children: t("editor.nodeStyle.section.background") }),
        /* @__PURE__ */ (0, import_jsx_runtime33.jsxs)("div", { style: { marginTop: 10, display: "flex", flexWrap: "wrap", gap: 8 }, children: [
          palette.map((color) => /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(
            "button",
            {
              onClick: () => applyFillColor(color),
              style: {
                width: 22,
                height: 22,
                borderRadius: 999,
                border: color.toLowerCase() === normalizedFill ? "2px solid var(--km-text)" : "1px solid var(--km-border)",
                background: color,
                boxSizing: "border-box",
                cursor: "pointer"
              },
              tabIndex: -1,
              type: "button"
            },
            `fill:${color}`
          )),
          /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(
            "button",
            {
              onClick: () => applyFillColor(null),
              style: {
                height: 22,
                padding: "0 10px",
                borderRadius: 999,
                border: "1px solid var(--km-border)",
                background: "transparent",
                color: "var(--km-muted)",
                fontSize: 12,
                cursor: "pointer"
              },
              tabIndex: -1,
              type: "button",
              children: t("editor.nodeStyle.background.clear")
            }
          )
        ] })
      ] }),
      renderSeparator(),
      renderSection({
        title: t("editor.nodeStyle.section.scope"),
        children: /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(import_jsx_runtime33.Fragment, { children: renderChipButton({
          title: t("editor.nodeStyle.scope.applyToSiblings"),
          disabled: applyToSiblingsDisabled,
          onClick: () => {
            void props.dispatchCommand("theme.nodeStyle.applyToSiblings", { nodeId: props.nodeId });
            setOpenId(null);
          }
        }) })
      })
    ] });
  };
  const renderSelectionPopoverVariant = (variant) => {
    if (variant === "selection.change-theme.root") return renderChangeThemePopover("root");
    if (variant === "selection.change-theme.child") return renderChangeThemePopover("child");
    if (variant === "selection.node-style") return renderNodeStylePopover();
    return /* @__PURE__ */ (0, import_jsx_runtime33.jsxs)("div", { style: { padding: 12, fontSize: 12, color: "var(--km-muted)" }, children: [
      "Popover variant:",
      " ",
      /* @__PURE__ */ (0, import_jsx_runtime33.jsx)("span", { style: { fontFamily: "ui-monospace, SFMono-Regular, Menlo, monospace" }, children: variant })
    ] });
  };
  const triggerQuickAction = (0, import_react28.useCallback)((actionId, args) => {
    const action = props.quickActions.find((item) => item.id === actionId) ?? null;
    if (!action) return;
    const toggle = args?.toggle === true;
    const expandToolbar = args?.expandToolbar !== false;
    const anchor = args?.anchorRect ? resolveAnchorFromTriggerRect(actionId, args.anchorRect) : expandToolbar ? resolveSyntheticQuickActionAnchor(actionId) : resolveNodeSidePopoverAnchor(actionId);
    if (action.source === "registry") {
      const item = action.item;
      if (item.kind === "button") {
        const disabled = !props.isCommandEnabled(item.commandId, item.args);
        if (disabled) return;
        if (item.id === "selection.relation.start") {
          setRelationPickerCursor(null);
        }
        closeQuickActionPopover();
        void props.dispatchCommand(item.commandId, item.args);
        return;
      }
      if (item.kind === "popover") {
        if (isSelectionPopoverDisabled(item.popover, props.snapshot)) return;
      }
      if (toggle && openId === actionId) {
        closeQuickActionPopover();
        return;
      }
      setOpenAnchor(anchor);
      setOpenId(actionId);
      setExpanded(expandToolbar);
      return;
    }
    switch (action.builtinId) {
      case "builtin.links": {
        if (props.onOpenLinksPanel) {
          closeQuickActionPopover();
          setExpanded(expandToolbar);
          props.onOpenLinksPanel({ nodeId: props.nodeId, mode: "edit" });
          return;
        }
        if (toggle && openId === actionId) {
          closeQuickActionPopover();
          return;
        }
        setLinksMode("edit");
        setOpenAnchor(anchor);
        setOpenId(actionId);
        setExpanded(expandToolbar);
        return;
      }
      case "builtin.image":
      case "builtin.icons":
      case "builtin.tags": {
        if (toggle && openId === actionId) {
          closeQuickActionPopover();
          return;
        }
        setOpenAnchor(anchor);
        setOpenId(actionId);
        setExpanded(expandToolbar);
        return;
      }
      case "builtin.brush": {
        if (formatPainter) {
          setFormatPainter(null);
          return;
        }
        if (!doc3 || !formatPainterSourcePatch) return;
        const resolved = resolveNodeTheme(doc3, props.nodeId);
        const strokeWidth = resolveNodeStrokeWidth(resolved.nodeShape);
        setFormatPainter({
          sourceNodeId: props.nodeId,
          patch: formatPainterSourcePatch,
          preview: {
            shape: resolved.nodeShape,
            fill: resolved.paint.nodeFill,
            stroke: resolved.paint.nodeStroke,
            strokeWidth,
            textColor: resolved.paint.text
          }
        });
        closeQuickActionPopover();
        return;
      }
      case "builtin.notes": {
        if (props.onOpenMetaPopover) {
          closeQuickActionPopover();
          setExpanded(expandToolbar);
          props.onOpenMetaPopover({ kind: "notes", nodeId: props.nodeId, mode: "edit" });
          return;
        }
        if (toggle && openId === actionId) {
          closeQuickActionPopover();
          return;
        }
        setNotesMode("edit");
        setOpenAnchor(anchor);
        setOpenId(actionId);
        setExpanded(expandToolbar);
        return;
      }
      case "builtin.comments": {
        if (props.onOpenMetaPopover) {
          closeQuickActionPopover();
          setExpanded(expandToolbar);
          props.onOpenMetaPopover({ kind: "comments", nodeId: props.nodeId, mode: "edit" });
          return;
        }
        if (toggle && openId === actionId) {
          closeQuickActionPopover();
          return;
        }
        setCommentsMode("edit");
        setOpenAnchor(anchor);
        setOpenId(actionId);
        setExpanded(expandToolbar);
      }
    }
  }, [
    closeQuickActionPopover,
    doc3,
    formatPainter,
    formatPainterSourcePatch,
    openId,
    props.dispatchCommand,
    props.isCommandEnabled,
    props.nodeId,
    props.onOpenLinksPanel,
    props.onOpenMetaPopover,
    props.quickActions,
    props.snapshot,
    resolveAnchorFromTriggerRect,
    resolveNodeSidePopoverAnchor,
    resolveSyntheticQuickActionAnchor
  ]);
  (0, import_react28.useEffect)(() => {
    const request = props.actionRequest;
    if (!request) return;
    if (!props.visible) return;
    if (request.nodeId !== props.nodeId) return;
    triggerQuickAction(request.actionId, { toggle: false, expandToolbar: request.presentation !== "popover-only" });
    props.onActionRequestHandled?.(request.requestId);
  }, [props.actionRequest, props.nodeId, props.onActionRequestHandled, props.visible, triggerQuickAction]);
  const renderToolbarItem = (item) => {
    if (item.kind === "button") {
      const disabled = !props.isCommandEnabled(item.commandId, item.args);
      if (item.icon) {
        return /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(
          IconButton,
          {
            disabled,
            iconId: item.icon,
            label: item.title,
            onPointerDown: (event) => {
              onToolbarButtonPointerDown(event);
              if (disabled) return;
              if (item.id === "selection.relation.start") {
                setRelationPickerCursor({ x: event.clientX, y: event.clientY });
              }
            },
            onClick: () => {
              if (disabled) return;
              void props.dispatchCommand(item.commandId, item.args);
            },
            tabIndex: -1,
            type: "button"
          },
          item.id
        );
      }
      return /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(
        "button",
        {
          disabled,
          onPointerDown: (event) => {
            onToolbarButtonPointerDown(event);
            if (disabled) return;
            if (item.id === "selection.relation.start") {
              setRelationPickerCursor({ x: event.clientX, y: event.clientY });
            }
          },
          onClick: () => {
            if (disabled) return;
            void props.dispatchCommand(item.commandId, item.args);
          },
          style: disabled ? disabledButtonStyle : buttonStyle2,
          tabIndex: -1,
          type: "button",
          children: item.title
        },
        item.id
      );
    }
    if (item.kind === "popover") {
      const disabled = isSelectionPopoverDisabled(item.popover, props.snapshot);
      return /* @__PURE__ */ (0, import_jsx_runtime33.jsx)("div", { children: item.icon ? /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(
        IconButton,
        {
          disabled,
          iconId: item.icon,
          label: item.title,
          onPointerDown: onToolbarButtonPointerDown,
          onClick: (event) => {
            const root = shellRef.current;
            const rootRect = root?.getBoundingClientRect() ?? null;
            const triggerRect = event.currentTarget.getBoundingClientRect();
            setOpenId((prev) => {
              const next = prev === item.id ? null : item.id;
              if (!next) {
                setOpenAnchor(null);
                return null;
              }
              if (!rootRect) {
                setOpenAnchor({ id: next, left: 0, top: 0, width: triggerRect.width, height: triggerRect.height });
                return next;
              }
              setOpenAnchor({
                id: next,
                left: triggerRect.left - rootRect.left,
                top: triggerRect.top - rootRect.top,
                width: triggerRect.width,
                height: triggerRect.height
              });
              return next;
            });
          },
          showChevron: true,
          tabIndex: -1,
          type: "button"
        }
      ) : /* @__PURE__ */ (0, import_jsx_runtime33.jsxs)(
        "button",
        {
          disabled,
          onPointerDown: onToolbarButtonPointerDown,
          onClick: (event) => {
            const root = shellRef.current;
            const rootRect = root?.getBoundingClientRect() ?? null;
            const triggerRect = event.currentTarget.getBoundingClientRect();
            setOpenId((prev) => {
              const next = prev === item.id ? null : item.id;
              if (!next) {
                setOpenAnchor(null);
                return null;
              }
              if (!rootRect) {
                setOpenAnchor({ id: next, left: 0, top: 0, width: triggerRect.width, height: triggerRect.height });
                return next;
              }
              setOpenAnchor({
                id: next,
                left: triggerRect.left - rootRect.left,
                top: triggerRect.top - rootRect.top,
                width: triggerRect.width,
                height: triggerRect.height
              });
              return next;
            });
          },
          style: disabled ? disabledButtonStyle : buttonStyle2,
          tabIndex: -1,
          type: "button",
          children: [
            item.title,
            " \u25BE"
          ]
        }
      ) }, item.id);
    }
    const menuItems = resolveSelectionToolbarMenuItems(item.items, props.snapshot);
    const open2 = openId === item.id;
    return /* @__PURE__ */ (0, import_jsx_runtime33.jsxs)("div", { style: { position: "relative" }, children: [
      item.icon ? /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(
        IconButton,
        {
          iconId: item.icon,
          label: item.title,
          onPointerDown: onToolbarButtonPointerDown,
          onClick: () => setOpenId((prev) => prev === item.id ? null : item.id),
          showChevron: true,
          tabIndex: -1,
          type: "button"
        }
      ) : /* @__PURE__ */ (0, import_jsx_runtime33.jsxs)(
        "button",
        {
          onPointerDown: onToolbarButtonPointerDown,
          onClick: () => setOpenId((prev) => prev === item.id ? null : item.id),
          style: buttonStyle2,
          tabIndex: -1,
          type: "button",
          children: [
            item.title,
            " \u25BE"
          ]
        }
      ),
      open2 ? /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(
        "div",
        {
          style: {
            position: "absolute",
            left: 0,
            top: "calc(100% + 8px)",
            width: 260,
            maxHeight: 320,
            overflow: "auto",
            padding: 6,
            borderRadius: 14,
            border: "1px solid var(--km-border)",
            background: "var(--km-panel)",
            boxShadow: "0 18px 36px rgba(15, 23, 42, 0.18)",
            zIndex: 80
          },
          children: menuItems.map((menuItem) => {
            const disabled = !props.isCommandEnabled(menuItem.commandId, menuItem.args);
            return /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(
              "button",
              {
                disabled,
                onClick: () => {
                  if (disabled) return;
                  setOpenId(null);
                  void props.dispatchCommand(menuItem.commandId, menuItem.args);
                },
                style: {
                  display: "flex",
                  width: "100%",
                  alignItems: "center",
                  justifyContent: "space-between",
                  gap: 10,
                  padding: "8px 10px",
                  borderRadius: 10,
                  border: "none",
                  background: "transparent",
                  color: disabled ? "rgba(100,116,139,0.7)" : "var(--km-text)",
                  fontSize: 13,
                  cursor: disabled ? "not-allowed" : "pointer"
                },
                tabIndex: -1,
                type: "button",
                children: /* @__PURE__ */ (0, import_jsx_runtime33.jsx)("span", { style: { overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }, children: menuItem.title })
              },
              menuItem.id
            );
          })
        }
      ) : null
    ] }, item.id);
  };
  const activeRegistryPopoverItem = openId ? selectionPopoverItemById.get(openId) ?? null : null;
  const onLinkPointerDown = (event) => {
    if (event.button !== 0) return;
    const svg = props.svgRef.current;
    if (!svg) return;
    const win = resolveOwnerWindow(svg) ?? (typeof window !== "undefined" ? window : null);
    if (!win) return;
    event.preventDefault();
    event.stopPropagation();
    const root = shellRef.current;
    const rootRect = root?.getBoundingClientRect() ?? null;
    const triggerRect = event.currentTarget.getBoundingClientRect();
    const anchor = rootRect ? {
      id: "builtin.links",
      left: triggerRect.left - rootRect.left,
      top: triggerRect.top - rootRect.top,
      width: triggerRect.width,
      height: triggerRect.height
    } : { id: "builtin.links", left: 0, top: 0, width: triggerRect.width, height: triggerRect.height };
    const startX = event.clientX;
    const startY = event.clientY;
    let dragging = false;
    let lastTarget = null;
    const clearHighlight = () => {
      lastTarget = null;
      props.onSetHighlightNodeId(null);
    };
    const updateTarget = (clientX, clientY) => {
      const world = clientToWorldPoint({ svg, viewBox: props.viewBox, clientX, clientY });
      if (!world) {
        clearHighlight();
        return;
      }
      const target2 = hitTestNodeId({
        layout: props.layout,
        world,
        hiddenNodeIds: props.hiddenNodeIds,
        ignoreNodeIds: /* @__PURE__ */ new Set([props.nodeId])
      });
      if (target2 === lastTarget) return;
      lastTarget = target2;
      props.onSetHighlightNodeId(target2);
    };
    const onMove = (e) => {
      const dx = e.clientX - startX;
      const dy = e.clientY - startY;
      const distance = Math.hypot(dx, dy);
      if (!dragging && distance > 4) dragging = true;
      if (!dragging) return;
      setLinkPickerCursor({ x: e.clientX, y: e.clientY });
      updateTarget(e.clientX, e.clientY);
    };
    const onUp = (e) => {
      win.removeEventListener("pointermove", onMove, true);
      win.removeEventListener("pointerup", onUp, true);
      setLinkPickerCursor(null);
      if (!dragging) {
        if (props.onOpenLinksPanel) {
          setOpenId(null);
          setOpenAnchor(null);
          props.onOpenLinksPanel({ nodeId: props.nodeId, mode: "edit" });
          return;
        }
        setLinksMode("edit");
        setOpenId((prev) => {
          const next = prev === "builtin.links" ? null : "builtin.links";
          if (!next) {
            setOpenAnchor(null);
            return null;
          }
          setOpenAnchor(anchor);
          return next;
        });
        return;
      }
      const target2 = lastTarget;
      clearHighlight();
      if (!target2) return;
      if (!props.isCommandEnabled("node.link.connect", { nodeId: props.nodeId, targetNodeId: target2 })) {
        props.onPremiumFeatureBlocked?.("backlinks");
        return;
      }
      void props.dispatchCommand("node.link.connect", { nodeId: props.nodeId, targetNodeId: target2 });
    };
    win.addEventListener("pointermove", onMove, true);
    win.addEventListener("pointerup", onUp, true);
  };
  (0, import_react28.useEffect)(() => {
    if (!formatPainter) return;
    const svg = props.svgRef.current;
    if (!svg) return;
    const win = resolveOwnerWindow(svg) ?? (typeof window !== "undefined" ? window : null);
    if (!win) return;
    const onMove = (event) => {
      setFormatPainterCursor({ x: event.clientX, y: event.clientY });
    };
    const onDown = (event) => {
      if (event.button !== 0) return;
      const target2 = event.target;
      if (!isNodeLike(target2)) return;
      if (interactionRootRef.current?.contains(target2)) return;
      if (!svg.contains(target2)) return;
      const world = clientToWorldPoint({ svg, viewBox: props.viewBox, clientX: event.clientX, clientY: event.clientY });
      if (!world) return;
      const hit = hitTestNodeId({
        layout: props.layout,
        world,
        hiddenNodeIds: props.hiddenNodeIds
      });
      if (!hit) return;
      if (hit === formatPainter.sourceNodeId) return;
      void props.dispatchCommand("theme.nodeOverride.merge", { nodeId: hit, patch: formatPainter.patch });
    };
    win.addEventListener("pointermove", onMove, true);
    win.addEventListener("pointerdown", onDown, true);
    return () => {
      win.removeEventListener("pointermove", onMove, true);
      win.removeEventListener("pointerdown", onDown, true);
    };
  }, [formatPainter, props.dispatchCommand, props.hiddenNodeIds, props.layout, props.svgRef, props.viewBox]);
  const panelCollapsedTransform = growthDirection === "left" ? "translateX(8px) scale(0.98)" : growthDirection === "up" ? "translateY(8px) scale(0.98)" : growthDirection === "down" ? "translateY(-8px) scale(0.98)" : "translateX(-8px) scale(0.98)";
  const panelTransformOrigin = growthDirection === "left" ? "right center" : growthDirection === "up" ? "center bottom" : growthDirection === "down" ? "center top" : "left center";
  return /* @__PURE__ */ (0, import_jsx_runtime33.jsxs)(
    "div",
    {
      ref: interactionRootRef,
      "data-km-selection-toolbar-root": "true",
      style: {
        position: "absolute",
        left: 0,
        top: 0,
        width: props.viewport.width,
        height: props.viewport.height,
        pointerEvents: "none",
        opacity: props.controlsHidden ? 0 : 1,
        visibility: props.controlsHidden ? "hidden" : "visible",
        transition: "opacity 120ms ease",
        zIndex: hostChromeSafeZIndex
      },
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(
          "div",
          {
            ref: shellRef,
            "data-km-selection-toolbar-shell": "true",
            style: { position: "absolute", left, top, width: activationWidth, height: activationHeight },
            children: /* @__PURE__ */ (0, import_jsx_runtime33.jsx)("div", { style: { position: "relative", width: activationWidth, height: activationHeight }, children: /* @__PURE__ */ (0, import_jsx_runtime33.jsxs)(
              "div",
              {
                style: {
                  position: "absolute",
                  top: panelTop,
                  left: panelLeft,
                  width: panelWidth,
                  height: panelHeight,
                  boxSizing: "border-box",
                  display: "flex",
                  alignItems: "center",
                  gap: 10,
                  padding: `${panelPadding}px`,
                  borderRadius: 16,
                  border: "1px solid color-mix(in srgb, var(--km-border) 72%, transparent)",
                  background: "color-mix(in srgb, var(--km-panel) 78%, transparent)",
                  boxShadow: "0 16px 40px rgba(15, 23, 42, 0.16)",
                  backdropFilter: "blur(14px)",
                  WebkitBackdropFilter: "blur(14px)",
                  opacity: expanded ? 1 : 0,
                  transform: expanded ? "translateX(0) scale(1)" : panelCollapsedTransform,
                  transformOrigin: panelTransformOrigin,
                  transition: "opacity 180ms ease, transform 220ms cubic-bezier(0.22, 1, 0.36, 1)",
                  pointerEvents: expanded ? "auto" : "none",
                  overflow: "visible"
                },
                children: [
                  /* @__PURE__ */ (0, import_jsx_runtime33.jsx)("div", { style: { display: "flex", alignItems: "center", gap: 8, minWidth: 0 }, children: visibleAreaAItems.map(renderToolbarItem) }),
                  visibleAreaAItems.length > 0 && (visibleAreaCItems.length > 0 || hasVisibleBuiltinActions) ? renderDivider() : null,
                  /* @__PURE__ */ (0, import_jsx_runtime33.jsxs)("div", { style: { display: "flex", alignItems: "center", gap: 8, minWidth: 0 }, children: [
                    visibleAreaCItems.map(renderToolbarItem),
                    isQuickActionVisible("builtin.links") || openId === "builtin.links" ? /* @__PURE__ */ (0, import_jsx_runtime33.jsxs)("div", { children: [
                      /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(
                        IconButton,
                        {
                          iconId: "kmind-icon://builtin/ui/link",
                          label: t("editor.selectionToolbar.button.link"),
                          onPointerDown: onLinkPointerDown,
                          style: !isQuickActionVisible("builtin.links") ? { display: "none" } : void 0,
                          tabIndex: -1,
                          type: "button"
                        }
                      ),
                      openId === "builtin.links" ? renderPopoverPanel({
                        anchorId: "builtin.links",
                        width: 420,
                        maxHeight: 560,
                        children: /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(
                          LinksPanel,
                          {
                            variant: "embedded",
                            backlinksIndex: props.backlinksIndex,
                            clipboard: props.clipboard,
                            doc: doc3,
                            documentId: props.documentId,
                            dialog: props.dialog,
                            dispatchCommand: props.dispatchCommand,
                            external: props.external,
                            maxHeight: 0,
                            mode: linksMode,
                            nodeRefResolveStore: props.nodeRefResolveStore,
                            nodeId: props.nodeId,
                            onClose: () => {
                              setOpenId(null);
                              setOpenAnchor(null);
                            },
                            onHoverChange: () => {
                            },
                            onOpenNodeRef: props.onOpenNodeRef,
                            onRequestModeChange: setLinksMode,
                            onSelectNode: (nodeId) => {
                              props.onSelectNode(nodeId);
                              setOpenId(null);
                              setOpenAnchor(null);
                            },
                            readOnly,
                            resolveNodeRefExists: props.resolveNodeRefExists,
                            resolveNodeRefTitle: props.resolveNodeRefTitle,
                            width: 0,
                            x: 0,
                            y: 0
                          }
                        )
                      }) : null
                    ] }) : null,
                    isQuickActionVisible("builtin.image") || openId === "builtin.image" ? /* @__PURE__ */ (0, import_jsx_runtime33.jsx)("div", { children: /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(
                      IconButton,
                      {
                        iconId: "kmind-icon://builtin/ui/image",
                        label: t("editor.selectionToolbar.button.image"),
                        onPointerDown: onToolbarButtonPointerDown,
                        onClick: (event) => triggerQuickAction("builtin.image", { anchorRect: event.currentTarget.getBoundingClientRect(), toggle: true }),
                        style: !isQuickActionVisible("builtin.image") ? { display: "none" } : void 0,
                        showChevron: true,
                        tabIndex: -1,
                        type: "button"
                      }
                    ) }) : null,
                    isQuickActionVisible("builtin.icons") || openId === "builtin.icons" ? /* @__PURE__ */ (0, import_jsx_runtime33.jsx)("div", { children: /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(
                      IconButton,
                      {
                        iconId: "kmind-icon://builtin/ui/icons",
                        label: t("editor.selectionToolbar.button.icons"),
                        onPointerDown: onToolbarButtonPointerDown,
                        onClick: (event) => triggerQuickAction("builtin.icons", { anchorRect: event.currentTarget.getBoundingClientRect(), toggle: true }),
                        style: !isQuickActionVisible("builtin.icons") ? { display: "none" } : void 0,
                        showChevron: true,
                        tabIndex: -1,
                        type: "button"
                      }
                    ) }) : null,
                    isQuickActionVisible("builtin.tags") || openId === "builtin.tags" ? /* @__PURE__ */ (0, import_jsx_runtime33.jsx)("div", { children: /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(
                      IconButton,
                      {
                        iconId: "kmind-icon://builtin/ui/tags",
                        label: t("editor.selectionToolbar.button.tags"),
                        onPointerDown: onToolbarButtonPointerDown,
                        onClick: (event) => triggerQuickAction("builtin.tags", { anchorRect: event.currentTarget.getBoundingClientRect(), toggle: true }),
                        style: !isQuickActionVisible("builtin.tags") ? { display: "none" } : void 0,
                        showChevron: true,
                        tabIndex: -1,
                        type: "button"
                      }
                    ) }) : null,
                    visibleQuickActionIds.has("builtin.brush") ? /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(
                      IconButton,
                      {
                        disabled: !formatPainter && !canStartFormatPainter,
                        iconId: "kmind-icon://builtin/ui/brush",
                        label: t("editor.selectionToolbar.button.brush"),
                        onPointerDown: (event) => {
                          onToolbarButtonPointerDown(event);
                          setFormatPainterCursor({ x: event.clientX, y: event.clientY });
                        },
                        onClick: () => triggerQuickAction("builtin.brush"),
                        style: formatPainter ? { background: "rgba(148,163,184,0.16)" } : void 0,
                        tabIndex: -1,
                        type: "button"
                      }
                    ) : null,
                    isQuickActionVisible("builtin.notes") || openId === "builtin.notes" ? /* @__PURE__ */ (0, import_jsx_runtime33.jsxs)("div", { children: [
                      /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(
                        IconButton,
                        {
                          iconId: "kmind-icon://builtin/ui/notes",
                          label: t("editor.selectionToolbar.button.notes"),
                          onPointerDown: onToolbarButtonPointerDown,
                          onClick: (event) => triggerQuickAction("builtin.notes", { anchorRect: event.currentTarget.getBoundingClientRect(), toggle: true }),
                          style: {
                            ...hasContentBlock(doc3, props.nodeId, "notes") ? { background: "rgba(148,163,184,0.16)" } : null,
                            ...!isQuickActionVisible("builtin.notes") ? { display: "none" } : null
                          },
                          tabIndex: -1,
                          type: "button"
                        }
                      ),
                      openId === "builtin.notes" ? renderPopoverPanel({
                        anchorId: "builtin.notes",
                        width: 420,
                        maxHeight: 560,
                        children: /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(
                          NodeMetaPopover,
                          {
                            variant: "embedded",
                            assetObjectUrlById: props.assetObjectUrlById ?? void 0,
                            commitRef: metaPopoverCommitRef,
                            core: props.core,
                            dialog: props.dialog,
                            doc: doc3,
                            kind: "notes",
                            maxHeight: 0,
                            mode: notesMode,
                            nodeId: props.nodeId,
                            onAction: props.onNodeAction,
                            onHoverChange: () => {
                            },
                            onRequestClose: () => {
                              setOpenId(null);
                              setOpenAnchor(null);
                            },
                            onRequestModeChange: setNotesMode,
                            readOnly,
                            width: 0,
                            x: 0,
                            y: 0
                          }
                        )
                      }) : null
                    ] }) : null,
                    isQuickActionVisible("builtin.comments") || openId === "builtin.comments" ? /* @__PURE__ */ (0, import_jsx_runtime33.jsxs)("div", { children: [
                      /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(
                        IconButton,
                        {
                          iconId: "kmind-icon://builtin/ui/comments",
                          label: t("editor.selectionToolbar.button.comments"),
                          onPointerDown: onToolbarButtonPointerDown,
                          onClick: (event) => triggerQuickAction("builtin.comments", { anchorRect: event.currentTarget.getBoundingClientRect(), toggle: true }),
                          style: {
                            ...hasContentBlock(doc3, props.nodeId, "comments") ? { background: "rgba(148,163,184,0.16)" } : null,
                            ...!isQuickActionVisible("builtin.comments") ? { display: "none" } : null
                          },
                          tabIndex: -1,
                          type: "button"
                        }
                      ),
                      openId === "builtin.comments" ? renderPopoverPanel({
                        anchorId: "builtin.comments",
                        width: 420,
                        maxHeight: 560,
                        children: /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(
                          NodeMetaPopover,
                          {
                            variant: "embedded",
                            assetObjectUrlById: props.assetObjectUrlById ?? void 0,
                            commitRef: metaPopoverCommitRef,
                            core: props.core,
                            dialog: props.dialog,
                            doc: doc3,
                            kind: "comments",
                            maxHeight: 0,
                            mode: commentsMode,
                            nodeId: props.nodeId,
                            onAction: props.onNodeAction,
                            onHoverChange: () => {
                            },
                            onRequestClose: () => {
                              setOpenId(null);
                              setOpenAnchor(null);
                            },
                            onRequestModeChange: setCommentsMode,
                            readOnly,
                            width: 0,
                            x: 0,
                            y: 0
                          }
                        )
                      }) : null
                    ] }) : null,
                    /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(
                      "button",
                      {
                        onPointerDown: onToolbarButtonPointerDown,
                        onClick: (event) => {
                          const rootRect = shellRef.current?.getBoundingClientRect() ?? null;
                          const triggerRect = event.currentTarget.getBoundingClientRect();
                          const x5 = left + (rootRect ? triggerRect.left - rootRect.left : panelWidth - moreButtonWidth);
                          const y = top + (rootRect ? triggerRect.bottom - rootRect.top + 8 : activationHeight + 8);
                          props.onRequestOpenNodeContextMenu?.({ x: x5, y, nodeId: props.nodeId });
                          closeQuickActionPopover();
                        },
                        style: {
                          width: moreButtonWidth,
                          height: 34,
                          borderRadius: 10,
                          border: "1px solid var(--km-border)",
                          background: overflowQuickActions.length > 0 ? "rgba(148,163,184,0.12)" : "var(--km-panel)",
                          color: "var(--km-text)",
                          cursor: "pointer",
                          flexShrink: 0
                        },
                        tabIndex: -1,
                        type: "button",
                        children: "\u2026"
                      }
                    )
                  ] })
                ]
              }
            ) })
          }
        ),
        activeRegistryPopoverItem ? renderPopoverPanel({
          anchorId: activeRegistryPopoverItem.id,
          children: renderSelectionPopoverVariant(activeRegistryPopoverItem.popover.variant),
          ...activeRegistryPopoverItem.popover.variant === "selection.change-theme.root" ? { width: 440, maxHeight: 620 } : {}
        }) : null,
        openId === "builtin.image" ? renderPopoverPanel({
          anchorId: "builtin.image",
          width: 420,
          maxHeight: 560,
          children: /* @__PURE__ */ (0, import_jsx_runtime33.jsxs)(import_jsx_runtime33.Fragment, { children: [
            /* @__PURE__ */ (0, import_jsx_runtime33.jsx)("div", { style: { padding: 12, fontSize: 12, fontWeight: 650, color: "var(--km-text)", ...popoverStickyTitleStyle }, children: t("editor.image.title") }),
            !image ? /* @__PURE__ */ (0, import_jsx_runtime33.jsxs)("div", { style: { padding: 12 }, children: [
              /* @__PURE__ */ (0, import_jsx_runtime33.jsx)("div", { style: { fontSize: 12, color: "var(--km-muted)", marginBottom: 10 }, children: t("editor.image.empty") }),
              /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(
                "button",
                {
                  disabled: !props.isCommandEnabled("node.image.add", { nodeId: props.nodeId }),
                  onPointerDown: onToolbarButtonPointerDown,
                  onClick: () => void props.dispatchCommand("node.image.add", { nodeId: props.nodeId }),
                  style: props.isCommandEnabled("node.image.add", { nodeId: props.nodeId }) ? buttonStyle2 : disabledButtonStyle,
                  tabIndex: -1,
                  type: "button",
                  children: t("editor.image.action.insert")
                }
              ),
              /* @__PURE__ */ (0, import_jsx_runtime33.jsx)("div", { style: { marginTop: 10, fontSize: 11, color: "var(--km-muted)" }, children: t("editor.image.hint.pasteReplace") })
            ] }) : /* @__PURE__ */ (0, import_jsx_runtime33.jsxs)(import_jsx_runtime33.Fragment, { children: [
              /* @__PURE__ */ (0, import_jsx_runtime33.jsx)("div", { style: { padding: 12 }, children: /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(
                "button",
                {
                  onPointerDown: onToolbarButtonPointerDown,
                  onClick: () => {
                    if (!image.src) return;
                    setImageLightbox({ src: image.src, alt: image.alt });
                  },
                  style: {
                    width: "100%",
                    borderRadius: 12,
                    border: "1px solid var(--km-border)",
                    background: "rgba(148,163,184,0.08)",
                    padding: 0,
                    cursor: image.src ? "pointer" : "not-allowed",
                    overflow: "hidden"
                  },
                  tabIndex: -1,
                  type: "button",
                  children: /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(
                    "img",
                    {
                      alt: image.alt,
                      src: image.src ?? TRANSPARENT_PIXEL_DATA_URL2,
                      style: {
                        width: "100%",
                        height: 168,
                        display: "block",
                        objectFit: image.fit,
                        background: image.placeholder ? "rgba(226,232,240,0.55)" : "transparent"
                      }
                    }
                  )
                }
              ) }),
              renderSeparator(),
              /* @__PURE__ */ (0, import_jsx_runtime33.jsxs)("div", { style: { padding: 12, display: "flex", flexWrap: "wrap", gap: 8 }, children: [
                /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(
                  "button",
                  {
                    disabled: !props.isCommandEnabled("node.image.add", { nodeId: props.nodeId }),
                    onPointerDown: onToolbarButtonPointerDown,
                    onClick: () => void props.dispatchCommand("node.image.add", { nodeId: props.nodeId }),
                    style: props.isCommandEnabled("node.image.add", { nodeId: props.nodeId }) ? buttonStyle2 : disabledButtonStyle,
                    tabIndex: -1,
                    type: "button",
                    children: t("editor.image.action.replace")
                  }
                ),
                /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(
                  "button",
                  {
                    onPointerDown: onToolbarButtonPointerDown,
                    onClick: () => void props.dispatchCommand("node.image.remove", { nodeId: props.nodeId, blockId: image.block.id }),
                    style: buttonStyle2,
                    tabIndex: -1,
                    type: "button",
                    children: t("editor.image.action.delete")
                  }
                ),
                /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(
                  "button",
                  {
                    onPointerDown: onToolbarButtonPointerDown,
                    onClick: () => {
                      void props.dispatchCommand("node.image.setSize", {
                        nodeId: props.nodeId,
                        blockId: image.block.id,
                        width: 240,
                        height: 160
                      });
                      void props.dispatchCommand("node.image.setFit", { nodeId: props.nodeId, blockId: image.block.id, fit: "contain" });
                    },
                    style: buttonStyle2,
                    tabIndex: -1,
                    type: "button",
                    children: t("editor.image.action.reset")
                  }
                ),
                /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(
                  "button",
                  {
                    disabled: !image.src,
                    onPointerDown: onToolbarButtonPointerDown,
                    onClick: () => {
                      if (!image.src) return;
                      setImageLightbox({ src: image.src, alt: image.alt });
                    },
                    style: image.src ? buttonStyle2 : disabledButtonStyle,
                    tabIndex: -1,
                    type: "button",
                    children: t("editor.image.action.preview")
                  }
                )
              ] }),
              renderSeparator(),
              renderSection({
                title: t("editor.image.section.position"),
                children: /* @__PURE__ */ (0, import_jsx_runtime33.jsxs)(import_jsx_runtime33.Fragment, { children: [
                  renderChipButton({
                    title: t("editor.image.position.top"),
                    active: image.block.region === "top" || image.block.region === "main",
                    onClick: () => void props.dispatchCommand("node.image.setRegion", { nodeId: props.nodeId, blockId: image.block.id, region: "top" })
                  }),
                  renderChipButton({
                    title: t("editor.image.position.bottom"),
                    active: image.block.region === "bottom",
                    onClick: () => void props.dispatchCommand("node.image.setRegion", { nodeId: props.nodeId, blockId: image.block.id, region: "bottom" })
                  }),
                  renderChipButton({
                    title: t("editor.image.position.left"),
                    active: image.block.region === "left",
                    onClick: () => void props.dispatchCommand("node.image.setRegion", { nodeId: props.nodeId, blockId: image.block.id, region: "left" })
                  }),
                  renderChipButton({
                    title: t("editor.image.position.right"),
                    active: image.block.region === "right",
                    onClick: () => void props.dispatchCommand("node.image.setRegion", { nodeId: props.nodeId, blockId: image.block.id, region: "right" })
                  })
                ] })
              }),
              renderSeparator(),
              renderSection({
                title: t("editor.image.section.fit"),
                children: /* @__PURE__ */ (0, import_jsx_runtime33.jsxs)(import_jsx_runtime33.Fragment, { children: [
                  renderChipButton({
                    title: t("editor.image.fit.contain"),
                    active: image.fit === "contain",
                    onClick: () => void props.dispatchCommand("node.image.setFit", { nodeId: props.nodeId, blockId: image.block.id, fit: "contain" })
                  }),
                  renderChipButton({
                    title: t("editor.image.fit.cover"),
                    active: image.fit === "cover",
                    onClick: () => void props.dispatchCommand("node.image.setFit", { nodeId: props.nodeId, blockId: image.block.id, fit: "cover" })
                  })
                ] })
              }),
              renderSeparator(),
              /* @__PURE__ */ (0, import_jsx_runtime33.jsxs)("div", { style: { padding: 12 }, children: [
                /* @__PURE__ */ (0, import_jsx_runtime33.jsxs)("div", { style: { display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 10 }, children: [
                  /* @__PURE__ */ (0, import_jsx_runtime33.jsx)("div", { style: { fontSize: 11, fontWeight: 700, color: "var(--km-muted)", letterSpacing: "0.04em", textTransform: "uppercase" }, children: t("editor.image.section.size") }),
                  /* @__PURE__ */ (0, import_jsx_runtime33.jsxs)("div", { style: { fontSize: 12, color: "var(--km-text)" }, children: [
                    image.width,
                    "\xD7",
                    image.height
                  ] })
                ] }),
                /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(
                  "input",
                  {
                    max: 920,
                    min: 80,
                    onChange: (event) => {
                      setLockedPosition((prev) => prev ?? { left, top });
                      const raw = Number(event.currentTarget.value);
                      const aspect = image.height > 0 ? image.width / image.height : 1.5;
                      const clampedWidth = Math.max(80, Math.min(920, Math.round(raw)));
                      const nextHeight = Math.max(20, Math.round(clampedWidth / (Number.isFinite(aspect) && aspect > 0 ? aspect : 1.5)));
                      scheduleSetImageSize({ blockId: image.block.id, width: clampedWidth, height: nextHeight });
                    },
                    onPointerDown: (event) => {
                      event.stopPropagation();
                      setLockedPosition((prev) => prev ?? { left, top });
                    },
                    onPointerUp: () => setLockedPosition(null),
                    onMouseDown: (event) => {
                      event.stopPropagation();
                      setLockedPosition((prev) => prev ?? { left, top });
                    },
                    onMouseUp: () => setLockedPosition(null),
                    onTouchStart: (event) => {
                      event.stopPropagation();
                      setLockedPosition((prev) => prev ?? { left, top });
                    },
                    onTouchEnd: () => setLockedPosition(null),
                    step: 10,
                    style: { width: "100%" },
                    type: "range",
                    value: Math.max(80, Math.min(920, image.width))
                  }
                ),
                /* @__PURE__ */ (0, import_jsx_runtime33.jsx)("div", { style: { marginTop: 8, fontSize: 11, color: "var(--km-muted)" }, children: t("editor.image.hint.dragResize") })
              ] })
            ] })
          ] })
        }) : null,
        openId === "builtin.icons" ? renderPopoverPanel({
          anchorId: "builtin.icons",
          width: 420,
          maxHeight: 560,
          children: /* @__PURE__ */ (0, import_jsx_runtime33.jsxs)(import_jsx_runtime33.Fragment, { children: [
            /* @__PURE__ */ (0, import_jsx_runtime33.jsx)("div", { style: { padding: 12, fontSize: 12, fontWeight: 650, color: "var(--km-text)", ...popoverStickyTitleStyle }, children: t("editor.icons.title") }),
            /* @__PURE__ */ (0, import_jsx_runtime33.jsxs)("div", { style: { padding: 12 }, children: [
              !canEditIcons ? /* @__PURE__ */ (0, import_jsx_runtime33.jsx)("div", { style: { fontSize: 12, color: "var(--km-muted)", marginBottom: 10 }, children: t("editor.icons.lockedReadonly") }) : null,
              /* @__PURE__ */ (0, import_jsx_runtime33.jsx)("div", { style: { display: "flex", flexDirection: "column", gap: 10 }, children: [0, 1, 2].map((slotIndex) => {
                const value = iconSlots[slotIndex];
                const filled = Boolean(value);
                const canMoveUp = Boolean(canEditIcons && filled && slotIndex > 0 && slotIndex < iconValues.length);
                const canMoveDown = Boolean(canEditIcons && filled && slotIndex >= 0 && slotIndex < iconValues.length - 1);
                const label = value ? value.replace("kmind-icon://builtin/", "") : "";
                return /* @__PURE__ */ (0, import_jsx_runtime33.jsxs)("div", { style: { display: "flex", alignItems: "center", gap: 8 }, children: [
                  /* @__PURE__ */ (0, import_jsx_runtime33.jsx)("div", { style: { width: 56, fontSize: 11, color: "var(--km-muted)" }, children: t("editor.icons.slot", { index: slotIndex + 1 }) }),
                  /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(
                    "button",
                    {
                      disabled: !canEditIcons,
                      onPointerDown: onToolbarButtonPointerDown,
                      onClick: () => setIconPickerSlot((prev) => prev === slotIndex ? null : slotIndex),
                      style: {
                        height: 34,
                        flex: 1,
                        minWidth: 0,
                        padding: "0 10px",
                        borderRadius: 10,
                        border: "1px solid var(--km-border)",
                        background: "var(--km-panel)",
                        color: "var(--km-text)",
                        fontSize: 12,
                        cursor: canEditIcons ? "pointer" : "not-allowed",
                        display: "inline-flex",
                        alignItems: "center",
                        gap: 8,
                        opacity: canEditIcons ? 1 : 0.55
                      },
                      tabIndex: -1,
                      type: "button",
                      children: value ? value.startsWith("kmind-icon://") ? /* @__PURE__ */ (0, import_jsx_runtime33.jsxs)(import_jsx_runtime33.Fragment, { children: [
                        /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(BuiltinIconPreview, { iconId: value, size: 18 }),
                        /* @__PURE__ */ (0, import_jsx_runtime33.jsx)("span", { style: { overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap", color: "var(--km-muted)" }, children: label })
                      ] }) : /* @__PURE__ */ (0, import_jsx_runtime33.jsx)("span", { style: { overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }, children: value }) : /* @__PURE__ */ (0, import_jsx_runtime33.jsx)("span", { style: { color: "var(--km-muted)" }, children: t("editor.icons.action.addPlaceholder") })
                    }
                  ),
                  /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(
                    "button",
                    {
                      disabled: !canEditIcons || !filled,
                      onPointerDown: onToolbarButtonPointerDown,
                      onClick: () => {
                        setIconPickerSlot(null);
                        setIconSlotValue(slotIndex, null);
                      },
                      style: {
                        width: 34,
                        height: 34,
                        borderRadius: 10,
                        border: "1px solid var(--km-border)",
                        background: "var(--km-panel)",
                        color: "var(--km-muted)",
                        cursor: canEditIcons && filled ? "pointer" : "not-allowed",
                        opacity: canEditIcons && filled ? 1 : 0.55
                      },
                      tabIndex: -1,
                      type: "button",
                      children: "\xD7"
                    }
                  ),
                  /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(
                    "button",
                    {
                      disabled: !canMoveUp,
                      onPointerDown: onToolbarButtonPointerDown,
                      onClick: () => {
                        setIconPickerSlot(null);
                        void props.dispatchCommand("node.icon.move", { nodeId: props.nodeId, index: slotIndex, direction: -1 });
                      },
                      style: {
                        width: 34,
                        height: 34,
                        borderRadius: 10,
                        border: "1px solid var(--km-border)",
                        background: "var(--km-panel)",
                        color: "var(--km-muted)",
                        cursor: canMoveUp ? "pointer" : "not-allowed",
                        opacity: canMoveUp ? 1 : 0.55
                      },
                      tabIndex: -1,
                      type: "button",
                      children: "\u2191"
                    }
                  ),
                  /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(
                    "button",
                    {
                      disabled: !canMoveDown,
                      onPointerDown: onToolbarButtonPointerDown,
                      onClick: () => {
                        setIconPickerSlot(null);
                        void props.dispatchCommand("node.icon.move", { nodeId: props.nodeId, index: slotIndex, direction: 1 });
                      },
                      style: {
                        width: 34,
                        height: 34,
                        borderRadius: 10,
                        border: "1px solid var(--km-border)",
                        background: "var(--km-panel)",
                        color: "var(--km-muted)",
                        cursor: canMoveDown ? "pointer" : "not-allowed",
                        opacity: canMoveDown ? 1 : 0.55
                      },
                      tabIndex: -1,
                      type: "button",
                      children: "\u2193"
                    }
                  )
                ] }, slotIndex);
              }) }),
              /* @__PURE__ */ (0, import_jsx_runtime33.jsxs)("div", { style: { display: "flex", alignItems: "center", justifyContent: "space-between", gap: 10, marginTop: 12 }, children: [
                /* @__PURE__ */ (0, import_jsx_runtime33.jsx)("div", { style: { fontSize: 11, color: "var(--km-muted)" }, children: t("editor.icons.hint.max3") }),
                /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(
                  "button",
                  {
                    disabled: !canEditIcons || iconValues.length === 0,
                    onPointerDown: onToolbarButtonPointerDown,
                    onClick: () => {
                      setIconPickerSlot(null);
                      commitIconSlots([null, null, null]);
                    },
                    style: !canEditIcons || iconValues.length === 0 ? disabledButtonStyle : buttonStyle2,
                    tabIndex: -1,
                    type: "button",
                    children: t("editor.icons.action.clearAll")
                  }
                )
              ] })
            ] }),
            iconPickerSlot !== null ? /* @__PURE__ */ (0, import_jsx_runtime33.jsxs)(import_jsx_runtime33.Fragment, { children: [
              renderSeparator(),
              /* @__PURE__ */ (0, import_jsx_runtime33.jsxs)("div", { style: { padding: 12 }, children: [
                /* @__PURE__ */ (0, import_jsx_runtime33.jsxs)("div", { style: { display: "flex", alignItems: "center", justifyContent: "space-between", gap: 8 }, children: [
                  /* @__PURE__ */ (0, import_jsx_runtime33.jsx)("div", { style: { fontSize: 12, fontWeight: 650, color: "var(--km-text)" }, children: t("editor.icons.picker.title", { index: iconPickerSlot + 1 }) }),
                  /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(
                    "button",
                    {
                      onPointerDown: onToolbarButtonPointerDown,
                      onClick: () => setIconPickerSlot(null),
                      style: { ...buttonStyle2, padding: "0 10px", height: 30 },
                      tabIndex: -1,
                      type: "button",
                      children: t("editor.icons.picker.close")
                    }
                  )
                ] }),
                /* @__PURE__ */ (0, import_jsx_runtime33.jsx)("div", { style: { display: "flex", flexWrap: "wrap", gap: 8, marginTop: 10 }, children: /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(
                  "button",
                  {
                    disabled: !canEditIcons,
                    onPointerDown: onToolbarButtonPointerDown,
                    onClick: () => {
                      setIconPickerSlot(null);
                      setIconSlotValue(iconPickerSlot, null);
                    },
                    style: !canEditIcons ? disabledButtonStyle : buttonStyle2,
                    tabIndex: -1,
                    type: "button",
                    children: t("editor.icons.action.clearSlot")
                  }
                ) }),
                /* @__PURE__ */ (0, import_jsx_runtime33.jsx)("div", { className: "km-popover-scroll", style: { marginTop: 10, maxHeight: 260, overflow: "auto", paddingRight: 4 }, children: iconGroups.map((group) => {
                  return /* @__PURE__ */ (0, import_jsx_runtime33.jsxs)("div", { style: { marginBottom: 10 }, children: [
                    /* @__PURE__ */ (0, import_jsx_runtime33.jsx)("div", { style: { fontSize: 11, fontWeight: 700, color: "var(--km-muted)", marginBottom: 6 }, children: group.label }),
                    /* @__PURE__ */ (0, import_jsx_runtime33.jsx)("div", { style: { display: "grid", gridTemplateColumns: "repeat(6, 1fr)", gap: 6 }, children: group.icons.map((icon) => {
                      const selected = iconSlots[iconPickerSlot] === icon.id;
                      return /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(
                        "button",
                        {
                          disabled: !canEditIcons,
                          onPointerDown: onToolbarButtonPointerDown,
                          onClick: () => {
                            setIconPickerSlot(null);
                            setIconSlotValue(iconPickerSlot, icon.id);
                          },
                          style: {
                            border: "1px solid var(--km-border)",
                            background: selected ? "rgba(59, 130, 246, 0.12)" : "transparent",
                            borderRadius: 10,
                            height: 36,
                            width: 36,
                            display: "flex",
                            alignItems: "center",
                            justifyContent: "center",
                            cursor: canEditIcons ? "pointer" : "not-allowed",
                            color: "var(--km-text)",
                            opacity: canEditIcons ? 1 : 0.55
                          },
                          title: icon.label,
                          tabIndex: -1,
                          type: "button",
                          children: /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(BuiltinIconPreview, { iconId: icon.id })
                        },
                        icon.id
                      );
                    }) })
                  ] }, group.id);
                }) })
              ] })
            ] }) : null
          ] })
        }) : null,
        openId === "builtin.tags" ? renderPopoverPanel({
          anchorId: "builtin.tags",
          children: /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(
            TagsPanel,
            {
              variant: "embedded",
              dispatchCommand: props.dispatchCommand,
              doc: doc3,
              isCommandEnabled: props.isCommandEnabled,
              maxHeight: 0,
              nodeId: props.nodeId,
              onClose: () => {
                setOpenId(null);
                setOpenAnchor(null);
              },
              onHoverChange: () => {
              },
              readOnly,
              showCloseButton: false,
              width: 0,
              x: 0,
              y: 0
            }
          )
        }) : null,
        props.pendingRelationFromId && relationPickerCursor ? renderCursorIconBadge({
          cursor: relationPickerCursor,
          iconId: "kmind-icon://builtin/ui/relation",
          label: t("editor.selectionToolbar.cursor.relation")
        }) : null,
        linkPickerCursor ? renderCursorIconBadge({
          cursor: linkPickerCursor,
          iconId: "kmind-icon://builtin/ui/backlinks",
          label: t("editor.selectionToolbar.cursor.backlinkPick")
        }) : null,
        formatPainter && formatPainterCursor ? (() => {
          const portalPosition = toOverlayPortalPoint(overlayPortalContainer, {
            x: formatPainterCursor.x + 10,
            y: formatPainterCursor.y + 10
          });
          const node = /* @__PURE__ */ (0, import_jsx_runtime33.jsxs)(
            "div",
            {
              style: {
                position: scopedOverlayPortal ? "absolute" : "fixed",
                left: portalPosition.x,
                top: portalPosition.y,
                width: 140,
                padding: 10,
                borderRadius: 14,
                border: "1px solid rgba(148, 163, 184, 0.45)",
                background: "rgba(255,255,255,0.92)",
                boxShadow: "0 18px 36px rgba(15, 23, 42, 0.18)",
                pointerEvents: "none",
                zIndex: 120
              },
              children: [
                /* @__PURE__ */ (0, import_jsx_runtime33.jsx)("div", { style: { fontSize: 11, color: "rgba(100,116,139,0.92)", marginBottom: 8 }, children: t("editor.selectionToolbar.formatPainter.hint") }),
                /* @__PURE__ */ (0, import_jsx_runtime33.jsxs)("svg", { height: 56, style: { display: "block" }, viewBox: "0 0 120 56", width: 120, children: [
                  renderNodeShape({
                    x: 0,
                    y: 4,
                    width: 120,
                    height: 48,
                    shape: formatPainter.preview.shape,
                    fill: formatPainter.preview.fill,
                    stroke: formatPainter.preview.stroke,
                    strokeWidth: formatPainter.preview.strokeWidth
                  }),
                  /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(
                    "text",
                    {
                      dominantBaseline: "middle",
                      fill: formatPainter.preview.textColor,
                      fontFamily: "ui-sans-serif, system-ui, sans-serif",
                      fontSize: 12,
                      textAnchor: "middle",
                      x: 60,
                      y: 28,
                      children: t("editor.nodeStyle.preview.nodeLabel")
                    }
                  )
                ] })
              ]
            }
          );
          return overlayPortalTarget ? (0, import_react_dom6.createPortal)(node, overlayPortalTarget) : node;
        })() : null,
        imageLightbox ? (() => {
          const node = /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(
            "div",
            {
              onPointerDown: () => setImageLightbox(null),
              style: {
                position: scopedOverlayPortal ? "absolute" : "fixed",
                inset: 0,
                background: "rgba(15, 23, 42, 0.58)",
                display: "flex",
                alignItems: "center",
                justifyContent: "center",
                padding: 24,
                pointerEvents: "auto",
                zIndex: 160
              },
              children: /* @__PURE__ */ (0, import_jsx_runtime33.jsxs)(
                "div",
                {
                  onPointerDown: (event) => {
                    event.stopPropagation();
                  },
                  style: {
                    width: "min(1100px, 94vw)",
                    maxHeight: "min(820px, 90vh)",
                    borderRadius: 16,
                    border: "1px solid rgba(148, 163, 184, 0.35)",
                    background: "rgba(255,255,255,0.92)",
                    boxShadow: "0 24px 64px rgba(15, 23, 42, 0.35)",
                    overflow: "hidden",
                    display: "flex",
                    flexDirection: "column"
                  },
                  children: [
                    /* @__PURE__ */ (0, import_jsx_runtime33.jsxs)("div", { style: { display: "flex", alignItems: "center", justifyContent: "space-between", padding: 10, gap: 10 }, children: [
                      /* @__PURE__ */ (0, import_jsx_runtime33.jsx)("div", { style: { minWidth: 0, fontSize: 12, fontWeight: 650, color: "var(--km-text)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }, children: imageLightbox.alt || t("editor.image.lightbox.fallbackTitle") }),
                      /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(
                        "button",
                        {
                          onPointerDown: (event) => {
                            event.preventDefault();
                            event.stopPropagation();
                          },
                          onClick: () => setImageLightbox(null),
                          style: {
                            height: 32,
                            padding: "0 10px",
                            borderRadius: 10,
                            border: "1px solid var(--km-border)",
                            background: "transparent",
                            color: "var(--km-text)",
                            fontSize: 12,
                            cursor: "pointer"
                          },
                          tabIndex: -1,
                          type: "button",
                          children: t("editor.image.lightbox.close")
                        }
                      )
                    ] }),
                    /* @__PURE__ */ (0, import_jsx_runtime33.jsx)("div", { style: { padding: 10, background: "rgba(148,163,184,0.06)" }, children: /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(
                      "img",
                      {
                        alt: imageLightbox.alt,
                        src: imageLightbox.src,
                        style: {
                          width: "100%",
                          maxHeight: "calc(min(820px, 90vh) - 64px)",
                          objectFit: "contain",
                          display: "block"
                        }
                      }
                    ) })
                  ]
                }
              )
            }
          );
          return overlayPortalTarget ? (0, import_react_dom6.createPortal)(node, overlayPortalTarget) : node;
        })() : null
      ]
    }
  );
}

// ../react/src/mindmap-editor/overlays/view-mode-hint-overlay.tsx
var import_react29 = __toESM(require_react(), 1);

// ../react/src/mindmap-editor/utils/view-mode-save-indicator.ts
function normalizeTimestamp(value) {
  return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : null;
}
function shouldTriggerRecentSavedIndicator(args) {
  if (!args.zenActive) return false;
  const prev = normalizeTimestamp(args.previousLastSavedAt);
  const next = normalizeTimestamp(args.nextLastSavedAt);
  return next !== null && next !== prev;
}
function resolveViewModeSaveIndicatorKind(args) {
  if (!args.zenActive) return "hidden";
  const status = args.status;
  if (!status) return "hidden";
  if (typeof status.lastSaveError === "string" && status.lastSaveError.trim().length > 0) return "error";
  if (status.saving) return "saving";
  if (status.dirty) return "hidden";
  if (!args.recentSavedVisible) return "hidden";
  return normalizeTimestamp(status.lastSavedAt) === null ? "hidden" : "saved";
}

// ../react/src/mindmap-editor/overlays/view-mode-hint-overlay.tsx
var import_jsx_runtime34 = __toESM(require_jsx_runtime(), 1);
var lastSignatureByProjectId = /* @__PURE__ */ new Map();
var viewModeExitOverlayCssText = `
  .km-viewmode-exit-root {
    position: absolute;
    top: 10px;
    right: 10px;
    left: 10px;
    z-index: 75;
    pointer-events: none;
  }

  .km-viewmode-exit-stack {
    pointer-events: auto;
    display: flex;
    align-items: center;
    justify-content: flex-end;
    gap: 8px;
  }

  .km-viewmode-exit-stack--panel {
    flex-direction: column;
    align-items: flex-end;
  }

  .km-viewmode-exit-pill[data-save-kind="error"] {
    border-color: color-mix(in srgb, rgb(239, 68, 68) 34%, var(--km-border));
    background: color-mix(in srgb, rgb(239, 68, 68) 6%, var(--km-panel) 72%);
  }

  .km-viewmode-exit-status {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    gap: 0;
    flex: 0 0 auto;
    min-width: 18px;
    margin-left: 6px;
  }

  .km-viewmode-exit-status-divider {
    width: 1px;
    height: 14px;
    margin-right: 6px;
    background: color-mix(in srgb, var(--km-border) 70%, transparent);
    opacity: 0.2;
    transition: opacity 160ms ease;
    flex: 0 0 auto;
  }

  .km-viewmode-exit-status-dot {
    width: 8px;
    height: 8px;
    border-radius: 999px;
    flex: 0 0 auto;
    background: color-mix(in srgb, var(--km-text) 26%, transparent);
    box-shadow: none;
    transition: background 180ms ease, box-shadow 180ms ease, transform 180ms ease, opacity 180ms ease;
  }

  .km-viewmode-exit-status[data-kind="hidden"] .km-viewmode-exit-status-divider {
    opacity: 0.12;
  }

  .km-viewmode-exit-status[data-kind="saving"] .km-viewmode-exit-status-dot,
  .km-viewmode-exit-panel-status[data-kind="saving"] .km-viewmode-exit-status-dot {
    width: 10px;
    height: 10px;
    border: 2px solid color-mix(in srgb, var(--km-border) 88%, transparent);
    border-top-color: rgb(59, 130, 246);
    border-right-color: rgb(59, 130, 246);
    background: transparent;
    animation: km-viewmode-save-spin 0.82s linear infinite;
  }

  .km-viewmode-exit-status[data-kind="saved"] .km-viewmode-exit-status-dot,
  .km-viewmode-exit-panel-status[data-kind="saved"] .km-viewmode-exit-status-dot {
    background: rgb(34, 197, 94);
    box-shadow: 0 0 0 4px rgba(34, 197, 94, 0.14);
    animation: km-viewmode-save-pulse 0.82s ease-out 1;
  }

  .km-viewmode-exit-status[data-kind="error"] .km-viewmode-exit-status-dot,
  .km-viewmode-exit-panel-status[data-kind="error"] .km-viewmode-exit-status-dot {
    background: rgb(239, 68, 68);
    box-shadow: 0 0 0 4px rgba(239, 68, 68, 0.12);
  }

  .km-viewmode-exit-status-text {
    min-width: 0;
    font-size: 12px;
    line-height: 1;
    color: var(--km-muted);
    white-space: nowrap;
  }

  .km-viewmode-exit-status-text[data-kind="saved"] {
    color: color-mix(in srgb, rgb(34, 197, 94) 76%, var(--km-text));
  }

  .km-viewmode-exit-status-text[data-kind="error"] {
    color: color-mix(in srgb, rgb(239, 68, 68) 76%, var(--km-text));
  }

  .km-viewmode-exit-status-text[data-kind="saving"] {
    color: color-mix(in srgb, rgb(59, 130, 246) 72%, var(--km-text));
  }

  .km-viewmode-exit-panel-status {
    display: inline-flex;
    align-items: center;
    gap: 8px;
    align-self: flex-end;
    min-height: 30px;
    max-width: min(220px, 100%);
    padding: 6px 10px;
    border-radius: 999px;
    border: 1px solid color-mix(in srgb, var(--km-border) 72%, transparent);
    background: color-mix(in srgb, var(--km-panel) 68%, transparent);
    color: var(--km-text);
  }

  .km-viewmode-exit-panel-status[data-kind="saved"] {
    border-color: color-mix(in srgb, rgb(34, 197, 94) 28%, var(--km-border));
    background: color-mix(in srgb, rgb(34, 197, 94) 8%, var(--km-panel) 72%);
  }

  .km-viewmode-exit-panel-status[data-kind="error"] {
    border-color: color-mix(in srgb, rgb(239, 68, 68) 30%, var(--km-border));
    background: color-mix(in srgb, rgb(239, 68, 68) 8%, var(--km-panel) 72%);
  }

  .km-viewmode-exit-pill {
    pointer-events: auto;
    user-select: none;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    border-radius: 999px;
    border: 1px solid color-mix(in srgb, var(--km-border) 70%, transparent);
    background: color-mix(in srgb, var(--km-panel) 65%, transparent);
    color: var(--km-muted);
    padding: 6px 8px;
    line-height: 1;
    backdrop-filter: blur(10px);
    -webkit-backdrop-filter: blur(10px);
    cursor: pointer;
    transition: background 160ms ease, border-color 160ms ease, color 160ms ease;
  }

  .km-viewmode-exit-pill:hover {
    border-color: color-mix(in srgb, var(--km-border) 90%, transparent);
    background: color-mix(in srgb, var(--km-panel) 78%, transparent);
    color: var(--km-text);
  }

  .km-viewmode-exit-pill:active {
    background: color-mix(in srgb, var(--km-panel) 84%, transparent);
  }

  .km-viewmode-exit-root[data-expanded="true"] .km-viewmode-exit-pill {
    color: var(--km-text);
  }

  .km-viewmode-exit-icon {
    width: 16px;
    height: 16px;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    flex: 0 0 auto;
  }

  .km-viewmode-exit-icons {
    display: inline-flex;
    align-items: center;
    gap: 0;
    flex: 0 0 auto;
  }

  .km-viewmode-exit-pill-content {
    display: inline-flex;
    align-items: center;
    gap: 8px;
    overflow: hidden;
    max-width: 0;
    opacity: 0;
    margin-left: 0;
    transition: max-width 180ms ease, opacity 120ms ease, margin-left 180ms ease;
    pointer-events: none;
  }

  .km-viewmode-exit-root[data-expanded="true"] .km-viewmode-exit-pill-content {
    max-width: 260px;
    opacity: 1;
    margin-left: 8px;
    pointer-events: auto;
  }

  .km-viewmode-exit-action {
    border: 1px solid color-mix(in srgb, var(--km-border) 70%, transparent);
    background: transparent;
    color: var(--km-text);
    border-radius: 10px;
    padding: 4px 8px;
    font-size: 12px;
    cursor: pointer;
    white-space: nowrap;
  }

  .km-viewmode-exit-divider {
    width: 1px;
    height: 14px;
    margin: 0 6px;
    background: color-mix(in srgb, var(--km-border) 70%, transparent);
    opacity: 0.85;
    flex: 0 0 auto;
  }

  .km-viewmode-exit-action:hover {
    background: color-mix(in srgb, var(--km-panel) 75%, transparent);
  }

  .km-viewmode-exit-action:active {
    background: color-mix(in srgb, var(--km-panel) 82%, transparent);
  }

  .km-viewmode-exit-panel {
    pointer-events: auto;
    display: flex;
    flex-direction: column;
    gap: 6px;
    padding: 8px;
    border-radius: 14px;
    border: 1px solid color-mix(in srgb, var(--km-border) 70%, transparent);
    background: color-mix(in srgb, var(--km-panel) 72%, transparent);
    color: var(--km-text);
    box-shadow: 0 10px 30px rgba(15, 23, 42, 0.10);
    backdrop-filter: blur(12px);
    -webkit-backdrop-filter: blur(12px);
    max-width: min(320px, calc(100% - 0px));
  }

  .km-viewmode-exit-panel-row {
    display: flex;
    align-items: center;
    gap: 10px;
    border-radius: 12px;
    border: 1px solid color-mix(in srgb, var(--km-border) 70%, transparent);
    background: transparent;
    color: var(--km-text);
    padding: 8px 10px;
    cursor: pointer;
  }

  .km-viewmode-exit-panel-row:hover {
    background: color-mix(in srgb, var(--km-panel) 78%, transparent);
  }

  .km-viewmode-exit-panel-row:active {
    background: color-mix(in srgb, var(--km-panel) 84%, transparent);
  }

  .km-viewmode-exit-panel-label {
    min-width: 0;
    flex: 1 1 auto;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    font-size: 12px;
  }

  @keyframes km-viewmode-save-spin {
    to {
      transform: rotate(360deg);
    }
  }

  @keyframes km-viewmode-save-pulse {
    0% {
      transform: scale(0.84);
      box-shadow: 0 0 0 0 rgba(34, 197, 94, 0.18);
    }
    55% {
      transform: scale(1);
      box-shadow: 0 0 0 5px rgba(34, 197, 94, 0.14);
    }
    100% {
      transform: scale(1);
      box-shadow: 0 0 0 3px rgba(34, 197, 94, 0.10);
    }
  }

  @media (prefers-reduced-motion: reduce) {
    .km-viewmode-exit-pill,
    .km-viewmode-exit-pill-content {
      transition-duration: 120ms;
    }

    .km-viewmode-exit-status[data-kind="saving"] .km-viewmode-exit-status-dot,
    .km-viewmode-exit-status[data-kind="saved"] .km-viewmode-exit-status-dot,
    .km-viewmode-exit-panel-status[data-kind="saving"] .km-viewmode-exit-status-dot,
    .km-viewmode-exit-panel-status[data-kind="saved"] .km-viewmode-exit-status-dot {
      animation: none;
    }
  }
`;
function extractSvgInnerContent2(svg) {
  const start = svg.indexOf(">");
  const end = svg.lastIndexOf("</svg>");
  if (start < 0 || end < 0 || end <= start) return svg;
  return svg.slice(start + 1, end);
}
function BuiltinIcon(props) {
  const svg = getBuiltinIconSvg(props.iconId);
  if (!svg) return null;
  const inner2 = extractSvgInnerContent2(svg).trim();
  return /* @__PURE__ */ (0, import_jsx_runtime34.jsx)(
    "span",
    {
      "aria-hidden": "true",
      style: { width: 16, height: 16, display: "inline-flex", alignItems: "center", justifyContent: "center" },
      children: /* @__PURE__ */ (0, import_jsx_runtime34.jsx)(
        "svg",
        {
          viewBox: "0 0 24 24",
          width: "100%",
          height: "100%",
          dangerouslySetInnerHTML: { __html: inner2 }
        }
      )
    }
  );
}
function ViewModeHintOverlay(props) {
  const t = useT();
  const zenActive = props.viewModes.zenMode.value;
  const readOnlyActive = props.viewModes.readOnly.value;
  const anyActive = zenActive || readOnlyActive;
  const documentStatus = props.documentStatus ?? null;
  const rootRef = (0, import_react29.useRef)(null);
  const [expanded, setExpanded] = (0, import_react29.useState)(false);
  const autoCollapseTimerRef = (0, import_react29.useRef)(null);
  const didManualExpandRef = (0, import_react29.useRef)(false);
  const [containerWidth, setContainerWidth] = (0, import_react29.useState)(0);
  const didInitRef = (0, import_react29.useRef)(false);
  const lastSignatureRef = (0, import_react29.useRef)("");
  const savedChipTimerRef = (0, import_react29.useRef)(null);
  const lastSeenSavedAtRef = (0, import_react29.useRef)(documentStatus?.lastSavedAt ?? null);
  const [recentSavedVisible, setRecentSavedVisible] = (0, import_react29.useState)(false);
  const clearTimer = () => {
    if (autoCollapseTimerRef.current === null) return;
    window.clearTimeout(autoCollapseTimerRef.current);
    autoCollapseTimerRef.current = null;
  };
  const clearSavedChipTimer = () => {
    if (savedChipTimerRef.current === null) return;
    window.clearTimeout(savedChipTimerRef.current);
    savedChipTimerRef.current = null;
  };
  const openExpanded = (0, import_react29.useCallback)((kind) => {
    if (!anyActive) return;
    setExpanded(true);
    clearTimer();
    if (kind === "manual") {
      didManualExpandRef.current = true;
      return;
    }
    didManualExpandRef.current = false;
    autoCollapseTimerRef.current = window.setTimeout(() => {
      autoCollapseTimerRef.current = null;
      if (didManualExpandRef.current) return;
      setExpanded(false);
    }, 3e3);
  }, [anyActive]);
  (0, import_react29.useEffect)(() => {
    return () => {
      clearTimer();
      clearSavedChipTimer();
    };
  }, []);
  (0, import_react29.useLayoutEffect)(() => {
    if (!anyActive) return;
    const root = rootRef.current;
    if (!root) return;
    const container = root.offsetParent ?? root.parentElement;
    if (!container) return;
    const update = () => {
      setContainerWidth(container.clientWidth);
    };
    update();
    if (typeof ResizeObserver === "undefined") {
      const win = resolveOwnerWindow(root) ?? (typeof window !== "undefined" ? window : null);
      if (!win) return;
      win.addEventListener("resize", update);
      return () => win.removeEventListener("resize", update);
    }
    const ro = new ResizeObserver(update);
    ro.observe(container);
    return () => ro.disconnect();
  }, [anyActive]);
  (0, import_react29.useEffect)(() => {
    if (!expanded) return;
    const win = resolveOwnerWindow(rootRef.current) ?? (typeof window !== "undefined" ? window : null);
    if (!win) return;
    const onPointerDown = (event) => {
      const target2 = event.target;
      if (!isNodeLike(target2)) return;
      const root = rootRef.current;
      if (root && root.contains(target2)) return;
      setExpanded(false);
    };
    const onKeyDown = (event) => {
      if (event.key !== "Escape") return;
      setExpanded(false);
    };
    win.addEventListener("pointerdown", onPointerDown, true);
    win.addEventListener("keydown", onKeyDown, true);
    return () => {
      win.removeEventListener("pointerdown", onPointerDown, true);
      win.removeEventListener("keydown", onKeyDown, true);
    };
  }, [expanded]);
  (0, import_react29.useEffect)(() => {
    if (!anyActive) {
      setExpanded(false);
      didManualExpandRef.current = false;
      return;
    }
  }, [anyActive]);
  (0, import_react29.useEffect)(() => {
    clearSavedChipTimer();
    setRecentSavedVisible(false);
    lastSeenSavedAtRef.current = documentStatus?.lastSavedAt ?? null;
  }, [props.projectId]);
  (0, import_react29.useEffect)(() => {
    if (!zenActive) {
      clearSavedChipTimer();
      setRecentSavedVisible(false);
      return;
    }
    if (!documentStatus) {
      clearSavedChipTimer();
      setRecentSavedVisible(false);
      return;
    }
    if (documentStatus.saving || documentStatus.dirty || documentStatus.lastSaveError) {
      clearSavedChipTimer();
      setRecentSavedVisible(false);
    }
  }, [documentStatus?.dirty, documentStatus?.lastSaveError, documentStatus?.saving, zenActive]);
  (0, import_react29.useEffect)(() => {
    const nextLastSavedAt = documentStatus?.lastSavedAt ?? null;
    const prevLastSavedAt = lastSeenSavedAtRef.current;
    const shouldOpen = shouldTriggerRecentSavedIndicator({
      zenActive,
      previousLastSavedAt: prevLastSavedAt,
      nextLastSavedAt
    });
    lastSeenSavedAtRef.current = nextLastSavedAt;
    if (!shouldOpen) return;
    clearSavedChipTimer();
    setRecentSavedVisible(true);
    savedChipTimerRef.current = window.setTimeout(() => {
      savedChipTimerRef.current = null;
      setRecentSavedVisible(false);
    }, 1600);
  }, [documentStatus?.lastSavedAt, zenActive]);
  (0, import_react29.useEffect)(() => {
    const signature = `${zenActive ? "1" : "0"}:${readOnlyActive ? "1" : "0"}`;
    const projectId = typeof props.projectId === "string" && props.projectId.trim().length > 0 ? props.projectId.trim() : null;
    if (projectId) {
      const last = lastSignatureByProjectId.get(projectId);
      lastSignatureByProjectId.set(projectId, signature);
      const changed2 = signature !== last;
      if (!anyActive) {
        didInitRef.current = true;
        setExpanded(false);
        return;
      }
      if (changed2) openExpanded("auto");
      didInitRef.current = true;
      return;
    }
    const changed = signature !== lastSignatureRef.current;
    lastSignatureRef.current = signature;
    if (!anyActive) {
      didInitRef.current = true;
      setExpanded(false);
      return;
    }
    if (!didInitRef.current || changed) {
      didInitRef.current = true;
      openExpanded("auto");
    }
  }, [anyActive, openExpanded, props.projectId, readOnlyActive, zenActive]);
  const saveIndicatorKind = resolveViewModeSaveIndicatorKind({
    zenActive,
    recentSavedVisible,
    status: documentStatus
  });
  const saveIndicatorLabel = saveIndicatorKind === "saving" ? t("appPage.floatingToolbar.saveBadge.saving") : saveIndicatorKind === "error" ? t("appPage.floatingToolbar.saveBadge.saveFailed") : saveIndicatorKind === "saved" ? t("appPage.floatingToolbar.saveBadge.saved") : "";
  const saveIndicatorTitle = saveIndicatorKind === "error" && typeof documentStatus?.lastSaveError === "string" && documentStatus.lastSaveError.trim().length > 0 ? `${saveIndicatorLabel} \xB7 ${documentStatus.lastSaveError.trim()}` : saveIndicatorLabel;
  const hintLines = (0, import_react29.useMemo)(() => {
    const lines = [];
    if (zenActive) {
      lines.push({
        iconId: "kmind-icon://builtin/ui/zen",
        label: t("editor.viewModes.hint.zen"),
        exitLabel: t("app.contextMenu.canvas.zen.exit"),
        commandId: "view.zen.toggle"
      });
    }
    if (readOnlyActive) {
      lines.push({
        iconId: "kmind-icon://builtin/ui/read-only",
        label: t("editor.viewModes.hint.readOnly"),
        exitLabel: t("app.contextMenu.canvas.readOnly.exit"),
        commandId: "view.readOnly.toggle"
      });
    }
    return lines;
  }, [readOnlyActive, t, zenActive]);
  if (!anyActive) return null;
  const usePanel = expanded && containerWidth > 0 && containerWidth < 320;
  const statusTitle = saveIndicatorTitle || void 0;
  return /* @__PURE__ */ (0, import_jsx_runtime34.jsxs)(import_jsx_runtime34.Fragment, { children: [
    /* @__PURE__ */ (0, import_jsx_runtime34.jsx)("style", { children: viewModeExitOverlayCssText }),
    /* @__PURE__ */ (0, import_jsx_runtime34.jsx)(
      "div",
      {
        className: "km-viewmode-exit-root",
        "data-expanded": expanded ? "true" : "false",
        ref: rootRef,
        children: /* @__PURE__ */ (0, import_jsx_runtime34.jsx)(
          "div",
          {
            "aria-label": t("editor.viewModes.badge.title"),
            className: ["km-viewmode-exit-stack", usePanel ? "km-viewmode-exit-stack--panel" : ""].filter(Boolean).join(" "),
            children: usePanel ? /* @__PURE__ */ (0, import_jsx_runtime34.jsxs)(
              "div",
              {
                className: "km-viewmode-exit-panel",
                onPointerEnter: () => {
                  clearTimer();
                  didManualExpandRef.current = true;
                },
                role: "dialog",
                "aria-label": t("editor.viewModes.badge.title"),
                children: [
                  saveIndicatorKind !== "hidden" ? /* @__PURE__ */ (0, import_jsx_runtime34.jsxs)("div", { "aria-label": statusTitle, "aria-live": "polite", className: "km-viewmode-exit-panel-status", "data-kind": saveIndicatorKind, role: "status", title: statusTitle, children: [
                    /* @__PURE__ */ (0, import_jsx_runtime34.jsx)("span", { "aria-hidden": "true", className: "km-viewmode-exit-status-dot" }),
                    /* @__PURE__ */ (0, import_jsx_runtime34.jsx)("span", { className: "km-viewmode-exit-status-text", "data-kind": saveIndicatorKind, children: saveIndicatorLabel })
                  ] }) : null,
                  hintLines.map((line) => /* @__PURE__ */ (0, import_jsx_runtime34.jsxs)(
                    "button",
                    {
                      className: "km-viewmode-exit-panel-row",
                      onClick: () => void props.dispatchCommand(line.commandId),
                      type: "button",
                      children: [
                        /* @__PURE__ */ (0, import_jsx_runtime34.jsx)("span", { className: "km-viewmode-exit-icon", "aria-hidden": "true", children: /* @__PURE__ */ (0, import_jsx_runtime34.jsx)(BuiltinIcon, { iconId: line.iconId }) }),
                        /* @__PURE__ */ (0, import_jsx_runtime34.jsx)("span", { className: "km-viewmode-exit-panel-label", children: line.exitLabel })
                      ]
                    },
                    line.commandId
                  ))
                ]
              }
            ) : /* @__PURE__ */ (0, import_jsx_runtime34.jsxs)(
              "div",
              {
                className: "km-viewmode-exit-pill",
                "data-save-kind": saveIndicatorKind,
                onClick: () => openExpanded("manual"),
                onPointerEnter: () => {
                  clearTimer();
                  didManualExpandRef.current = true;
                },
                role: "button",
                tabIndex: -1,
                title: [hintLines.map((line) => line.label).join(" \xB7 "), saveIndicatorTitle].filter(Boolean).join(" \xB7 "),
                children: [
                  /* @__PURE__ */ (0, import_jsx_runtime34.jsx)("span", { className: "km-viewmode-exit-icons", "data-count": String(hintLines.length), "aria-hidden": "true", children: hintLines.map((line, index) => /* @__PURE__ */ (0, import_jsx_runtime34.jsxs)(import_react29.Fragment, { children: [
                    index > 0 ? /* @__PURE__ */ (0, import_jsx_runtime34.jsx)("span", { className: "km-viewmode-exit-divider" }) : null,
                    /* @__PURE__ */ (0, import_jsx_runtime34.jsx)("span", { className: "km-viewmode-exit-icon", children: /* @__PURE__ */ (0, import_jsx_runtime34.jsx)(BuiltinIcon, { iconId: line.iconId }) })
                  ] }, `icon:${line.commandId}`)) }),
                  /* @__PURE__ */ (0, import_jsx_runtime34.jsxs)("span", { "aria-label": saveIndicatorKind === "hidden" ? void 0 : statusTitle, "aria-live": saveIndicatorKind === "hidden" ? void 0 : "polite", className: "km-viewmode-exit-status", "data-kind": saveIndicatorKind, role: saveIndicatorKind === "hidden" ? void 0 : "status", title: statusTitle, children: [
                    /* @__PURE__ */ (0, import_jsx_runtime34.jsx)("span", { "aria-hidden": "true", className: "km-viewmode-exit-status-divider" }),
                    /* @__PURE__ */ (0, import_jsx_runtime34.jsx)("span", { "aria-hidden": "true", className: "km-viewmode-exit-status-dot" })
                  ] }),
                  /* @__PURE__ */ (0, import_jsx_runtime34.jsxs)("span", { className: "km-viewmode-exit-pill-content", children: [
                    saveIndicatorKind !== "hidden" ? /* @__PURE__ */ (0, import_jsx_runtime34.jsx)("span", { className: "km-viewmode-exit-status-text", "data-kind": saveIndicatorKind, children: saveIndicatorLabel }) : null,
                    hintLines.map((line) => /* @__PURE__ */ (0, import_jsx_runtime34.jsx)(
                      "button",
                      {
                        className: "km-viewmode-exit-action",
                        onClick: (event) => {
                          event.preventDefault();
                          event.stopPropagation();
                          void props.dispatchCommand(line.commandId);
                        },
                        tabIndex: -1,
                        type: "button",
                        children: line.exitLabel
                      },
                      `exit:${line.commandId}`
                    ))
                  ] })
                ]
              }
            )
          }
        )
      }
    )
  ] });
}

// ../react/src/mindmap-editor/subtree.ts
function collectSubtreeNodeIds2(doc3, nodeId) {
  const stack = [nodeId];
  const visited = /* @__PURE__ */ new Set();
  const result = [];
  while (stack.length > 0) {
    const current = stack.pop();
    if (!current) break;
    if (visited.has(current)) continue;
    visited.add(current);
    result.push(current);
    const node = doc3.nodes[current];
    if (!node) continue;
    for (const childId of node.children) {
      stack.push(childId);
    }
  }
  return result;
}
function collectSubtreeElements(doc3, nodeId) {
  const summariesByParent = /* @__PURE__ */ new Map();
  const summaryById = /* @__PURE__ */ new Map();
  for (const summary of doc3.summaries) {
    summaryById.set(summary.id, summary);
    const bucket = summariesByParent.get(summary.parentId);
    if (bucket) bucket.push(summary.id);
    else summariesByParent.set(summary.parentId, [summary.id]);
  }
  const stack = [nodeId];
  const visited = /* @__PURE__ */ new Set();
  const nodeIds = /* @__PURE__ */ new Set();
  const summaryIds = /* @__PURE__ */ new Set();
  while (stack.length > 0) {
    const current = stack.pop();
    if (!current) break;
    if (visited.has(current)) continue;
    visited.add(current);
    const node = doc3.nodes[current];
    if (node) {
      nodeIds.add(node.id);
      for (const childId of node.children) {
        if (doc3.nodes[childId]) stack.push(childId);
      }
    }
    const attachedSummaryIds = summariesByParent.get(current);
    if (attachedSummaryIds) {
      for (const summaryId of attachedSummaryIds) {
        summaryIds.add(summaryId);
        stack.push(summaryId);
        const summary2 = summaryById.get(summaryId);
        if (!summary2) continue;
        for (const childId of summary2.children) {
          if (doc3.nodes[childId]) stack.push(childId);
        }
      }
    }
    const summary = summaryById.get(current);
    if (summary) {
      summaryIds.add(summary.id);
      for (const childId of summary.children) {
        if (doc3.nodes[childId]) stack.push(childId);
      }
    }
  }
  return { nodeIds, summaryIds };
}

// ../react/src/mindmap-editor/editor-view.tsx
var import_jsx_runtime35 = __toESM(require_jsx_runtime(), 1);
var crossPaneDropTailSize = 80;
var crossPaneChildEnterPadding = 8;
var crossPaneChildLeavePadding = 22;
var crossPaneSiblingLanePadding = 44;
var crossPaneSiblingLanePaddingActive = 72;
var crossPaneSiblingEndPadding = 44;
var crossPaneSiblingEndPaddingActive = 72;
var crossPaneMapAutoPanEdgeSize = 64;
var crossPaneMapAutoPanMaxStep = 22;
function clientToWorldFromSvg(args) {
  const rect = args.svg.getBoundingClientRect();
  if (!rect.width || !rect.height) return null;
  if (args.clientX < rect.left || args.clientX > rect.right || args.clientY < rect.top || args.clientY > rect.bottom) return null;
  return {
    x: args.viewBox.x + (args.clientX - rect.left) / rect.width * args.viewBox.width,
    y: args.viewBox.y + (args.clientY - rect.top) / rect.height * args.viewBox.height
  };
}
function pointInsideLayoutItem(point, item) {
  if (!item) return false;
  return point.x >= item.x && point.x <= item.x + item.width && point.y >= item.y && point.y <= item.y + item.height;
}
function resolveCrossPaneMapAutoPanDelta(svg, clientX, clientY) {
  if (!svg) return null;
  const rect = svg.getBoundingClientRect();
  if (!rect.width || !rect.height) return null;
  if (clientX < rect.left || clientX > rect.right || clientY < rect.top || clientY > rect.bottom) return null;
  const edge = crossPaneMapAutoPanEdgeSize;
  const maxStep = crossPaneMapAutoPanMaxStep;
  let dx = 0;
  let dy = 0;
  const leftDistance = clientX - rect.left;
  const rightDistance = rect.right - clientX;
  const topDistance = clientY - rect.top;
  const bottomDistance = rect.bottom - clientY;
  if (leftDistance < edge) dx = -maxStep * (1 - Math.max(0, leftDistance) / edge);
  else if (rightDistance < edge) dx = maxStep * (1 - Math.max(0, rightDistance) / edge);
  if (topDistance < edge) dy = -maxStep * (1 - Math.max(0, topDistance) / edge);
  else if (bottomDistance < edge) dy = maxStep * (1 - Math.max(0, bottomDistance) / edge);
  if (Math.abs(dx) < 0.5 && Math.abs(dy) < 0.5) return null;
  return { dx, dy };
}
function extractSvgInnerContent3(svg) {
  const start = svg.indexOf(">");
  const end = svg.lastIndexOf("</svg>");
  if (start < 0 || end < 0 || end <= start) return svg;
  return svg.slice(start + 1, end);
}
function BuiltinIconSymbol(props) {
  const icon = resolveBuiltinIcon(props.iconId);
  if (!icon) return null;
  const inner2 = extractSvgInnerContent3(icon.svg).trim();
  return /* @__PURE__ */ (0, import_jsx_runtime35.jsx)("symbol", { dangerouslySetInnerHTML: { __html: inner2 }, id: props.id, viewBox: icon.viewBox });
}
function BuiltinUiIconSymbols(props) {
  return /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)(import_jsx_runtime35.Fragment, { children: [
    /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(BuiltinIconSymbol, { iconId: "kmind-icon://builtin/ui/back", id: `${props.prefix}-ui-back` }),
    /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(BuiltinIconSymbol, { iconId: "kmind-icon://builtin/ui/backlinks", id: `${props.prefix}-ui-backlinks` }),
    /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(BuiltinIconSymbol, { iconId: "kmind-icon://builtin/ui/enter-submap", id: `${props.prefix}-ui-enter-submap` }),
    /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(BuiltinIconSymbol, { iconId: "kmind-icon://builtin/ui/link", id: `${props.prefix}-ui-link` })
  ] });
}
var HEX_COLOR_RE = /^#[0-9a-fA-F]{6}$/;
var RELATION_INHERIT_OPTION = "__inherit";
function normalizeHexColor(value) {
  if (typeof value !== "string") return null;
  const trimmed = value.trim();
  return HEX_COLOR_RE.test(trimmed) ? trimmed.toLowerCase() : null;
}
function resolveRelationDashControlValue(value) {
  return typeof value === "string" && value.trim().length > 0 ? value.trim() : RELATION_INHERIT_OPTION;
}
function normalizeRelationDashControlValue(value) {
  if (value === RELATION_INHERIT_OPTION) return void 0;
  if (typeof value !== "string") return void 0;
  const trimmed = value.trim();
  return trimmed.length > 0 ? trimmed : void 0;
}
function RelationDirectionIcon(props) {
  const common = {
    fill: "none",
    stroke: "currentColor",
    strokeLinecap: "round",
    strokeLinejoin: "round",
    strokeWidth: 1.6
  };
  if (props.direction === RELATION_INHERIT_OPTION) {
    return /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)("svg", { "aria-hidden": "true", height: "18", viewBox: "0 0 18 18", width: "18", children: [
      /* @__PURE__ */ (0, import_jsx_runtime35.jsx)("path", { ...common, d: "M4 6.3h7.8", opacity: "0.62" }),
      /* @__PURE__ */ (0, import_jsx_runtime35.jsx)("path", { ...common, d: "M6.2 11.7H14" }),
      /* @__PURE__ */ (0, import_jsx_runtime35.jsx)("path", { ...common, d: "m10.2 4.6 2.4 1.7-2.4 1.7", opacity: "0.62" }),
      /* @__PURE__ */ (0, import_jsx_runtime35.jsx)("path", { ...common, d: "m11.6 9.9 2.4 1.8-2.4 1.7" })
    ] });
  }
  if (props.direction === "none") {
    return /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)("svg", { "aria-hidden": "true", height: "18", viewBox: "0 0 18 18", width: "18", children: [
      /* @__PURE__ */ (0, import_jsx_runtime35.jsx)("path", { ...common, d: "M4.5 9h9" }),
      /* @__PURE__ */ (0, import_jsx_runtime35.jsx)("circle", { cx: "4", cy: "9", fill: "currentColor", r: "1.2" }),
      /* @__PURE__ */ (0, import_jsx_runtime35.jsx)("circle", { cx: "14", cy: "9", fill: "currentColor", r: "1.2" })
    ] });
  }
  if (props.direction === "forward") {
    return /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)("svg", { "aria-hidden": "true", height: "18", viewBox: "0 0 18 18", width: "18", children: [
      /* @__PURE__ */ (0, import_jsx_runtime35.jsx)("path", { ...common, d: "M4 9h9.5" }),
      /* @__PURE__ */ (0, import_jsx_runtime35.jsx)("path", { ...common, d: "m10.5 5.8 3.7 3.2-3.7 3.2" }),
      /* @__PURE__ */ (0, import_jsx_runtime35.jsx)("circle", { cx: "4", cy: "9", fill: "currentColor", r: "1.2" })
    ] });
  }
  if (props.direction === "backward") {
    return /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)("svg", { "aria-hidden": "true", height: "18", viewBox: "0 0 18 18", width: "18", children: [
      /* @__PURE__ */ (0, import_jsx_runtime35.jsx)("path", { ...common, d: "M4.5 9H14" }),
      /* @__PURE__ */ (0, import_jsx_runtime35.jsx)("path", { ...common, d: "M7.5 5.8 3.8 9l3.7 3.2" }),
      /* @__PURE__ */ (0, import_jsx_runtime35.jsx)("circle", { cx: "14", cy: "9", fill: "currentColor", r: "1.2" })
    ] });
  }
  return /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)("svg", { "aria-hidden": "true", height: "18", viewBox: "0 0 18 18", width: "18", children: [
    /* @__PURE__ */ (0, import_jsx_runtime35.jsx)("path", { ...common, d: "M4.4 9h9.2" }),
    /* @__PURE__ */ (0, import_jsx_runtime35.jsx)("path", { ...common, d: "M7.4 5.8 3.8 9l3.6 3.2" }),
    /* @__PURE__ */ (0, import_jsx_runtime35.jsx)("path", { ...common, d: "m10.6 5.8 3.6 3.2-3.6 3.2" })
  ] });
}
function RelationWidthPreview(props) {
  return /* @__PURE__ */ (0, import_jsx_runtime35.jsx)("svg", { "aria-hidden": "true", height: "18", viewBox: "0 0 48 18", width: "48", children: /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(
    "path",
    {
      d: "M5 9 H43",
      fill: "none",
      opacity: props.muted ? 0.68 : 1,
      stroke: "currentColor",
      strokeLinecap: "round",
      strokeWidth: props.strokeWidth
    }
  ) });
}
function RelationBubbleDropdown(props) {
  const selected = props.options.find((option) => option.value === props.value) ?? props.options[0];
  return /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)("div", { style: { position: "relative" }, children: [
    /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)(
      "button",
      {
        "aria-expanded": props.open,
        "aria-haspopup": "menu",
        "aria-label": props.ariaLabel,
        onClick: () => props.onOpenChange(!props.open),
        style: { ...relationBubbleDropdownButtonStyle, minWidth: props.minWidth },
        title: selected?.label,
        type: "button",
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime35.jsx)("span", { style: relationBubbleDropdownVisualStyle, children: selected?.visual }),
          /* @__PURE__ */ (0, import_jsx_runtime35.jsx)("span", { style: relationBubbleDropdownLabelStyle, children: selected?.label }),
          /* @__PURE__ */ (0, import_jsx_runtime35.jsx)("span", { "aria-hidden": "true", style: relationBubbleDropdownChevronStyle, children: /* @__PURE__ */ (0, import_jsx_runtime35.jsx)("svg", { height: "12", viewBox: "0 0 12 12", width: "12", children: /* @__PURE__ */ (0, import_jsx_runtime35.jsx)("path", { d: "M3.2 4.5 6 7.2l2.8-2.7", fill: "none", stroke: "currentColor", strokeLinecap: "round", strokeLinejoin: "round", strokeWidth: "1.5" }) }) })
        ]
      }
    ),
    props.open ? /* @__PURE__ */ (0, import_jsx_runtime35.jsx)("div", { role: "menu", style: { ...relationBubbleDropdownMenuStyle, minWidth: props.minWidth }, children: props.options.map((option) => {
      const active = option.value === props.value;
      return /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)(
        "button",
        {
          "aria-checked": active,
          onClick: () => props.onSelect(option.value),
          role: "menuitemradio",
          style: {
            ...relationBubbleDropdownItemStyle,
            background: active ? "color-mix(in srgb, var(--km-primary-bg, #2563eb) 12%, transparent)" : "transparent",
            color: active ? "var(--km-primary-bg, #2563eb)" : "var(--km-text)"
          },
          type: "button",
          children: [
            /* @__PURE__ */ (0, import_jsx_runtime35.jsx)("span", { style: relationBubbleDropdownVisualStyle, children: option.visual }),
            /* @__PURE__ */ (0, import_jsx_runtime35.jsx)("span", { style: relationBubbleDropdownLabelStyle, children: option.label })
          ]
        },
        option.value
      );
    }) }) : null
  ] });
}
function RelationQuickEditBubble(props) {
  const t = useT();
  const relation = props.doc.relations.find((item) => item.id === props.relationId);
  const anchor = relation ? resolveRelationAnchor(props.layout, relation) : null;
  const visualStyle = relation ? resolveRelationVisualStyle({
    doc: props.doc,
    nodeThemeById: props.nodeThemeById,
    relation,
    summaryThemeById: props.summaryThemeById
  }) : null;
  const [labelText, setLabelText] = (0, import_react30.useState)(() => {
    return relation?.label?.schemaVersion === 1 && relation.label.kind === "plain-text" ? relation.label.text : "";
  });
  const [strokeColor, setStrokeColor] = (0, import_react30.useState)(() => normalizeHexColor(relation?.style?.strokeColor) ?? normalizeHexColor(visualStyle?.stroke) ?? "#334155");
  const [strokeWidth, setStrokeWidth] = (0, import_react30.useState)(() => String(relation?.style?.strokeWidth ?? ""));
  const [strokeDasharray, setStrokeDasharray] = (0, import_react30.useState)(() => resolveRelationDashControlValue(relation?.style?.strokeDasharray));
  const [openMenu, setOpenMenu] = (0, import_react30.useState)(null);
  const bubbleRef = (0, import_react30.useRef)(null);
  const colorCommitTimerRef = (0, import_react30.useRef)(null);
  const pendingColorRef = (0, import_react30.useRef)(null);
  (0, import_react30.useEffect)(() => {
    setLabelText(relation?.label?.schemaVersion === 1 && relation.label.kind === "plain-text" ? relation.label.text : "");
    setStrokeColor(normalizeHexColor(relation?.style?.strokeColor) ?? normalizeHexColor(visualStyle?.stroke) ?? "#334155");
    setStrokeWidth(String(relation?.style?.strokeWidth ?? ""));
    setStrokeDasharray(resolveRelationDashControlValue(relation?.style?.strokeDasharray));
  }, [relation?.id, relation?.label, relation?.style?.strokeColor, relation?.style?.strokeWidth, relation?.style?.strokeDasharray, visualStyle?.stroke]);
  (0, import_react30.useEffect)(() => {
    return () => {
      if (colorCommitTimerRef.current) clearTimeout(colorCommitTimerRef.current);
    };
  }, []);
  (0, import_react30.useEffect)(() => {
    if (!openMenu) return;
    const onPointerDown = (event) => {
      const target2 = event.target;
      if (target2 instanceof Node && bubbleRef.current?.contains(target2)) return;
      setOpenMenu(null);
    };
    const onKeyDown = (event) => {
      if (event.key === "Escape") setOpenMenu(null);
    };
    document.addEventListener("pointerdown", onPointerDown, true);
    document.addEventListener("keydown", onKeyDown, true);
    return () => {
      document.removeEventListener("pointerdown", onPointerDown, true);
      document.removeEventListener("keydown", onKeyDown, true);
    };
  }, [openMenu]);
  if (!relation || !anchor) return null;
  if (props.viewportSize.width <= 0 || props.viewportSize.height <= 0 || props.viewBox.width <= 0 || props.viewBox.height <= 0) return null;
  const left = (anchor.x - props.viewBox.x) * (props.viewportSize.width / props.viewBox.width);
  const top = (anchor.y - props.viewBox.y) * (props.viewportSize.height / props.viewBox.height);
  const direction = relation.direction ?? RELATION_INHERIT_OPTION;
  const commitLabel = () => {
    const result = props.core.dispatch({
      type: "set_relation_label",
      payload: {
        relationId: relation.id,
        label: labelText.trim().length > 0 ? { schemaVersion: 1, kind: "plain-text", text: labelText } : null
      }
    });
    if (!result.ok) void props.dialog.alert(result.error);
  };
  const applyStyle = (patch) => {
    const nextColor = patch && Object.prototype.hasOwnProperty.call(patch, "strokeColor") ? patch.strokeColor : relation.style?.strokeColor ?? "";
    const nextWidthRaw = patch && Object.prototype.hasOwnProperty.call(patch, "strokeWidth") ? patch.strokeWidth : Number(strokeWidth);
    const nextDash = patch && Object.prototype.hasOwnProperty.call(patch, "strokeDasharray") ? normalizeRelationDashControlValue(patch.strokeDasharray) : normalizeRelationDashControlValue(strokeDasharray);
    const style2 = {
      strokeColor: typeof nextColor === "string" && nextColor.trim().length > 0 ? nextColor.trim() : void 0,
      strokeWidth: typeof nextWidthRaw === "number" && Number.isFinite(nextWidthRaw) && nextWidthRaw > 0 ? nextWidthRaw : void 0,
      strokeDasharray: typeof nextDash === "string" && nextDash.trim().length > 0 ? nextDash.trim() : void 0
    };
    const hasAny = Boolean(style2.strokeColor || style2.strokeDasharray || typeof style2.strokeWidth === "number");
    const result = props.core.dispatch({ type: "set_relation_style", payload: { relationId: relation.id, style: hasAny ? style2 : null } });
    if (!result.ok) void props.dialog.alert(result.error);
  };
  const flushColorChange = (nextColor = pendingColorRef.current ?? strokeColor) => {
    if (colorCommitTimerRef.current) {
      clearTimeout(colorCommitTimerRef.current);
      colorCommitTimerRef.current = null;
    }
    pendingColorRef.current = null;
    applyStyle({ strokeColor: nextColor });
  };
  const scheduleColorChange = (nextColor) => {
    setStrokeColor(nextColor);
    pendingColorRef.current = nextColor;
    if (colorCommitTimerRef.current) clearTimeout(colorCommitTimerRef.current);
    colorCommitTimerRef.current = setTimeout(() => {
      colorCommitTimerRef.current = null;
      const value = pendingColorRef.current ?? nextColor;
      pendingColorRef.current = null;
      applyStyle({ strokeColor: value });
    }, 96);
  };
  const setDirection = (next) => {
    const result = props.core.dispatch({
      type: "set_relation_direction",
      payload: {
        relationId: relation.id,
        direction: next === RELATION_INHERIT_OPTION ? null : next
      }
    });
    if (!result.ok) void props.dialog.alert(result.error);
  };
  const resetStyle = () => {
    setStrokeColor("");
    setStrokeWidth("");
    setStrokeDasharray(RELATION_INHERIT_OPTION);
    const batch = props.core.dispatchBatch([
      { type: "set_relation_style", payload: { relationId: relation.id, style: null } },
      { type: "set_relation_direction", payload: { relationId: relation.id, direction: null } }
    ]);
    if (!batch.ok) void props.dialog.alert(batch.error);
  };
  const deleteRelation = () => {
    const result = props.core.dispatch({ type: "delete_relation", payload: { relationId: relation.id } });
    if (!result.ok) void props.dialog.alert(result.error);
  };
  const directionButtons = [RELATION_INHERIT_OPTION, "none", "forward", "backward", "both"];
  const directionOptions = directionButtons.map((item) => ({
    value: item,
    label: item === RELATION_INHERIT_OPTION ? t("editor.relationBubble.direction.inherit") : t(`editor.relationBubble.direction.${item}`),
    visual: /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(RelationDirectionIcon, { direction: item })
  }));
  const widthOptions = [
    { value: "", label: t("editor.relationBubble.width.default"), strokeWidth: 2, muted: true },
    { value: "1", label: t("editor.relationBubble.width.hairline"), strokeWidth: 1 },
    { value: "2", label: t("editor.relationBubble.width.thin"), strokeWidth: 2 },
    { value: "3", label: t("editor.relationBubble.width.regular"), strokeWidth: 3 },
    { value: "4", label: t("editor.relationBubble.width.bold"), strokeWidth: 4 },
    { value: "5", label: t("editor.relationBubble.width.heavy"), strokeWidth: 5 },
    { value: "6", label: t("editor.relationBubble.width.extraHeavy"), strokeWidth: 6 }
  ].map((item) => ({
    value: item.value,
    label: item.label,
    visual: /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(RelationWidthPreview, { muted: item.muted === true, strokeWidth: item.strokeWidth })
  }));
  return /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)(
    "div",
    {
      ref: bubbleRef,
      "data-export-exclude": "true",
      style: {
        position: "absolute",
        left,
        top,
        transform: "translate(-50%, calc(-100% - 14px))",
        zIndex: 38,
        display: "flex",
        alignItems: "center",
        gap: 6,
        maxWidth: "min(620px, calc(100% - 24px))",
        padding: "7px 8px",
        border: "1px solid var(--km-border)",
        borderRadius: 8,
        background: "color-mix(in srgb, var(--km-panel, #fff) 94%, transparent)",
        boxShadow: "0 16px 38px rgba(15, 23, 42, 0.18)",
        color: "var(--km-text)",
        pointerEvents: "auto",
        backdropFilter: "blur(10px)"
      },
      children: [
        /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(
          "input",
          {
            "aria-label": t("editor.relationBubble.label"),
            onBlur: commitLabel,
            onChange: (event) => setLabelText(event.target.value),
            onKeyDown: (event) => {
              if (event.key === "Enter") {
                event.preventDefault();
                commitLabel();
              }
            },
            placeholder: t("editor.relationBubble.label.placeholder"),
            style: {
              width: 112,
              height: 28,
              border: "1px solid var(--km-border)",
              borderRadius: 6,
              background: "var(--km-panel)",
              color: "var(--km-text)",
              fontSize: 12,
              outline: "none",
              padding: "0 8px"
            },
            value: labelText
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(
          RelationBubbleDropdown,
          {
            ariaLabel: t("editor.relationBubble.direction"),
            minWidth: 112,
            onOpenChange: (open2) => setOpenMenu(open2 ? "direction" : null),
            onSelect: (value) => {
              setDirection(value);
              setOpenMenu(null);
            },
            open: openMenu === "direction",
            options: directionOptions,
            value: direction
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(
          "input",
          {
            "aria-label": t("editor.relationBubble.color"),
            onChange: (event) => {
              scheduleColorChange(event.target.value);
            },
            onBlur: () => flushColorChange(),
            style: { width: 30, height: 28, padding: 2, border: "1px solid var(--km-border)", borderRadius: 6, background: "transparent" },
            type: "color",
            value: normalizeHexColor(strokeColor) ?? "#334155"
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)(
          "select",
          {
            "aria-label": t("editor.relationBubble.dash"),
            onChange: (event) => {
              setStrokeDasharray(event.target.value);
              applyStyle({ strokeDasharray: event.target.value });
            },
            style: relationBubbleSelectStyle,
            value: strokeDasharray,
            children: [
              /* @__PURE__ */ (0, import_jsx_runtime35.jsx)("option", { value: RELATION_INHERIT_OPTION, children: t("editor.relationBubble.dash.inherit") }),
              /* @__PURE__ */ (0, import_jsx_runtime35.jsx)("option", { value: "none", children: t("editor.relationBubble.dash.solid") }),
              /* @__PURE__ */ (0, import_jsx_runtime35.jsx)("option", { value: "6 4", children: t("editor.relationBubble.dash.dashed") }),
              /* @__PURE__ */ (0, import_jsx_runtime35.jsx)("option", { value: "2 2", children: t("editor.relationBubble.dash.dotted") })
            ]
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(
          RelationBubbleDropdown,
          {
            ariaLabel: t("editor.relationBubble.width"),
            minWidth: 108,
            onOpenChange: (open2) => setOpenMenu(open2 ? "width" : null),
            onSelect: (value) => {
              setStrokeWidth(value);
              applyStyle({ strokeWidth: value.trim().length > 0 ? Number(value) : void 0 });
              setOpenMenu(null);
            },
            open: openMenu === "width",
            options: widthOptions,
            value: strokeWidth
          }
        ),
        /* @__PURE__ */ (0, import_jsx_runtime35.jsx)("button", { onClick: resetStyle, style: relationBubbleIconButtonStyle, tabIndex: -1, title: t("editor.relationBubble.reset"), type: "button", children: "\u21BA" }),
        /* @__PURE__ */ (0, import_jsx_runtime35.jsx)("button", { onClick: deleteRelation, style: { ...relationBubbleIconButtonStyle, color: "#ef4444" }, tabIndex: -1, title: t("editor.relationBubble.delete"), type: "button", children: "\xD7" })
      ]
    }
  );
}
var relationBubbleSelectStyle = {
  height: 28,
  maxWidth: 92,
  border: "1px solid var(--km-border)",
  borderRadius: 6,
  background: "var(--km-panel)",
  color: "var(--km-text)",
  fontSize: 12,
  outline: "none"
};
var relationBubbleDropdownButtonStyle = {
  height: 28,
  border: "1px solid var(--km-border)",
  borderRadius: 6,
  background: "var(--km-panel)",
  color: "var(--km-text)",
  cursor: "pointer",
  display: "inline-flex",
  alignItems: "center",
  justifyContent: "space-between",
  gap: 6,
  fontSize: 12,
  outline: "none",
  padding: "0 7px"
};
var relationBubbleDropdownVisualStyle = {
  display: "inline-flex",
  alignItems: "center",
  justifyContent: "center",
  flex: "0 0 auto",
  minWidth: 18
};
var relationBubbleDropdownLabelStyle = {
  overflow: "hidden",
  textOverflow: "ellipsis",
  whiteSpace: "nowrap"
};
var relationBubbleDropdownChevronStyle = {
  color: "var(--km-muted-text, #64748b)",
  fontSize: 12,
  lineHeight: 1,
  marginLeft: 1
};
var relationBubbleDropdownMenuStyle = {
  position: "absolute",
  left: 0,
  top: 34,
  zIndex: 42,
  display: "grid",
  gap: 2,
  padding: 4,
  border: "1px solid var(--km-border)",
  borderRadius: 8,
  background: "var(--km-panel)",
  boxShadow: "0 18px 42px rgba(15, 23, 42, 0.2)"
};
var relationBubbleDropdownItemStyle = {
  height: 30,
  border: "none",
  borderRadius: 6,
  background: "transparent",
  color: "var(--km-text)",
  cursor: "pointer",
  display: "flex",
  alignItems: "center",
  gap: 8,
  fontSize: 12,
  padding: "0 8px",
  textAlign: "left",
  whiteSpace: "nowrap"
};
var relationBubbleIconButtonStyle = {
  width: 28,
  height: 28,
  border: "1px solid var(--km-border)",
  borderRadius: 6,
  background: "transparent",
  color: "var(--km-text)",
  cursor: "pointer",
  fontSize: 15,
  lineHeight: "26px"
};
function resolveRelationAnchor(layout, relation) {
  const from2 = resolveRelationEndpointLayout2(layout, relation.from);
  const to = resolveRelationEndpointLayout2(layout, relation.to);
  if (!from2 || !to) return null;
  const start = resolvePortPoint3(from2, relation.from.port ?? "right", relation.from.portRatio);
  const end = resolvePortPoint3(to, relation.to.port ?? "left", relation.to.portRatio);
  const { control1: defaultControl1, control2: defaultControl2 } = computeDefaultCubicControlDeltas(start, end);
  const curveV1 = relation.curve?.schemaVersion === 1 && relation.curve.kind === "cubic" ? relation.curve : null;
  const control1 = curveV1?.control1 ?? defaultControl1;
  const control2 = curveV1?.control2 ?? defaultControl2;
  const c1 = { x: start.x + control1.x, y: start.y + control1.y };
  const c2 = { x: end.x + control2.x, y: end.y + control2.y };
  return cubicAtHalf3(start, c1, c2, end);
}
function resolveRelationEndpointLayout2(layout, endpoint) {
  return endpoint.kind === "summary" ? layout.summaries[endpoint.summaryId] : layout.nodes[endpoint.nodeId];
}
function resolveRelationEndpointTheme(endpoint, nodeThemeById, summaryThemeById) {
  return endpoint.kind === "summary" ? summaryThemeById[endpoint.summaryId] : nodeThemeById[endpoint.nodeId];
}
function resolveRelationVisualStyle(args) {
  const baseTheme = resolveRelationEndpointTheme(args.relation.from, args.nodeThemeById, args.summaryThemeById) ?? resolveRelationEndpointTheme(args.relation.to, args.nodeThemeById, args.summaryThemeById);
  const override = args.doc.theme?.overrides?.relations?.[args.relation.id];
  const sharedRootId = relationEndpointsShareRoot(args.doc, args.relation);
  const rootStyle = sharedRootId ? args.doc.theme?.rootRelationStyles?.[sharedRootId] : void 0;
  const projectStyle = args.doc.theme?.relationStyle;
  return {
    stroke: args.relation.style?.strokeColor ?? override?.strokeColor ?? rootStyle?.strokeColor ?? projectStyle?.strokeColor ?? baseTheme?.paint.relationStroke ?? "#334155",
    strokeWidth: args.relation.style?.strokeWidth ?? override?.strokeWidth ?? rootStyle?.strokeWidth ?? projectStyle?.strokeWidth ?? baseTheme?.relations?.strokeWidth ?? 2,
    dasharray: args.relation.style?.strokeDasharray ?? override?.dasharray ?? rootStyle?.dasharray ?? projectStyle?.dasharray ?? baseTheme?.relations?.dasharray ?? ""
  };
}
function CursorIconBadge(props) {
  return /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(
    "div",
    {
      "aria-hidden": "true",
      "data-export-exclude": "true",
      style: {
        position: "fixed",
        left: props.cursor.x + 10,
        top: props.cursor.y + 10,
        width: 28,
        height: 28,
        borderRadius: 10,
        border: "1px solid rgba(148, 163, 184, 0.45)",
        background: "rgba(255,255,255,0.92)",
        boxShadow: "0 18px 36px rgba(15, 23, 42, 0.18)",
        pointerEvents: "none",
        display: "flex",
        alignItems: "center",
        justifyContent: "center",
        zIndex: 120
      },
      title: props.label,
      children: /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(Icon, { iconId: props.iconId, size: 16 })
    }
  );
}
function EditorView2(args) {
  const t = useT();
  const {
    props: editorProps,
    submap,
    doc: doc3,
    embedRegistry,
    nodeBodyLayout,
    dialog,
    clipboard,
    assetObjectUrlById,
    assetObjectUrlVersion,
    perfConfig,
    perfStatsRef,
    svgRef,
    canvasRef,
    viewBox,
    viewportSize,
    viewportCullRect,
    visibleNodeIds,
    visibleSummaryIds,
    panByViewportDelta,
    selection,
    setSelection,
    contextMenu,
    closeContextMenu,
    openNodeContextMenuAt,
    openSummaryContextMenuAt,
    onCanvasContextMenu,
    hoveredNodeId,
    setHoveredNodeId,
    selectedNodeIds,
    editing,
    editingLayout,
    pendingRelationFromId,
    editingLayoutMode,
    dragGhostMode,
    editTabEnterBehavior,
    setInternalEditingLayoutMode,
    setInternalDragGhostMode,
    setInternalEditTabEnterBehavior,
    setEditingDraftSize,
    resizeDraft,
    relationCurveDraft,
    relationEndpointsDraft,
    blurViewState,
    setBlurViewState,
    documentTheme,
    themeVars,
    uiVars,
    nodeThemeById,
    summaryThemeById,
    backlinksIndex,
    progressByNodeId,
    layout,
    sceneLayout,
    containerLayoutTypeById,
    hiddenNodeIds,
    hiddenSummaryIds,
    dropHighlight,
    selectionToolbarHighlightNodeId,
    revealHighlightNodeId,
    revealHighlightSummaryId,
    setSelectionToolbarHighlightNodeId,
    selectionToolbarPopoverRequest,
    selectionToolbarActionRequest,
    requestSelectionToolbarPopover,
    requestSelectionToolbarAction,
    onSelectionToolbarPopoverRequestHandled,
    onSelectionToolbarActionRequestHandled,
    ghostDelta,
    dragUi,
    isPanning,
    marqueeRect,
    linksPanel,
    linksPanelPosition,
    closeLinksPanel,
    openLinksPanel,
    onRequestLinksPanelModeChange,
    onLinksPanelHoverChange,
    onLinksPanelIconHoverChange,
    metaPopover,
    metaPopoverPosition,
    metaPopoverCommitRef,
    closeMetaPopover,
    openMetaPopover,
    onMetaPopoverHoverChange,
    onRequestMetaPopoverModeChange,
    onOverlayNodeHoverChange,
    onOverlayNodePointerMove,
    exportExpandedEnabled,
    exportExpandedDoc,
    exportExpandedLayout,
    exportExpandedSvgRef,
    exportExpandedContainerLayoutTypeById,
    exportFullActive,
    exportFullSvgRef,
    subtreeExportNodeId,
    subtreeExportDoc,
    subtreeExportLayout,
    subtreeExportSvgRef,
    subtreeExportContainerLayoutTypeById,
    svgExportMode,
    setSvgExportMode,
    pngExportMode,
    setPngExportMode,
    exportScope,
    setExportScope,
    hasCollapsedNodes,
    spaceDown,
    onCanvasBlur,
    onCanvasCopy,
    onCanvasPaste,
    onCanvasKeyDownCapture,
    onCanvasKeyUpCapture,
    onSvgPointerDownCapture,
    onSvgPointerMove,
    onSvgPointerUp,
    onSvgPointerCancel,
    onSvgDoubleClick,
    onNodePointerDown,
    onSummaryPointerDown,
    onNodeResizeHandlePointerDown,
    onRelationControlHandlePointerDown,
    onRelationLabelDoubleClick,
    relationLabelEditing,
    commitRelationLabelEditing,
    cancelRelationLabelEditing,
    undo: undo2,
    redo: redo2,
    addChild,
    addSibling,
    addRoot,
    moveRoot,
    toggleLayout,
    createSummary,
    startRelation,
    toggleNodeCollapsed,
    deleteSelected,
    copyNodeContent,
    pasteNodeContent,
    copySubtree,
    pasteSubtree,
    exportSvg,
    exportPng,
    importFreeMind,
    focusCanvas,
    selectNodeAndReveal,
    selectSingleNode,
    selectSummary,
    selectRelation,
    startEditNode,
    startEditSummary,
    stopEdit,
    emptySelectedNodeIds,
    isCanvasOnly,
    measurerRef,
    richTextEditorRef,
    onCommitNodeRichText,
    onCommitSummaryRichText
  } = args.model;
  const textEditor = editorProps.textEditor ?? "rich";
  const canvasBackground = documentTheme.background?.color ?? "var(--km-bg)";
  const props = editorProps;
  const selectionQuickActions = props.appUi && selection?.type === "node" ? buildSelectionQuickActions({
    isRoot: doc3.roots.includes(selection.id),
    selectionToolbar: props.appUi.selectionToolbar,
    labels: {
      "builtin.links": t("editor.selectionToolbar.button.link"),
      "builtin.image": t("editor.selectionToolbar.button.image"),
      "builtin.icons": t("editor.selectionToolbar.button.icons"),
      "builtin.tags": t("editor.selectionToolbar.button.tags"),
      "builtin.brush": t("editor.selectionToolbar.button.brush"),
      "builtin.notes": t("editor.selectionToolbar.button.notes"),
      "builtin.comments": t("editor.selectionToolbar.button.comments")
    }
  }) : [];
  const summaryContextQuickActions = props.appUi ? buildSummaryContextQuickActions({
    selectionToolbar: props.appUi.selectionToolbar
  }) : [];
  const contextMenuQuickActions = contextMenu?.scope === "summary" ? summaryContextQuickActions : selectionQuickActions;
  const [summaryRelationPickerCursor, setSummaryRelationPickerCursor] = (0, import_react30.useState)(null);
  (0, import_react30.useEffect)(() => {
    if (pendingRelationFromId?.kind !== "summary") {
      setSummaryRelationPickerCursor(null);
      return;
    }
    const win = typeof window !== "undefined" ? window : null;
    if (!win) return;
    const onMove = (event) => {
      setSummaryRelationPickerCursor({ x: event.clientX, y: event.clientY });
    };
    win.addEventListener("pointermove", onMove, true);
    return () => win.removeEventListener("pointermove", onMove, true);
  }, [pendingRelationFromId]);
  const readOnly = Boolean(props.appUi?.snapshot.editor.viewModes.readOnly.value);
  const premiumCapabilities = props.premiumCapabilities ?? {
    canCreateBacklinks: true,
    canInsertFormula: true,
    canInsertCloze: true,
    canCreateComments: true,
    canInsertSiyuanDocLink: true
  };
  const onPremiumFeatureBlocked = props.onPremiumFeatureBlocked;
  const builtinIconSymbolPrefixBase = `kmind-icons-${(0, import_react30.useId)().replaceAll(":", "_")}`;
  const mainBuiltinIconSymbolPrefix = `${builtinIconSymbolPrefixBase}-main`;
  const exportFullBuiltinIconSymbolPrefix = `${builtinIconSymbolPrefixBase}-export-full`;
  const exportExpandedBuiltinIconSymbolPrefix = `${builtinIconSymbolPrefixBase}-export-expanded`;
  const subtreeExportBuiltinIconSymbolPrefix = `${builtinIconSymbolPrefixBase}-export-subtree`;
  const [crossPaneMapDropHighlight, setCrossPaneMapDropHighlight] = (0, import_react30.useState)(null);
  const resolveCrossPaneMapDrop = (0, import_react30.useCallback)((nodeId, clientX, clientY) => {
    if (editorProps.interaction?.readOnly) return { command: null, canDrop: false, highlight: null };
    if (!doc3.nodes[nodeId]) return { command: null, canDrop: false, highlight: null };
    const svg = svgRef.current;
    if (!svg) return { command: null, canDrop: false, highlight: null };
    const world = clientToWorldFromSvg({ svg, viewBox, clientX, clientY });
    if (!world) return { command: null, canDrop: false, highlight: null };
    const draggedLayout = layout.nodes[nodeId];
    if (!draggedLayout) return { command: null, canDrop: false, highlight: null };
    const subtree = collectSubtreeElements(doc3, nodeId);
    for (const ignoredNodeId of subtree.nodeIds) {
      if (pointInsideLayoutItem(world, layout.nodes[ignoredNodeId])) {
        return { command: null, canDrop: false, highlight: { type: "node", id: ignoredNodeId } };
      }
    }
    for (const ignoredSummaryId of subtree.summaryIds) {
      if (pointInsideLayoutItem(world, layout.summaries[ignoredSummaryId])) {
        return { command: null, canDrop: false, highlight: { type: "summary", id: ignoredSummaryId } };
      }
    }
    const ghost = {
      x: world.x - draggedLayout.width / 2,
      y: world.y - draggedLayout.height / 2
    };
    const intent = resolveDropIntentV2({
      doc: doc3,
      layout,
      draggedNodeId: nodeId,
      draggedRect: { x: ghost.x, y: ghost.y, width: draggedLayout.width, height: draggedLayout.height },
      ignoreNodeIds: subtree.nodeIds,
      ignoreSummaryIds: subtree.summaryIds,
      currentIntent: { kind: "none" },
      options: {
        tailSize: crossPaneDropTailSize,
        childEnterPadding: crossPaneChildEnterPadding,
        childLeavePadding: crossPaneChildLeavePadding,
        siblingLanePadding: crossPaneSiblingLanePadding,
        siblingLanePaddingActive: crossPaneSiblingLanePaddingActive,
        siblingEndPadding: crossPaneSiblingEndPadding,
        siblingEndPaddingActive: crossPaneSiblingEndPaddingActive
      }
    });
    if (intent.kind === "as-child") {
      const command2 = intent.target.type === "node" ? {
        type: "move_node",
        payload: { nodeId, to: { type: "node", parentId: intent.target.id, branchSide: intent.branchSide } }
      } : { type: "move_node", payload: { nodeId, to: { type: "summary", summaryId: intent.target.id } } };
      return { command: command2, canDrop: true, highlight: { type: intent.target.type, id: intent.target.id } };
    }
    if (intent.kind === "as-sibling") {
      const command2 = intent.parent.type === "node" ? {
        type: "move_node",
        payload: {
          nodeId,
          to: {
            type: "node",
            parentId: intent.parent.id,
            index: intent.index,
            ...intent.branchSide ? { branchSide: intent.branchSide } : {}
          }
        }
      } : intent.parent.type === "summary" ? {
        type: "move_node",
        payload: { nodeId, to: { type: "summary", summaryId: intent.parent.id, index: intent.index } }
      } : {
        type: "move_node",
        payload: { nodeId, to: { type: "root", index: intent.index, position: { x: ghost.x, y: ghost.y } } }
      };
      return {
        command: command2,
        canDrop: true,
        highlight: intent.parent.type === "root" ? null : { type: intent.parent.type, id: intent.parent.id }
      };
    }
    return {
      command: { type: "move_node", payload: { nodeId, to: { type: "root", position: { x: ghost.x, y: ghost.y } } } },
      canDrop: true,
      highlight: null
    };
  }, [doc3, editorProps.interaction?.readOnly, layout, svgRef, viewBox]);
  const activeOutlineCrossPaneSession = props.crossPaneDrag?.activeSession?.sourcePane === "outline" && props.crossPaneDrag.activeSession.editorInstanceId === props.crossPaneDrag.editorInstanceId ? props.crossPaneDrag.activeSession : null;
  const activeOutlineCrossPaneNodeId = activeOutlineCrossPaneSession?.nodeId ?? null;
  const onCrossPaneMapDragOver = (0, import_react30.useCallback)((event) => {
    const nodeId = activeOutlineCrossPaneNodeId;
    if (!nodeId) return;
    event.preventDefault();
    event.stopPropagation();
    const resolved = resolveCrossPaneMapDrop(nodeId, event.clientX, event.clientY);
    setCrossPaneMapDropHighlight(resolved.highlight);
    if (event.dataTransfer) event.dataTransfer.dropEffect = resolved.canDrop ? "move" : "none";
    props.crossPaneDrag?.onMapTargetHover?.({
      nodeId,
      clientX: event.clientX,
      clientY: event.clientY,
      canDrop: resolved.canDrop,
      command: resolved.command,
      highlight: resolved.highlight
    });
    const panDelta = resolveCrossPaneMapAutoPanDelta(svgRef.current, event.clientX, event.clientY);
    if (panDelta) panByViewportDelta(panDelta);
  }, [activeOutlineCrossPaneNodeId, panByViewportDelta, props.crossPaneDrag, resolveCrossPaneMapDrop, svgRef]);
  const onCrossPaneMapDrop = (0, import_react30.useCallback)((event) => {
    const nodeId = activeOutlineCrossPaneNodeId;
    if (!nodeId) return;
    event.preventDefault();
    event.stopPropagation();
    const resolved = resolveCrossPaneMapDrop(nodeId, event.clientX, event.clientY);
    setCrossPaneMapDropHighlight(null);
    if (!resolved.canDrop || !resolved.command) {
      props.crossPaneDrag?.onMapTargetLeave?.();
      return;
    }
    const result = props.core.dispatch(resolved.command);
    if (!result.ok) {
      void dialog.alert(result.error);
      props.crossPaneDrag?.onMapTargetLeave?.();
      return;
    }
    selectSingleNode(nodeId);
    props.crossPaneDrag?.onMapTargetDrop?.({ nodeId, command: resolved.command });
  }, [activeOutlineCrossPaneNodeId, dialog, props.core, props.crossPaneDrag, resolveCrossPaneMapDrop, selectSingleNode]);
  const onCrossPaneMapDragLeave = (0, import_react30.useCallback)((event) => {
    const nodeId = activeOutlineCrossPaneNodeId;
    if (!nodeId) return;
    const next = event.relatedTarget;
    if (next instanceof Node && svgRef.current?.contains(next)) return;
    setCrossPaneMapDropHighlight(null);
    props.crossPaneDrag?.onMapTargetLeave?.();
  }, [activeOutlineCrossPaneNodeId, props.crossPaneDrag, svgRef]);
  (0, import_react30.useEffect)(() => {
    if (activeOutlineCrossPaneNodeId) return;
    setCrossPaneMapDropHighlight(null);
  }, [activeOutlineCrossPaneNodeId]);
  return /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)(
    "div",
    {
      className: props.className,
      style: isCanvasOnly ? { position: "relative", width: "100%", height: "100%", ...uiVars } : { display: "flex", flexDirection: "column", gap: 12, ...uiVars },
      children: [
        isCanvasOnly ? null : /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)("div", { style: { display: "flex", flexWrap: "wrap", alignItems: "center", gap: 8 }, children: [
          /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(
            "button",
            {
              onClick: () => {
                if (selection?.type === "node") startEditNode(selection.id);
                if (selection?.type === "summary") startEditSummary(selection.id);
              },
              style: buttonStyle,
              type: "button",
              children: "\u7F16\u8F91"
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime35.jsx)("button", { onClick: undo2, style: buttonStyle, type: "button", children: "\u64A4\u9500" }),
          /* @__PURE__ */ (0, import_jsx_runtime35.jsx)("button", { onClick: redo2, style: buttonStyle, type: "button", children: "\u91CD\u505A" }),
          /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(
            "button",
            {
              onClick: addChild,
              style: buttonStyle,
              type: "button",
              children: "\u65B0\u589E\u5B50\u8282\u70B9"
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime35.jsx)("button", { onClick: addRoot, style: buttonStyle, type: "button", children: "\u65B0\u589E Root" }),
          /* @__PURE__ */ (0, import_jsx_runtime35.jsx)("button", { onClick: () => moveRoot("up"), style: buttonStyle, type: "button", children: "Root \u4E0A\u79FB" }),
          /* @__PURE__ */ (0, import_jsx_runtime35.jsx)("button", { onClick: () => moveRoot("down"), style: buttonStyle, type: "button", children: "Root \u4E0B\u79FB" }),
          /* @__PURE__ */ (0, import_jsx_runtime35.jsx)("button", { onClick: toggleLayout, style: buttonStyle, type: "button", children: "\u5207\u6362\u5E03\u5C40" }),
          /* @__PURE__ */ (0, import_jsx_runtime35.jsx)("button", { onClick: createSummary, style: buttonStyle, type: "button", children: "\u521B\u5EFA\u6982\u8981" }),
          /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(
            "button",
            {
              onClick: startRelation,
              style: buttonStyle,
              type: "button",
              children: pendingRelationFromId ? "\u9009\u62E9\u76EE\u6807\u8282\u70B9\u2026" : "\u521B\u5EFA\u5173\u8054\u7EBF"
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime35.jsx)("button", { onClick: () => void copyNodeContent(), style: buttonStyle, type: "button", children: "\u590D\u5236\u5185\u5BB9" }),
          /* @__PURE__ */ (0, import_jsx_runtime35.jsx)("button", { onClick: () => void pasteNodeContent(), style: buttonStyle, type: "button", children: "\u7C98\u8D34\u5185\u5BB9" }),
          /* @__PURE__ */ (0, import_jsx_runtime35.jsx)("button", { onClick: () => void copySubtree(), style: buttonStyle, type: "button", children: "\u590D\u5236\u5B50\u6811" }),
          /* @__PURE__ */ (0, import_jsx_runtime35.jsx)("button", { onClick: () => void pasteSubtree(), style: buttonStyle, type: "button", children: "\u7C98\u8D34\u5B50\u6811" }),
          /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(
            "button",
            {
              onClick: deleteSelected,
              style: buttonStyle,
              type: "button",
              children: "\u5220\u9664"
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime35.jsx)("span", { style: { height: 16, width: 1, background: "#e2e8f0", marginInline: 4 } }),
          /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)("label", { style: { display: "flex", alignItems: "center", gap: 6, fontSize: 12, color: "var(--km-muted)" }, children: [
            "\u7F16\u8F91\u5E03\u5C40",
            /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)(
              "select",
              {
                disabled: props.editingLayoutMode !== void 0,
                onChange: (event) => setInternalEditingLayoutMode(event.target.value),
                style: { ...buttonStyle, padding: "4px 8px" },
                value: editingLayoutMode,
                children: [
                  /* @__PURE__ */ (0, import_jsx_runtime35.jsx)("option", { value: "stable", children: "stable" }),
                  /* @__PURE__ */ (0, import_jsx_runtime35.jsx)("option", { value: "live-preview", children: "live-preview" })
                ]
              }
            )
          ] }),
          /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)("label", { style: { display: "flex", alignItems: "center", gap: 6, fontSize: 12, color: "var(--km-muted)" }, children: [
            "Drag ghost",
            /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)(
              "select",
              {
                disabled: props.dragGhostMode !== void 0,
                onChange: (event) => setInternalDragGhostMode(event.target.value),
                style: { ...buttonStyle, padding: "4px 8px" },
                value: dragGhostMode,
                children: [
                  /* @__PURE__ */ (0, import_jsx_runtime35.jsx)("option", { value: "light", children: "light" }),
                  /* @__PURE__ */ (0, import_jsx_runtime35.jsx)("option", { value: "rich", children: "rich" })
                ]
              }
            )
          ] }),
          /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)("label", { style: { display: "flex", alignItems: "center", gap: 6, fontSize: 12, color: "var(--km-muted)" }, children: [
            "\u7F16\u8F91\u6D41\uFF08Tab/Enter\uFF09",
            /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)(
              "select",
              {
                disabled: props.editTabEnterBehavior !== void 0,
                onChange: (event) => setInternalEditTabEnterBehavior(event.target.value),
                style: { ...buttonStyle, padding: "4px 8px" },
                value: editTabEnterBehavior,
                children: [
                  /* @__PURE__ */ (0, import_jsx_runtime35.jsx)("option", { value: "exit", children: "A\uFF1A\u63D0\u4EA4\u9000\u51FA" }),
                  /* @__PURE__ */ (0, import_jsx_runtime35.jsx)("option", { value: "create-next", children: "B\uFF1A\u63D0\u4EA4\u5E76\u521B\u5EFA\u4E0B\u4E00\u8282\u70B9" })
                ]
              }
            )
          ] }),
          /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)("label", { style: { display: "flex", alignItems: "center", gap: 6, fontSize: 12, color: "var(--km-muted)" }, children: [
            "Blur \u6301\u4E45\u5316",
            /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)(
              "select",
              {
                onChange: (event) => setBlurViewState((prev) => ({ ...prev, revealPersistence: event.target.value })),
                style: { ...buttonStyle, padding: "4px 8px" },
                value: blurViewState.revealPersistence,
                children: [
                  /* @__PURE__ */ (0, import_jsx_runtime35.jsx)("option", { value: "session", children: "session" }),
                  /* @__PURE__ */ (0, import_jsx_runtime35.jsx)("option", { value: "local", children: "local" }),
                  /* @__PURE__ */ (0, import_jsx_runtime35.jsx)("option", { value: "document", children: "document" })
                ]
              }
            )
          ] }),
          /* @__PURE__ */ (0, import_jsx_runtime35.jsx)("button", { onClick: () => setBlurViewState((prev) => showAllBlur(prev)), style: buttonStyle, type: "button", children: "\u663E\u793A\u5168\u90E8 Blur" }),
          /* @__PURE__ */ (0, import_jsx_runtime35.jsx)("button", { onClick: () => setBlurViewState((prev) => hideAllBlur(prev)), style: buttonStyle, type: "button", children: "\u9690\u85CF\u5168\u90E8 Blur" }),
          /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)("label", { style: { display: "flex", alignItems: "center", gap: 6, fontSize: 12, color: "#475569" }, children: [
            "SVG \u6A21\u5F0F",
            /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)(
              "select",
              {
                onChange: (event) => setSvgExportMode(event.target.value),
                style: { ...buttonStyle, padding: "4px 8px" },
                value: svgExportMode,
                children: [
                  /* @__PURE__ */ (0, import_jsx_runtime35.jsx)("option", { value: "fidelity", children: "fidelity" }),
                  /* @__PURE__ */ (0, import_jsx_runtime35.jsx)("option", { value: "portable", children: "portable" })
                ]
              }
            )
          ] }),
          /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)("label", { style: { display: "flex", alignItems: "center", gap: 6, fontSize: 12, color: "#475569" }, children: [
            "\u5BFC\u51FA\u8303\u56F4",
            /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)(
              "select",
              {
                onChange: (event) => setExportScope(event.target.value),
                style: { ...buttonStyle, padding: "4px 8px" },
                value: exportScope,
                children: [
                  /* @__PURE__ */ (0, import_jsx_runtime35.jsx)("option", { value: "current", children: "current" }),
                  /* @__PURE__ */ (0, import_jsx_runtime35.jsx)("option", { value: "expanded", disabled: !hasCollapsedNodes, children: "expanded" })
                ]
              }
            )
          ] }),
          /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(
            "button",
            {
              onClick: exportSvg,
              style: buttonStyle,
              type: "button",
              children: "\u5BFC\u51FA SVG"
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)("label", { style: { display: "flex", alignItems: "center", gap: 6, fontSize: 12, color: "#475569" }, children: [
            "PNG \u6A21\u5F0F",
            /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)(
              "select",
              {
                onChange: (event) => setPngExportMode(event.target.value),
                style: { ...buttonStyle, padding: "4px 8px" },
                value: pngExportMode,
                children: [
                  /* @__PURE__ */ (0, import_jsx_runtime35.jsx)("option", { value: "fast", children: "fast" }),
                  /* @__PURE__ */ (0, import_jsx_runtime35.jsx)("option", { value: "accurate", children: "accurate" })
                ]
              }
            )
          ] }),
          /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(
            "button",
            {
              onClick: () => void exportPng(1),
              style: buttonStyle,
              type: "button",
              children: "\u5BFC\u51FA PNG\uFF081x\uFF09"
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(
            "button",
            {
              onClick: () => void exportPng(2),
              style: buttonStyle,
              type: "button",
              children: "\u5BFC\u51FA PNG\uFF082x\uFF09"
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)("label", { style: { display: "inline-flex", alignItems: "center", gap: 6, fontSize: 12, color: "var(--km-muted)" }, children: [
            "\u5BFC\u5165 FreeMind",
            /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(
              "input",
              {
                accept: ".mm,text/xml,application/xml",
                onChange: (event) => {
                  const file = event.target.files?.[0];
                  if (!file) return;
                  void importFreeMind(file);
                  event.target.value = "";
                },
                style: { fontSize: 12 },
                type: "file"
              }
            )
          ] }),
          /* @__PURE__ */ (0, import_jsx_runtime35.jsx)("div", { style: { marginLeft: "auto", fontSize: 12, color: "#64748b" }, children: selection ? `\u9009\u4E2D: ${selection.type}:${selection.id}` : "\u672A\u9009\u4E2D" })
        ] }),
        /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(
          "div",
          {
            ref: canvasRef,
            tabIndex: 0,
            onBlur: onCanvasBlur,
            onCopy: onCanvasCopy,
            onContextMenu: onCanvasContextMenu,
            onKeyDownCapture: onCanvasKeyDownCapture,
            onKeyUpCapture: onCanvasKeyUpCapture,
            onPaste: onCanvasPaste,
            style: {
              position: "relative",
              overflow: "hidden",
              height: props.canvasHeight ?? (isCanvasOnly ? "100%" : 560),
              borderRadius: isCanvasOnly ? 0 : 12,
              border: isCanvasOnly ? "none" : "1px solid var(--km-border)",
              background: canvasBackground,
              outline: "none",
              ...themeVars
            },
            children: /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)("div", { style: { position: "relative", width: "100%", height: "100%" }, children: [
              /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)(
                "svg",
                {
                  ref: svgRef,
                  onDragLeave: onCrossPaneMapDragLeave,
                  onDragOver: onCrossPaneMapDragOver,
                  onDrop: onCrossPaneMapDrop,
                  onDoubleClick: onSvgDoubleClick,
                  onPointerDownCapture: onSvgPointerDownCapture,
                  onPointerCancel: onSvgPointerCancel,
                  onPointerLeave: () => setHoveredNodeId(null),
                  onPointerMove: onSvgPointerMove,
                  onPointerUp: onSvgPointerUp,
                  style: {
                    display: "block",
                    width: "100%",
                    height: "100%",
                    background: canvasBackground,
                    touchAction: "none",
                    cursor: isPanning ? "grabbing" : spaceDown ? "grab" : "default",
                    ...themeVars
                  },
                  viewBox: `${viewBox.x} ${viewBox.y} ${viewBox.width} ${viewBox.height}`,
                  xmlns: "http://www.w3.org/2000/svg",
                  children: [
                    /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)("defs", { children: [
                      /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(
                        "pattern",
                        {
                          height: 20,
                          id: `km-grid-${props.core.id}`,
                          patternUnits: "userSpaceOnUse",
                          width: 20,
                          x: 0,
                          y: 0,
                          children: /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(
                            "path",
                            {
                              d: "M 20 0 L 0 0 0 20",
                              fill: "none",
                              opacity: 0.5,
                              stroke: documentTheme.variantId === "dark" ? "rgba(148, 163, 184, 0.20)" : "rgba(100, 116, 139, 0.18)",
                              strokeWidth: 1
                            }
                          )
                        }
                      ),
                      /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)("linearGradient", { id: `km-ai-rainbow-${mainBuiltinIconSymbolPrefix}`, x1: "0", x2: "1", y1: "0", y2: "1", children: [
                        /* @__PURE__ */ (0, import_jsx_runtime35.jsx)("stop", { offset: "0%", stopColor: "#f43f5e" }),
                        /* @__PURE__ */ (0, import_jsx_runtime35.jsx)("stop", { offset: "16%", stopColor: "#f97316" }),
                        /* @__PURE__ */ (0, import_jsx_runtime35.jsx)("stop", { offset: "32%", stopColor: "#facc15" }),
                        /* @__PURE__ */ (0, import_jsx_runtime35.jsx)("stop", { offset: "48%", stopColor: "#22c55e" }),
                        /* @__PURE__ */ (0, import_jsx_runtime35.jsx)("stop", { offset: "64%", stopColor: "#38bdf8" }),
                        /* @__PURE__ */ (0, import_jsx_runtime35.jsx)("stop", { offset: "80%", stopColor: "#6366f1" }),
                        /* @__PURE__ */ (0, import_jsx_runtime35.jsx)("stop", { offset: "100%", stopColor: "#a855f7" })
                      ] }),
                      /* @__PURE__ */ (0, import_jsx_runtime35.jsx)("style", { children: `
                @keyframes kmind-ripple {
                  from { transform: scale(0.6); opacity: 0.85; }
                  to { transform: scale(1.6); opacity: 0; }
                }
                .kmind-ripple {
                  transform-box: fill-box;
                  transform-origin: center;
                  animation: kmind-ripple 260ms ease-out forwards;
                }
                @keyframes kmind-ai-cowrite-dash {
                  from { stroke-dashoffset: 0; }
                  to { stroke-dashoffset: -48; }
                }
                .kmind-ai-cowrite-dash-anim {
                  animation: kmind-ai-cowrite-dash 900ms linear infinite;
                }
              ` }),
                      /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(BuiltinUiIconSymbols, { prefix: mainBuiltinIconSymbolPrefix })
                    ] }),
                    /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)("g", { children: [
                      /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(
                        "rect",
                        {
                          "data-export-exclude": "true",
                          fill: `url(#km-grid-${props.core.id})`,
                          height: viewBox.height,
                          opacity: dragUi?.isRoot && dragUi.intent.kind === "none" ? 1 : 0,
                          style: { transition: "opacity 180ms ease", pointerEvents: "none" },
                          width: viewBox.width,
                          x: viewBox.x,
                          y: viewBox.y
                        }
                      ),
                      /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(
                        Edges,
                        {
                          containerLayoutTypeById,
                          hiddenNodeIds,
                          hiddenSummaryIds,
                          layout: sceneLayout,
                          viewportCullRect: visibleNodeIds || visibleSummaryIds ? viewportCullRect : null,
                          visibleNodeIds,
                          visibleSummaryIds,
                          nodeThemeById,
                          perfEnabled: perfConfig.enabled,
                          perfStatsRef: perfConfig.enabled ? perfStatsRef : null
                        }
                      ),
                      /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(
                        Relations,
                        {
                          doc: doc3,
                          excludedNodeIds: hiddenNodeIds,
                          visibleNodeIds,
                          visibleSummaryIds,
                          layout: sceneLayout,
                          nodeThemeById,
                          summaryThemeById,
                          markerIdPrefix: `km-relation-arrow-${mainBuiltinIconSymbolPrefix}`,
                          curveDraft: relationCurveDraft,
                          endpointsDraft: relationEndpointsDraft,
                          onRelationSelect: (relationId) => {
                            focusCanvas();
                            selectRelation(relationId);
                          },
                          onRelationLabelDoubleClick,
                          selectedRelationId: selection?.type === "relation" ? selection.id : null,
                          perfEnabled: perfConfig.enabled,
                          perfStatsRef: perfConfig.enabled ? perfStatsRef : null
                        }
                      ),
                      /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(
                        SummaryBrackets,
                        {
                          doc: doc3,
                          hiddenSummaryIds,
                          visibleSummaryIds,
                          highlightId: (dropHighlight?.type === "summary" ? dropHighlight.id : null) ?? (crossPaneMapDropHighlight?.type === "summary" ? crossPaneMapDropHighlight.id : null) ?? revealHighlightSummaryId,
                          layout: sceneLayout,
                          summaryThemeById
                        }
                      ),
                      /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(
                        Nodes,
                        {
                          assetObjectUrlById,
                          assetObjectUrlVersion,
                          builtinIconSymbolPrefix: mainBuiltinIconSymbolPrefix,
                          backlinksIndex,
                          doc: doc3,
                          external: props.external,
                          layoutTypeById: containerLayoutTypeById,
                          collapseToggleVisibility: editorProps.interaction?.collapseToggleVisibility,
                          showNodeWidthResizeHandle: editorProps.nodeChrome?.showNodeWidthResizeHandle,
                          showAddChildButton: editorProps.nodeChrome?.showAddChildButton,
                          showNodeMenuTrigger: editorProps.nodeChrome?.showNodeMenuTrigger,
                          canRequestAddChild: props.appUi?.isCommandEnabled?.("mindmap.addChild") ?? Boolean(props.appUi),
                          externalLinkPlacement: editorProps.nodeChrome?.externalLinkPlacement,
                          blurViewState,
                          nodeBodyLayout,
                          nodeHtmlCache: perfConfig.nodeHtmlCache,
                          optimizeEmbedMounting: perfConfig.optimizeEmbedMounting,
                          progressByNodeId,
                          embedRegistry,
                          hiddenNodeIds,
                          visibleNodeIds,
                          highlightId: selectionToolbarHighlightNodeId ?? (dropHighlight?.type === "node" ? dropHighlight.id : null) ?? (crossPaneMapDropHighlight?.type === "node" ? crossPaneMapDropHighlight.id : null) ?? revealHighlightNodeId,
                          editing,
                          forceCursor: spaceDown ? "grab" : null,
                          layout: sceneLayout,
                          nodeThemeById,
                          onOpenLinksPanel: (nodeId, mode) => {
                            focusCanvas();
                            selectSingleNode(nodeId);
                            openLinksPanel(nodeId, mode);
                          },
                          onNodeDoubleClick: startEditNode,
                          onNodePointerDown,
                          onNodePointerMove: onOverlayNodePointerMove,
                          onNodeHoverChange: (nodeId) => {
                            setHoveredNodeId(nodeId);
                            onOverlayNodeHoverChange?.(nodeId);
                          },
                          submap,
                          onToggleNodeCollapsed: toggleNodeCollapsed,
                          onRequestAddChild: props.appUi ? () => {
                            void props.appUi?.dispatchCommand("mindmap.addChild");
                          } : void 0,
                          onRequestOpenNodeContextMenu: props.appUi ? openNodeContextMenuAt : void 0,
                          hoveredId: hoveredNodeId,
                          selectedNodeIds,
                          selectedId: selection?.type === "node" ? selection.id : null,
                          resizeDraft,
                          onNodeResizeHandlePointerDown,
                          perfEnabled: perfConfig.enabled,
                          perfStatsRef: perfConfig.enabled ? perfStatsRef : null
                        }
                      ),
                      /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(
                        Summaries,
                        {
                          doc: doc3,
                          blurViewState,
                          hiddenSummaryIds,
                          visibleSummaryIds,
                          highlightId: (dropHighlight?.type === "summary" ? dropHighlight.id : null) ?? (crossPaneMapDropHighlight?.type === "summary" ? crossPaneMapDropHighlight.id : null) ?? revealHighlightSummaryId,
                          editingSummaryId: editing?.type === "summary" ? editing.id : null,
                          forceCursor: spaceDown ? "grab" : null,
                          layout: sceneLayout,
                          summaryThemeById,
                          onRequestOpenSummaryContextMenu: props.appUi ? openSummaryContextMenuAt : void 0,
                          onSummaryPointerDown,
                          selectedSummaryId: selection?.type === "summary" ? selection.id : null,
                          perfEnabled: perfConfig.enabled,
                          perfStatsRef: perfConfig.enabled ? perfStatsRef : null
                        }
                      ),
                      /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(
                        RelationControls,
                        {
                          curveDraft: relationCurveDraft,
                          doc: doc3,
                          endpointsDraft: relationEndpointsDraft,
                          excludedNodeIds: hiddenNodeIds,
                          hidden: Boolean(dragUi) || Boolean(relationLabelEditing),
                          layout: sceneLayout,
                          nodeThemeById,
                          summaryThemeById,
                          onRelationControlHandlePointerDown,
                          selectedRelationId: selection?.type === "relation" ? selection.id : null
                        }
                      ),
                      marqueeRect ? /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(
                        "rect",
                        {
                          "data-export-exclude": "true",
                          fill: "rgba(59, 130, 246, 0.08)",
                          height: marqueeRect.height,
                          pointerEvents: "none",
                          rx: 8,
                          ry: 8,
                          stroke: "rgba(59, 130, 246, 0.55)",
                          strokeWidth: 1.5,
                          vectorEffect: "non-scaling-stroke",
                          width: marqueeRect.width,
                          x: marqueeRect.x,
                          y: marqueeRect.y
                        }
                      ) : null,
                      /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(
                        DragOverlay,
                        {
                          doc: doc3,
                          drag: dragUi,
                          layout: sceneLayout,
                          nodeThemeById,
                          showDetachedHint: editorProps.interaction?.showDetachedRootHint !== false
                        }
                      ),
                      /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(
                        GhostLayer,
                        {
                          assetObjectUrlById,
                          doc: doc3,
                          embedRegistry,
                          drag: dragUi,
                          ghostDelta,
                          hiddenNodeIds,
                          hiddenSummaryIds,
                          ghostMode: dragGhostMode,
                          nodeBodyLayout,
                          layout,
                          nodeThemeById,
                          summaryThemeById,
                          containerLayoutTypeById
                        }
                      )
                    ] })
                  ]
                }
              ),
              props.appUi && linksPanel?.nodeId && linksPanelPosition ? /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(
                "div",
                {
                  "data-export-exclude": "true",
                  style: {
                    position: "absolute",
                    left: linksPanelPosition.left,
                    top: linksPanelPosition.top,
                    width: linksPanelPosition.width,
                    maxHeight: linksPanelPosition.maxHeight,
                    overflow: "hidden",
                    borderRadius: 14,
                    border: "1px solid var(--km-border)",
                    background: "var(--km-panel)",
                    boxShadow: "0 18px 36px rgba(15, 23, 42, 0.18)",
                    pointerEvents: "auto",
                    zIndex: 79
                  },
                  children: /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(
                    LinksPanel,
                    {
                      variant: "embedded",
                      backlinksIndex,
                      clipboard,
                      doc: doc3,
                      documentId: props.documentId,
                      dialog,
                      dispatchCommand: props.appUi.dispatchCommand,
                      isCommandEnabled: props.appUi.isCommandEnabled ?? (() => true),
                      premiumCapabilities,
                      onPremiumFeatureBlocked,
                      external: props.external,
                      maxHeight: 0,
                      mode: linksPanel.mode,
                      onRequestModeChange: (mode) => {
                        focusCanvas();
                        selectSingleNode(linksPanel.nodeId);
                        openLinksPanel(linksPanel.nodeId, mode);
                      },
                      readOnly,
                      nodeRefResolveStore: props.nodeRefResolveStore,
                      nodeId: linksPanel.nodeId,
                      onClose: closeLinksPanel,
                      onHoverChange: onLinksPanelHoverChange,
                      onOpenNodeRef: props.onOpenNodeRef,
                      onSelectNode: (targetId) => {
                        focusCanvas();
                        selectNodeAndReveal(targetId);
                        closeLinksPanel();
                      },
                      resolveNodeRefExists: props.resolveNodeRefExists,
                      resolveNodeRefTitle: props.resolveNodeRefTitle,
                      width: 0,
                      x: 0,
                      y: 0
                    }
                  )
                }
              ) : null,
              props.appUi && metaPopover && metaPopoverPosition ? /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(
                "div",
                {
                  "data-export-exclude": "true",
                  style: {
                    position: "absolute",
                    left: metaPopoverPosition.left,
                    top: metaPopoverPosition.top,
                    width: metaPopoverPosition.width,
                    maxHeight: metaPopoverPosition.maxHeight,
                    overflow: "hidden",
                    borderRadius: 14,
                    border: "1px solid var(--km-border)",
                    background: "var(--km-panel)",
                    boxShadow: "0 18px 36px rgba(15, 23, 42, 0.18)",
                    pointerEvents: "auto",
                    zIndex: 79
                  },
                  children: /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(
                    NodeMetaPopover,
                    {
                      variant: "embedded",
                      assetObjectUrlById,
                      commitRef: metaPopoverCommitRef,
                      core: props.core,
                      dialog,
                      doc: doc3,
                      kind: metaPopover.kind,
                      maxHeight: metaPopoverPosition.maxHeight,
                      mode: metaPopover.mode,
                      nodeId: metaPopover.nodeId,
                      onAction: props.onNodeAction,
                      onHoverChange: onMetaPopoverHoverChange,
                      onRequestClose: closeMetaPopover,
                      onRequestModeChange: (mode) => {
                        focusCanvas();
                        selectSingleNode(metaPopover.nodeId);
                        openMetaPopover({ kind: metaPopover.kind, nodeId: metaPopover.nodeId, mode });
                      },
                      premiumCapabilities,
                      onPremiumFeatureBlocked,
                      readOnly,
                      width: 0,
                      x: 0,
                      y: 0
                    }
                  )
                }
              ) : null,
              props.appUi && selection?.type === "node" && !editing && !relationLabelEditing && linksPanel?.mode !== "edit" && metaPopover?.mode !== "edit" ? /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(
                SelectionToolbarOverlay,
                {
                  assetObjectUrlById,
                  backlinksIndex,
                  clipboard,
                  core: props.core,
                  doc: doc3,
                  dialog,
                  documentId: props.documentId,
                  dispatchCommand: props.appUi.dispatchCommand,
                  external: props.external,
                  hiddenNodeIds,
                  isCommandEnabled: props.appUi.isCommandEnabled ?? (() => true),
                  isRoot: doc3.roots.includes(selection.id),
                  activationAnchor: (() => {
                    const layoutRect = sceneLayout.nodes[selection.id];
                    if (!layoutRect) return null;
                    const pad2 = 10;
                    const layoutType = containerLayoutTypeById[selection.id] ?? "logical-right";
                    const anchor = (() => {
                      if (layoutType === "tree-up") {
                        return { x: layoutRect.x + layoutRect.width / 2, y: layoutRect.y - pad2 };
                      }
                      if (layoutType === "tree-down" || layoutType === "timeline-down" || layoutType === "mindmap-both" || layoutType === "mindmap-both-auto") {
                        return { x: layoutRect.x + layoutRect.width / 2, y: layoutRect.y + layoutRect.height + pad2 };
                      }
                      if (layoutType === "logical-left" || layoutType === "fishbone-right") {
                        return { x: layoutRect.x - pad2, y: layoutRect.y + layoutRect.height / 2 };
                      }
                      return { x: layoutRect.x + layoutRect.width + pad2, y: layoutRect.y + layoutRect.height / 2 };
                    })();
                    return {
                      x: (anchor.x - viewBox.x) * (viewportSize.width / Math.max(viewBox.width, 1)),
                      y: (anchor.y - viewBox.y) * (viewportSize.height / Math.max(viewBox.height, 1))
                    };
                  })(),
                  nodeRefResolveStore: props.nodeRefResolveStore,
                  onNodeAction: props.onNodeAction,
                  onOpenLinksPanel: ({ nodeId, mode }) => {
                    focusCanvas();
                    selectSingleNode(nodeId);
                    openLinksPanel(nodeId, mode);
                  },
                  onOpenMetaPopover: ({ kind, nodeId, mode }) => {
                    focusCanvas();
                    selectSingleNode(nodeId);
                    openMetaPopover({ kind, nodeId, mode });
                  },
                  onOpenNodeRef: props.onOpenNodeRef,
                  onSelectNode: (nodeId) => {
                    focusCanvas();
                    selectNodeAndReveal(nodeId);
                  },
                  pendingRelationFromId,
                  layout: sceneLayout,
                  nodeId: selection.id,
                  nodeRect: (() => {
                    const rect = sceneLayout.nodes[selection.id];
                    return rect ? worldRectToViewportRect({ rect, viewBox, viewport: viewportSize }) : { x: 0, y: 0, width: 0, height: 0 };
                  })(),
                  onRequestOpenNodeContextMenu: openNodeContextMenuAt,
                  actionRequest: selectionToolbarActionRequest,
                  onActionRequestHandled: onSelectionToolbarActionRequestHandled,
                  onPopoverRequestHandled: onSelectionToolbarPopoverRequestHandled,
                  onPremiumFeatureBlocked,
                  onSetHighlightNodeId: setSelectionToolbarHighlightNodeId,
                  popoverRequest: selectionToolbarPopoverRequest,
                  quickActions: selectionQuickActions,
                  resolveNodeRefExists: props.resolveNodeRefExists,
                  resolveNodeRefTitle: props.resolveNodeRefTitle,
                  selectionToolbar: props.appUi.selectionToolbar,
                  snapshot: props.appUi.snapshot,
                  svgRef,
                  themeCatalog: props.appUi.themeCatalog,
                  viewBox,
                  viewport: viewportSize,
                  visible: true,
                  controlsHidden: Boolean(dragUi) || isPanning,
                  contextMenuOpen: Boolean(contextMenu)
                }
              ) : null,
              props.appUi ? /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(
                ContextMenuOverlay,
                {
                  containerRef: canvasRef,
                  contributions: props.appUi.contextMenus,
                  keymapOverrides: props.appUi.keymapOverrides,
                  dispatchCommand: props.appUi.dispatchCommand,
                  isCommandEnabled: props.appUi.isCommandEnabled ?? (() => true),
                  nodeRects: sceneLayout.nodes,
                  quickActions: contextMenuQuickActions,
                  onQuickActionPointerDown: (actionId, pointer) => {
                    if (contextMenu?.scope !== "summary") return;
                    if (actionId !== "selection.relation.start") return;
                    setSummaryRelationPickerCursor({ x: pointer.clientX, y: pointer.clientY });
                  },
                  onQuickActionRequest: (actionId) => {
                    if (selection?.type !== "node" || !requestSelectionToolbarAction) return;
                    requestSelectionToolbarAction({ actionId, nodeId: selection.id, presentation: "popover-only" });
                  },
                  onPremiumFeatureBlocked,
                  onRequestClose: () => {
                    closeContextMenu();
                    focusCanvas();
                  },
                  snapshot: props.appUi.snapshot,
                  state: contextMenu,
                  viewBox,
                  viewportSize
                }
              ) : null,
              props.appUi ? /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(
                ViewModeHintOverlay,
                {
                  dispatchCommand: props.appUi.dispatchCommand,
                  documentStatus: props.appUi.snapshot.documents.status,
                  projectId: props.appUi.snapshot.navigation.rootId,
                  viewModes: props.appUi.snapshot.editor.viewModes
                }
              ) : null,
              !props.appUi && linksPanel?.nodeId && linksPanelPosition ? /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(
                LinksPanel,
                {
                  backlinksIndex,
                  clipboard,
                  doc: doc3,
                  documentId: props.documentId,
                  dialog,
                  dispatchCommand: void 0,
                  isCommandEnabled: () => false,
                  premiumCapabilities,
                  onPremiumFeatureBlocked,
                  external: props.external,
                  maxHeight: linksPanelPosition.maxHeight,
                  mode: linksPanel.mode,
                  readOnly: false,
                  nodeRefResolveStore: props.nodeRefResolveStore,
                  nodeId: linksPanel.nodeId,
                  onClose: closeLinksPanel,
                  onOpenNodeRef: props.onOpenNodeRef,
                  onHoverChange: onLinksPanelHoverChange,
                  onRequestModeChange: onRequestLinksPanelModeChange,
                  onSelectNode: (targetId) => {
                    focusCanvas();
                    selectNodeAndReveal(targetId);
                    closeLinksPanel();
                  },
                  resolveNodeRefExists: props.resolveNodeRefExists,
                  resolveNodeRefTitle: props.resolveNodeRefTitle,
                  width: linksPanelPosition.width,
                  x: linksPanelPosition.left,
                  y: linksPanelPosition.top
                }
              ) : null,
              !props.appUi && metaPopover && metaPopoverPosition ? /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(
                NodeMetaPopover,
                {
                  assetObjectUrlById,
                  commitRef: metaPopoverCommitRef,
                  core: props.core,
                  dialog,
                  doc: doc3,
                  kind: metaPopover.kind,
                  maxHeight: metaPopoverPosition.maxHeight,
                  mode: metaPopover.mode,
                  readOnly: false,
                  nodeId: metaPopover.nodeId,
                  onAction: props.onNodeAction,
                  onHoverChange: onMetaPopoverHoverChange,
                  onRequestClose: closeMetaPopover,
                  onRequestModeChange: onRequestMetaPopoverModeChange,
                  premiumCapabilities,
                  onPremiumFeatureBlocked,
                  width: metaPopoverPosition.width,
                  x: metaPopoverPosition.left,
                  y: metaPopoverPosition.top
                }
              ) : null,
              relationLabelEditing ? /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(
                RelationLabelEditorOverlay,
                {
                  anchor: relationLabelEditing.anchor,
                  initialValue: relationLabelEditing.initialValue,
                  onCancel: cancelRelationLabelEditing,
                  onCommit: commitRelationLabelEditing,
                  viewBox,
                  viewportSize
                },
                relationLabelEditing.relationId
              ) : null,
              selection?.type === "relation" && !editing && !relationLabelEditing && !dragUi ? /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(
                RelationQuickEditBubble,
                {
                  core: props.core,
                  dialog,
                  doc: doc3,
                  layout: sceneLayout,
                  nodeThemeById,
                  relationId: selection.id,
                  summaryThemeById,
                  viewBox,
                  viewportSize
                },
                selection.id
              ) : null,
              pendingRelationFromId?.kind === "summary" && summaryRelationPickerCursor ? /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(
                CursorIconBadge,
                {
                  cursor: summaryRelationPickerCursor,
                  iconId: "kmind-icon://builtin/ui/relation",
                  label: t("editor.selectionToolbar.cursor.relation")
                }
              ) : null,
              exportFullActive ? /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(
                "div",
                {
                  style: {
                    position: "absolute",
                    left: -1e5,
                    top: -1e5,
                    width: 1,
                    height: 1,
                    overflow: "hidden",
                    pointerEvents: "none"
                  },
                  children: /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)(
                    "svg",
                    {
                      ref: exportFullSvgRef,
                      style: { display: "block", background: canvasBackground, ...themeVars },
                      viewBox: `${viewBox.x} ${viewBox.y} ${viewBox.width} ${viewBox.height}`,
                      xmlns: "http://www.w3.org/2000/svg",
                      children: [
                        /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)("defs", { children: [
                          /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)("linearGradient", { id: `km-ai-rainbow-${exportFullBuiltinIconSymbolPrefix}`, x1: "0", x2: "1", y1: "0", y2: "1", children: [
                            /* @__PURE__ */ (0, import_jsx_runtime35.jsx)("stop", { offset: "0%", stopColor: "#f43f5e" }),
                            /* @__PURE__ */ (0, import_jsx_runtime35.jsx)("stop", { offset: "16%", stopColor: "#f97316" }),
                            /* @__PURE__ */ (0, import_jsx_runtime35.jsx)("stop", { offset: "32%", stopColor: "#facc15" }),
                            /* @__PURE__ */ (0, import_jsx_runtime35.jsx)("stop", { offset: "48%", stopColor: "#22c55e" }),
                            /* @__PURE__ */ (0, import_jsx_runtime35.jsx)("stop", { offset: "64%", stopColor: "#38bdf8" }),
                            /* @__PURE__ */ (0, import_jsx_runtime35.jsx)("stop", { offset: "80%", stopColor: "#6366f1" }),
                            /* @__PURE__ */ (0, import_jsx_runtime35.jsx)("stop", { offset: "100%", stopColor: "#a855f7" })
                          ] }),
                          /* @__PURE__ */ (0, import_jsx_runtime35.jsx)("style", { children: `
                    @keyframes kmind-ai-cowrite-dash {
                      from { stroke-dashoffset: 0; }
                      to { stroke-dashoffset: -48; }
                    }
                    .kmind-ai-cowrite-dash-anim {
                      animation: kmind-ai-cowrite-dash 900ms linear infinite;
                    }
                  ` }),
                          /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(BuiltinUiIconSymbols, { prefix: exportFullBuiltinIconSymbolPrefix })
                        ] }),
                        /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)("g", { children: [
                          /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(
                            Edges,
                            {
                              containerLayoutTypeById,
                              hiddenNodeIds: null,
                              hiddenSummaryIds: null,
                              layout,
                              viewportCullRect: null,
                              visibleNodeIds: null,
                              visibleSummaryIds: null,
                              nodeThemeById,
                              perfEnabled: false,
                              perfStatsRef: null
                            }
                          ),
                          /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(
                            Relations,
                            {
                              doc: doc3,
                              excludedNodeIds: null,
                              visibleNodeIds: null,
                              visibleSummaryIds: null,
                              layout,
                              nodeThemeById,
                              summaryThemeById,
                              markerIdPrefix: `km-relation-arrow-${exportFullBuiltinIconSymbolPrefix}`,
                              curveDraft: null,
                              endpointsDraft: null,
                              onRelationSelect: () => {
                              },
                              onRelationLabelDoubleClick: (_args) => {
                              },
                              selectedRelationId: null,
                              perfEnabled: false,
                              perfStatsRef: null
                            }
                          ),
                          /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(
                            SummaryBrackets,
                            {
                              doc: doc3,
                              hiddenSummaryIds: null,
                              visibleSummaryIds: null,
                              highlightId: null,
                              layout,
                              summaryThemeById
                            }
                          ),
                          /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(
                            Nodes,
                            {
                              assetObjectUrlById,
                              assetObjectUrlVersion,
                              builtinIconSymbolPrefix: exportFullBuiltinIconSymbolPrefix,
                              backlinksIndex,
                              doc: doc3,
                              external: editorProps.external,
                              layoutTypeById: containerLayoutTypeById,
                              blurViewState,
                              nodeBodyLayout,
                              nodeHtmlCache: perfConfig.nodeHtmlCache,
                              optimizeEmbedMounting: perfConfig.optimizeEmbedMounting,
                              progressByNodeId,
                              embedRegistry,
                              hiddenNodeIds: null,
                              visibleNodeIds: null,
                              highlightId: null,
                              editing: null,
                              forceCursor: null,
                              layout,
                              nodeThemeById,
                              onOpenLinksPanel: () => {
                              },
                              onNodeDoubleClick: () => {
                              },
                              onNodePointerDown: () => {
                              },
                              onNodePointerMove: () => {
                              },
                              onNodeHoverChange: () => {
                              },
                              submap: void 0,
                              onToggleNodeCollapsed: () => {
                              },
                              hoveredId: null,
                              selectedNodeIds: emptySelectedNodeIds,
                              selectedId: null,
                              resizeDraft: null,
                              onNodeResizeHandlePointerDown: () => {
                              },
                              perfEnabled: false,
                              perfStatsRef: null
                            }
                          ),
                          /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(
                            Summaries,
                            {
                              doc: doc3,
                              blurViewState,
                              hiddenSummaryIds: null,
                              visibleSummaryIds: null,
                              highlightId: null,
                              editingSummaryId: null,
                              forceCursor: null,
                              layout,
                              summaryThemeById,
                              onSummaryPointerDown: () => {
                              },
                              selectedSummaryId: null,
                              perfEnabled: false,
                              perfStatsRef: null
                            }
                          )
                        ] })
                      ]
                    }
                  )
                }
              ) : null,
              exportExpandedEnabled ? /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(
                "div",
                {
                  style: {
                    position: "absolute",
                    left: -1e5,
                    top: -1e5,
                    width: 1,
                    height: 1,
                    overflow: "hidden",
                    pointerEvents: "none"
                  },
                  children: /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)(
                    "svg",
                    {
                      ref: exportExpandedSvgRef,
                      style: { display: "block", background: canvasBackground, ...themeVars },
                      viewBox: `${viewBox.x} ${viewBox.y} ${viewBox.width} ${viewBox.height}`,
                      xmlns: "http://www.w3.org/2000/svg",
                      children: [
                        /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)("defs", { children: [
                          /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)("linearGradient", { id: `km-ai-rainbow-${exportExpandedBuiltinIconSymbolPrefix}`, x1: "0", x2: "1", y1: "0", y2: "1", children: [
                            /* @__PURE__ */ (0, import_jsx_runtime35.jsx)("stop", { offset: "0%", stopColor: "#f43f5e" }),
                            /* @__PURE__ */ (0, import_jsx_runtime35.jsx)("stop", { offset: "16%", stopColor: "#f97316" }),
                            /* @__PURE__ */ (0, import_jsx_runtime35.jsx)("stop", { offset: "32%", stopColor: "#facc15" }),
                            /* @__PURE__ */ (0, import_jsx_runtime35.jsx)("stop", { offset: "48%", stopColor: "#22c55e" }),
                            /* @__PURE__ */ (0, import_jsx_runtime35.jsx)("stop", { offset: "64%", stopColor: "#38bdf8" }),
                            /* @__PURE__ */ (0, import_jsx_runtime35.jsx)("stop", { offset: "80%", stopColor: "#6366f1" }),
                            /* @__PURE__ */ (0, import_jsx_runtime35.jsx)("stop", { offset: "100%", stopColor: "#a855f7" })
                          ] }),
                          /* @__PURE__ */ (0, import_jsx_runtime35.jsx)("style", { children: `
                    @keyframes kmind-ai-cowrite-dash {
                      from { stroke-dashoffset: 0; }
                      to { stroke-dashoffset: -48; }
                    }
                    .kmind-ai-cowrite-dash-anim {
                      animation: kmind-ai-cowrite-dash 900ms linear infinite;
                    }
                  ` }),
                          /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(BuiltinUiIconSymbols, { prefix: exportExpandedBuiltinIconSymbolPrefix })
                        ] }),
                        /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)("g", { children: [
                          /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(
                            Edges,
                            {
                              containerLayoutTypeById: exportExpandedContainerLayoutTypeById,
                              hiddenNodeIds: null,
                              hiddenSummaryIds: null,
                              layout: exportExpandedLayout,
                              viewportCullRect: null,
                              visibleNodeIds: null,
                              visibleSummaryIds: null,
                              nodeThemeById,
                              perfEnabled: false,
                              perfStatsRef: null
                            }
                          ),
                          /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(
                            Relations,
                            {
                              doc: exportExpandedDoc,
                              excludedNodeIds: null,
                              visibleNodeIds: null,
                              visibleSummaryIds: null,
                              layout: exportExpandedLayout,
                              nodeThemeById,
                              summaryThemeById,
                              markerIdPrefix: `km-relation-arrow-${exportExpandedBuiltinIconSymbolPrefix}`,
                              curveDraft: null,
                              endpointsDraft: null,
                              onRelationSelect: () => {
                              },
                              onRelationLabelDoubleClick: (_args) => {
                              },
                              selectedRelationId: null,
                              perfEnabled: false,
                              perfStatsRef: null
                            }
                          ),
                          /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(
                            SummaryBrackets,
                            {
                              doc: exportExpandedDoc,
                              hiddenSummaryIds: null,
                              visibleSummaryIds: null,
                              highlightId: null,
                              layout: exportExpandedLayout,
                              summaryThemeById
                            }
                          ),
                          /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(
                            Nodes,
                            {
                              assetObjectUrlById,
                              assetObjectUrlVersion,
                              builtinIconSymbolPrefix: exportExpandedBuiltinIconSymbolPrefix,
                              backlinksIndex,
                              doc: exportExpandedDoc,
                              external: editorProps.external,
                              layoutTypeById: exportExpandedContainerLayoutTypeById,
                              blurViewState,
                              nodeBodyLayout,
                              nodeHtmlCache: perfConfig.nodeHtmlCache,
                              optimizeEmbedMounting: perfConfig.optimizeEmbedMounting,
                              progressByNodeId,
                              embedRegistry,
                              hiddenNodeIds: null,
                              visibleNodeIds: null,
                              highlightId: null,
                              editing: null,
                              forceCursor: null,
                              layout: exportExpandedLayout,
                              nodeThemeById,
                              onOpenLinksPanel: () => {
                              },
                              onNodeDoubleClick: () => {
                              },
                              onNodePointerDown: () => {
                              },
                              onNodePointerMove: () => {
                              },
                              onNodeHoverChange: () => {
                              },
                              submap: void 0,
                              onToggleNodeCollapsed: () => {
                              },
                              hoveredId: null,
                              selectedNodeIds: emptySelectedNodeIds,
                              selectedId: null,
                              resizeDraft: null,
                              onNodeResizeHandlePointerDown: () => {
                              },
                              perfEnabled: false,
                              perfStatsRef: null
                            }
                          ),
                          /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(
                            Summaries,
                            {
                              doc: exportExpandedDoc,
                              blurViewState,
                              hiddenSummaryIds: null,
                              visibleSummaryIds: null,
                              highlightId: null,
                              editingSummaryId: null,
                              forceCursor: null,
                              layout: exportExpandedLayout,
                              summaryThemeById,
                              onSummaryPointerDown: () => {
                              },
                              selectedSummaryId: null,
                              perfEnabled: false,
                              perfStatsRef: null
                            }
                          )
                        ] })
                      ]
                    }
                  )
                }
              ) : null,
              subtreeExportNodeId && subtreeExportDoc && subtreeExportLayout && subtreeExportContainerLayoutTypeById ? /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(
                "div",
                {
                  style: {
                    position: "absolute",
                    left: -1e5,
                    top: -1e5,
                    width: 1,
                    height: 1,
                    overflow: "hidden",
                    pointerEvents: "none"
                  },
                  children: /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)(
                    "svg",
                    {
                      ref: subtreeExportSvgRef,
                      style: { display: "block", background: canvasBackground, ...themeVars },
                      viewBox: `${viewBox.x} ${viewBox.y} ${viewBox.width} ${viewBox.height}`,
                      xmlns: "http://www.w3.org/2000/svg",
                      children: [
                        /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)("defs", { children: [
                          /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)("linearGradient", { id: `km-ai-rainbow-${subtreeExportBuiltinIconSymbolPrefix}`, x1: "0", x2: "1", y1: "0", y2: "1", children: [
                            /* @__PURE__ */ (0, import_jsx_runtime35.jsx)("stop", { offset: "0%", stopColor: "#f43f5e" }),
                            /* @__PURE__ */ (0, import_jsx_runtime35.jsx)("stop", { offset: "16%", stopColor: "#f97316" }),
                            /* @__PURE__ */ (0, import_jsx_runtime35.jsx)("stop", { offset: "32%", stopColor: "#facc15" }),
                            /* @__PURE__ */ (0, import_jsx_runtime35.jsx)("stop", { offset: "48%", stopColor: "#22c55e" }),
                            /* @__PURE__ */ (0, import_jsx_runtime35.jsx)("stop", { offset: "64%", stopColor: "#38bdf8" }),
                            /* @__PURE__ */ (0, import_jsx_runtime35.jsx)("stop", { offset: "80%", stopColor: "#6366f1" }),
                            /* @__PURE__ */ (0, import_jsx_runtime35.jsx)("stop", { offset: "100%", stopColor: "#a855f7" })
                          ] }),
                          /* @__PURE__ */ (0, import_jsx_runtime35.jsx)("style", { children: `
                    @keyframes kmind-ai-cowrite-dash {
                      from { stroke-dashoffset: 0; }
                      to { stroke-dashoffset: -48; }
                    }
                    .kmind-ai-cowrite-dash-anim {
                      animation: kmind-ai-cowrite-dash 900ms linear infinite;
                    }
                  ` }),
                          /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(BuiltinUiIconSymbols, { prefix: subtreeExportBuiltinIconSymbolPrefix })
                        ] }),
                        /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)("g", { children: [
                          /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(
                            Edges,
                            {
                              containerLayoutTypeById: subtreeExportContainerLayoutTypeById,
                              hiddenNodeIds: null,
                              hiddenSummaryIds: null,
                              layout: subtreeExportLayout,
                              viewportCullRect: null,
                              visibleNodeIds: null,
                              visibleSummaryIds: null,
                              nodeThemeById,
                              perfEnabled: false,
                              perfStatsRef: null
                            }
                          ),
                          /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(
                            Relations,
                            {
                              doc: subtreeExportDoc,
                              excludedNodeIds: null,
                              visibleNodeIds: null,
                              visibleSummaryIds: null,
                              layout: subtreeExportLayout,
                              nodeThemeById,
                              summaryThemeById,
                              markerIdPrefix: `km-relation-arrow-${subtreeExportBuiltinIconSymbolPrefix}`,
                              curveDraft: null,
                              endpointsDraft: null,
                              onRelationSelect: () => {
                              },
                              onRelationLabelDoubleClick: (_args) => {
                              },
                              selectedRelationId: null,
                              perfEnabled: false,
                              perfStatsRef: null
                            }
                          ),
                          /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(
                            SummaryBrackets,
                            {
                              doc: subtreeExportDoc,
                              hiddenSummaryIds: null,
                              visibleSummaryIds: null,
                              highlightId: null,
                              layout: subtreeExportLayout,
                              summaryThemeById
                            }
                          ),
                          /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(
                            Nodes,
                            {
                              assetObjectUrlById,
                              assetObjectUrlVersion,
                              builtinIconSymbolPrefix: subtreeExportBuiltinIconSymbolPrefix,
                              backlinksIndex,
                              doc: subtreeExportDoc,
                              external: editorProps.external,
                              layoutTypeById: subtreeExportContainerLayoutTypeById,
                              blurViewState,
                              nodeBodyLayout,
                              nodeHtmlCache: perfConfig.nodeHtmlCache,
                              optimizeEmbedMounting: perfConfig.optimizeEmbedMounting,
                              progressByNodeId,
                              embedRegistry,
                              hiddenNodeIds: null,
                              visibleNodeIds: null,
                              highlightId: null,
                              editing: null,
                              forceCursor: null,
                              layout: subtreeExportLayout,
                              nodeThemeById,
                              onOpenLinksPanel: () => {
                              },
                              onNodeDoubleClick: () => {
                              },
                              onNodePointerDown: () => {
                              },
                              onNodePointerMove: () => {
                              },
                              onNodeHoverChange: () => {
                              },
                              submap: void 0,
                              onToggleNodeCollapsed: () => {
                              },
                              hoveredId: null,
                              selectedNodeIds: emptySelectedNodeIds,
                              selectedId: null,
                              resizeDraft: null,
                              onNodeResizeHandlePointerDown: () => {
                              },
                              perfEnabled: false,
                              perfStatsRef: null
                            }
                          ),
                          /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(
                            Summaries,
                            {
                              doc: subtreeExportDoc,
                              blurViewState,
                              hiddenSummaryIds: null,
                              visibleSummaryIds: null,
                              highlightId: null,
                              editingSummaryId: null,
                              forceCursor: null,
                              layout: subtreeExportLayout,
                              summaryThemeById,
                              onSummaryPointerDown: () => {
                              },
                              selectedSummaryId: null,
                              perfEnabled: false,
                              perfStatsRef: null
                            }
                          )
                        ] })
                      ]
                    }
                  )
                }
              ) : null,
              editing?.type === "node" && editingLayout ? textEditor === "plain" ? /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(
                NodePlainTextEditorOverlay,
                {
                  bounds: (() => {
                    const rect = worldRectToViewportRect({ rect: editingLayout, viewBox, viewport: viewportSize });
                    return { left: rect.x, top: rect.y, width: rect.width, height: rect.height };
                  })(),
                  canvasRef,
                  dialog,
                  core: editorProps.core,
                  kind: "node",
                  entityId: editing.id,
                  initialText: doc3.nodes[editing.id]?.text ?? "",
                  requestSoftKeyboard: editorProps.requestSoftKeyboard,
                  onCancel: stopEdit,
                  onCommit: stopEdit
                },
                editing.id
              ) : /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(
                NodeRichTextEditorOverlay,
                {
                  bounds: (() => {
                    const rect = worldRectToViewportRect({ rect: editingLayout, viewBox, viewport: viewportSize });
                    return { left: rect.x, top: rect.y, width: rect.width, height: rect.height };
                  })(),
                  canvasRef,
                  dialog,
                  slashMenuProviders: editorProps.richTextSlashMenuProviders,
                  editorRef: richTextEditorRef,
                  premiumCapabilities,
                  onPremiumFeatureBlocked,
                  accessoryContext: "node",
                  entityId: editing.id,
                  entity: doc3.nodes[editing.id],
                  theme: nodeThemeById[editing.id] ?? null,
                  nodeBodyLayout,
                  requestSoftKeyboard: editorProps.requestSoftKeyboard,
                  zoom: viewportSize.width > 0 && viewBox.width > 0 ? viewportSize.width / viewBox.width : 1,
                  maxWidth: doc3.nodes[editing.id] ? resolveNodeContentWidth(doc3.nodes[editing.id]).width : defaultMaxWidth,
                  buildMeasureHtml: ({ content, plainText }) => buildNodeMeasureHtml(doc3, editing.id, { content, text: plainText }, { nodeBodyLayout }),
                  tabEnterBehavior: editTabEnterBehavior,
                  layoutMode: editingLayoutMode,
                  measurer: measurerRef.current?.measure ?? null,
                  onCancel: stopEdit,
                  onRequestAddChild: addChild,
                  onRequestAddSibling: addSibling,
                  ...editingLayoutMode === "live-preview" ? { onDraftSizeChange: (size) => setEditingDraftSize({ nodeId: editing.id, size }) } : {},
                  onCommit: onCommitNodeRichText
                },
                editing.id
              ) : null,
              editing?.type === "summary" && editingLayout ? textEditor === "plain" ? /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(
                NodePlainTextEditorOverlay,
                {
                  bounds: (() => {
                    const rect = worldRectToViewportRect({ rect: editingLayout, viewBox, viewport: viewportSize });
                    return { left: rect.x, top: rect.y, width: rect.width, height: rect.height };
                  })(),
                  canvasRef,
                  dialog,
                  core: editorProps.core,
                  kind: "summary",
                  entityId: editing.id,
                  initialText: doc3.summaries.find((item) => item.id === editing.id)?.text ?? "",
                  requestSoftKeyboard: editorProps.requestSoftKeyboard,
                  onCancel: stopEdit,
                  onCommit: stopEdit
                },
                editing.id
              ) : /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(
                NodeRichTextEditorOverlay,
                {
                  bounds: (() => {
                    const rect = worldRectToViewportRect({ rect: editingLayout, viewBox, viewport: viewportSize });
                    return { left: rect.x, top: rect.y, width: rect.width, height: rect.height };
                  })(),
                  canvasRef,
                  dialog,
                  slashMenuProviders: editorProps.richTextSlashMenuProviders,
                  editorRef: richTextEditorRef,
                  premiumCapabilities,
                  onPremiumFeatureBlocked,
                  accessoryContext: "summary",
                  entityId: editing.id,
                  entity: doc3.summaries.find((item) => item.id === editing.id),
                  theme: summaryThemeById[editing.id] ?? null,
                  requestSoftKeyboard: editorProps.requestSoftKeyboard,
                  zoom: viewportSize.width > 0 && viewBox.width > 0 ? viewportSize.width / viewBox.width : 1,
                  maxWidth: doc3.summaries.find((item) => item.id === editing.id)?.maxWidth ?? defaultMaxWidth,
                  buildMeasureHtml: ({ content, plainText }) => buildSummaryMeasureHtmlFromContent(doc3, editing.id, { content, text: plainText }),
                  tabEnterBehavior: "exit",
                  layoutMode: editingLayoutMode,
                  measurer: measurerRef.current?.measure ?? null,
                  onCancel: stopEdit,
                  onRequestAddChild: () => {
                  },
                  onRequestAddSibling: () => {
                  },
                  onCommit: onCommitSummaryRichText
                },
                editing.id
              ) : null
            ] })
          }
        ),
        isCanvasOnly ? null : /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)(import_jsx_runtime35.Fragment, { children: [
          /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)("div", { style: { fontSize: 12, color: "var(--km-muted)" }, children: [
            "\u63D0\u793A\uFF1A\u53CC\u51FB\u8282\u70B9/\u6982\u8981\u53EF\u7F16\u8F91\uFF1B\u7F16\u8F91\u6846\u5931\u7126\u4F1A\u81EA\u52A8\u63D0\u4EA4\uFF1B",
            editTabEnterBehavior === "create-next" ? "\u7F16\u8F91\u6001\uFF1ATab=\u63D0\u4EA4\u5E76\u521B\u5EFA\u5B50\u8282\u70B9\uFF1BEnter=\u63D0\u4EA4\u5E76\u521B\u5EFA\u5144\u5F1F\u8282\u70B9\uFF1BShift+Enter \u6362\u884C\uFF1BEsc \u9000\u51FA\u3002" : "\u7F16\u8F91\u6001\uFF1AEnter/Tab \u63D0\u4EA4\u9000\u51FA\uFF1BShift+Enter \u6362\u884C\uFF1BEsc \u53D6\u6D88\u3002"
          ] }),
          /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(
            NodeInspectorPanel,
            {
              backlinksIndex,
              core: props.core,
              dialog,
              doc: doc3,
              selection,
              onSelectNode: selectSingleNode,
              setBlurViewState
            }
          )
        ] })
      ]
    }
  );
}

// ../react/src/mindmap-editor/hooks/use-editor-model.ts
var import_react45 = __toESM(require_react(), 1);
init_src();

// ../react/src/selection-navigation.ts
function buildSummaryById2(doc3) {
  return new Map(doc3.summaries.map((summary) => [summary.id, summary]));
}
function resolveNodeContainer(doc3, summaryById, nodeId) {
  const node = doc3.nodes[nodeId];
  if (!node) return null;
  if (!node.parentId && !node.parentSummaryId) {
    return { type: "root", ids: doc3.roots.filter((id) => Boolean(doc3.nodes[id])) };
  }
  if (node.parentId) {
    const parent = doc3.nodes[node.parentId];
    if (!parent) return null;
    return { type: "node", parentId: node.parentId, ids: parent.children.filter((id) => Boolean(doc3.nodes[id])) };
  }
  if (node.parentSummaryId) {
    const summary = summaryById.get(node.parentSummaryId);
    if (!summary) return null;
    return { type: "summary", summaryId: summary.id, ids: summary.children.filter((id) => Boolean(doc3.nodes[id])) };
  }
  return null;
}
function resolveParentNodeId(doc3, nodeId) {
  const node = doc3.nodes[nodeId];
  if (!node) return null;
  if (node.parentId) return node.parentId;
  if (!node.parentSummaryId) return null;
  const summaryById = buildSummaryById2(doc3);
  let cursor = node.parentSummaryId;
  const visited = /* @__PURE__ */ new Set();
  while (cursor) {
    if (visited.has(cursor)) break;
    visited.add(cursor);
    const summary = summaryById.get(cursor);
    if (!summary) break;
    const parentId = summary.parentId;
    if (doc3.nodes[parentId]) return parentId;
    const parentSummary = summaryById.get(parentId);
    if (parentSummary) {
      cursor = parentSummary.id;
      continue;
    }
    break;
  }
  return null;
}
function resolveNearestDeletedAncestor(doc3, anchorId, deletedNodeIds) {
  const visited = /* @__PURE__ */ new Set();
  let cursor = anchorId;
  while (true) {
    if (deletedNodeIds.has(cursor)) return cursor;
    const parent = resolveParentNodeId(doc3, cursor);
    if (!parent) return cursor;
    if (visited.has(parent)) return cursor;
    visited.add(parent);
    cursor = parent;
  }
}
function createDeletedSubtreeMatcher(doc3, deletedNodeIds) {
  const memo2 = /* @__PURE__ */ new Map();
  const matches2 = (nodeId) => {
    if (deletedNodeIds.has(nodeId)) return true;
    const cached = memo2.get(nodeId);
    if (cached !== void 0) return cached;
    const visited = /* @__PURE__ */ new Set();
    let cursor = nodeId;
    while (cursor) {
      if (deletedNodeIds.has(cursor)) {
        memo2.set(nodeId, true);
        return true;
      }
      const parent = resolveParentNodeId(doc3, cursor);
      if (!parent || visited.has(parent)) break;
      visited.add(parent);
      cursor = parent;
    }
    memo2.set(nodeId, false);
    return false;
  };
  return matches2;
}
function resolveFirstRemainingRoot(doc3, belongsToDeletedSubtree) {
  for (const rootId of doc3.roots) {
    if (!doc3.nodes[rootId]) continue;
    if (belongsToDeletedSubtree(rootId)) continue;
    return rootId;
  }
  return null;
}
function rectCenter(rect) {
  return { x: rect.x + rect.width / 2, y: rect.y + rect.height / 2 };
}
function resolveOverlap(startA, endA, startB, endB) {
  return Math.max(0, Math.min(endA, endB) - Math.max(startA, startB));
}
function resolveDirectionalMetrics(fromRect, toRect, direction) {
  const fromCenter = rectCenter(fromRect);
  const toCenter = rectCenter(toRect);
  if (direction === "left") {
    const primary2 = fromCenter.x - toCenter.x;
    if (primary2 <= 0) return null;
    return {
      primary: primary2,
      secondary: Math.abs(fromCenter.y - toCenter.y),
      edgeGap: Math.max(0, fromRect.x - (toRect.x + toRect.width)),
      crossOverlap: resolveOverlap(fromRect.y, fromRect.y + fromRect.height, toRect.y, toRect.y + toRect.height)
    };
  }
  if (direction === "right") {
    const primary2 = toCenter.x - fromCenter.x;
    if (primary2 <= 0) return null;
    return {
      primary: primary2,
      secondary: Math.abs(fromCenter.y - toCenter.y),
      edgeGap: Math.max(0, toRect.x - (fromRect.x + fromRect.width)),
      crossOverlap: resolveOverlap(fromRect.y, fromRect.y + fromRect.height, toRect.y, toRect.y + toRect.height)
    };
  }
  if (direction === "up") {
    const primary2 = fromCenter.y - toCenter.y;
    if (primary2 <= 0) return null;
    return {
      primary: primary2,
      secondary: Math.abs(fromCenter.x - toCenter.x),
      edgeGap: Math.max(0, fromRect.y - (toRect.y + toRect.height)),
      crossOverlap: resolveOverlap(fromRect.x, fromRect.x + fromRect.width, toRect.x, toRect.x + toRect.width)
    };
  }
  const primary = toCenter.y - fromCenter.y;
  if (primary <= 0) return null;
  return {
    primary,
    secondary: Math.abs(fromCenter.x - toCenter.x),
    edgeGap: Math.max(0, toRect.y - (fromRect.y + fromRect.height)),
    crossOverlap: resolveOverlap(fromRect.x, fromRect.x + fromRect.width, toRect.x, toRect.x + toRect.width)
  };
}
function resolveDirectionalCandidate(args) {
  const { doc: doc3, layout, fromNodeId, direction, exclude } = args;
  const fromRect = layout.nodes[fromNodeId];
  if (!fromRect) return null;
  const allCandidates = [];
  const alignedCandidates = [];
  let order = 0;
  for (const [rawNodeId, toRect] of Object.entries(layout.nodes)) {
    const nodeId = rawNodeId;
    if (nodeId === fromNodeId) continue;
    if (!doc3.nodes[nodeId]) continue;
    if (exclude?.(nodeId)) continue;
    const metrics = resolveDirectionalMetrics(fromRect, toRect, direction);
    if (!metrics) continue;
    const candidate = {
      nodeId,
      order,
      ...metrics
    };
    order += 1;
    allCandidates.push(candidate);
    if (metrics.crossOverlap > 0) alignedCandidates.push(candidate);
  }
  const pool = alignedCandidates.length > 0 ? alignedCandidates : allCandidates;
  if (pool.length === 0) return null;
  let best = null;
  for (const candidate of pool) {
    const score = candidate.secondary * 8 + candidate.edgeGap * 4 + candidate.primary - Math.min(candidate.crossOverlap, 120) * 0.2;
    if (!best || score < best.score - 1e-3) {
      best = { ...candidate, score };
      continue;
    }
    if (Math.abs(score - best.score) <= 1e-3) {
      if (candidate.secondary < best.secondary - 1e-3) {
        best = { ...candidate, score };
        continue;
      }
      if (Math.abs(candidate.secondary - best.secondary) <= 1e-3 && candidate.primary < best.primary - 1e-3) {
        best = { ...candidate, score };
        continue;
      }
      if (Math.abs(candidate.secondary - best.secondary) <= 1e-3 && Math.abs(candidate.primary - best.primary) <= 1e-3 && candidate.order < best.order) {
        best = { ...candidate, score };
      }
    }
  }
  return best?.nodeId ?? null;
}
function resolveRectDistanceScore(fromRect, toRect) {
  const dx = Math.max(0, fromRect.x - (toRect.x + toRect.width), toRect.x - (fromRect.x + fromRect.width));
  const dy = Math.max(0, fromRect.y - (toRect.y + toRect.height), toRect.y - (fromRect.y + fromRect.height));
  const fromCenter = rectCenter(fromRect);
  const toCenter = rectCenter(toRect);
  const centerDistance = Math.hypot(fromCenter.x - toCenter.x, fromCenter.y - toCenter.y);
  return Math.hypot(dx, dy) * 10 + centerDistance;
}
function resolveNearestNodeByGeometry(args) {
  const { doc: doc3, layout, fromRect, exclude } = args;
  let bestNodeId = null;
  let bestScore = Number.POSITIVE_INFINITY;
  let order = 0;
  let bestOrder = Number.POSITIVE_INFINITY;
  for (const [rawNodeId, rect] of Object.entries(layout.nodes)) {
    const nodeId = rawNodeId;
    if (!doc3.nodes[nodeId]) continue;
    if (exclude(nodeId)) continue;
    const score = resolveRectDistanceScore(fromRect, rect);
    if (score < bestScore - 1e-3) {
      bestScore = score;
      bestNodeId = nodeId;
      bestOrder = order;
      order += 1;
      continue;
    }
    if (Math.abs(score - bestScore) <= 1e-3 && order < bestOrder) {
      bestNodeId = nodeId;
      bestOrder = order;
    }
    order += 1;
  }
  return bestNodeId;
}
function resolveCollapsedOutwardDirections(args) {
  const { doc: doc3, nodeId, containerLayoutTypeById } = args;
  const node = doc3.nodes[nodeId];
  const directions = /* @__PURE__ */ new Set();
  if (!node || node.children.length === 0) return directions;
  const layoutType = containerLayoutTypeById?.[nodeId] ?? node.layout ?? "logical-right";
  if (layoutType === "logical-left" || layoutType === "fishbone-right") {
    directions.add("left");
    return directions;
  }
  if (layoutType === "tree-up") {
    directions.add("up");
    return directions;
  }
  if (layoutType === "tree-down" || layoutType === "timeline-down") {
    directions.add("down");
    return directions;
  }
  if (layoutType === "mindmap-both" || layoutType === "mindmap-both-auto") {
    for (const childId of node.children) {
      const child = doc3.nodes[childId];
      if (!child) continue;
      if (child.branchSide === "left") directions.add("left");
      if (child.branchSide === "right") directions.add("right");
      const resolvedChildLayout = containerLayoutTypeById?.[childId];
      if (resolvedChildLayout === "logical-left" || resolvedChildLayout === "fishbone-right") directions.add("left");
      if (resolvedChildLayout === "logical-right" || resolvedChildLayout === "timeline-right" || resolvedChildLayout === "fishbone-left") {
        directions.add("right");
      }
    }
    if (directions.size === 0) {
      directions.add("left");
      directions.add("right");
    }
    return directions;
  }
  directions.add("right");
  return directions;
}
function resolveNextNodeSelectionAfterDelete(args) {
  const { doc: doc3, layout, anchorId, deletedNodeIds } = args;
  const summaryById = buildSummaryById2(doc3);
  const belongsToDeletedSubtree = createDeletedSubtreeMatcher(doc3, deletedNodeIds);
  const anchorRoot = resolveNearestDeletedAncestor(doc3, anchorId, deletedNodeIds);
  const container = resolveNodeContainer(doc3, summaryById, anchorRoot);
  const containerIds = container?.ids ?? doc3.roots.filter((id) => Boolean(doc3.nodes[id]));
  const anchorIndex = containerIds.indexOf(anchorRoot);
  if (anchorIndex >= 0) {
    for (let i = anchorIndex - 1; i >= 0; i -= 1) {
      const candidate = containerIds[i];
      if (!candidate) continue;
      if (belongsToDeletedSubtree(candidate)) continue;
      if (!doc3.nodes[candidate]) continue;
      return candidate;
    }
    for (let i = anchorIndex + 1; i < containerIds.length; i += 1) {
      const candidate = containerIds[i];
      if (!candidate) continue;
      if (belongsToDeletedSubtree(candidate)) continue;
      if (!doc3.nodes[candidate]) continue;
      return candidate;
    }
  }
  const anchorRect = layout?.nodes[anchorId] ?? layout?.nodes[anchorRoot] ?? null;
  if (layout && anchorRect) {
    const geometryCandidate = resolveNearestNodeByGeometry({
      doc: doc3,
      layout,
      fromRect: anchorRect,
      exclude: belongsToDeletedSubtree
    });
    if (geometryCandidate) return geometryCandidate;
  }
  const parentId = resolveParentNodeId(doc3, anchorRoot);
  if (parentId && doc3.nodes[parentId] && !belongsToDeletedSubtree(parentId)) return parentId;
  return resolveFirstRemainingRoot(doc3, belongsToDeletedSubtree);
}
function resolveArrowNavigation(args) {
  const { doc: doc3, layout, fromNodeId, direction, containerLayoutTypeById } = args;
  const node = doc3.nodes[fromNodeId];
  if (!node || !layout) return null;
  const collapsed = Boolean(doc3.viewState?.collapsedNodeIds?.[fromNodeId]);
  if (collapsed && node.children.length > 0) {
    const outwardDirections = resolveCollapsedOutwardDirections({ doc: doc3, nodeId: fromNodeId, containerLayoutTypeById });
    if (outwardDirections.has(direction)) {
      return { type: "toggleCollapse", nodeId: fromNodeId };
    }
  }
  const nextNodeId = resolveDirectionalCandidate({
    doc: doc3,
    layout,
    fromNodeId,
    direction
  });
  if (!nextNodeId) return null;
  return { type: "select", nodeId: nextNodeId };
}

// ../react/src/shortcuts.ts
var priorityOrder = [
  "cancelPendingRelation",
  "undo",
  "redo",
  "startEdit",
  "addChild",
  "addSibling",
  "deleteSelection"
];
function createDefaultShortcutKeymap(platform) {
  const mod = platform === "mac" ? { meta: true, ctrl: false } : { ctrl: true, meta: false };
  const modShift = { ...mod, shift: true };
  return {
    undo: [{ key: "z", ...mod, shift: false, alt: false }],
    redo: [
      { key: "z", ...modShift, alt: false },
      { key: "y", ...mod, shift: false, alt: false }
    ],
    addChild: [{ key: "Tab", code: "Tab", alt: false, ctrl: false, meta: false, shift: false }],
    addSibling: [{ key: "Enter", code: "Enter", alt: false, ctrl: false, meta: false, shift: false }],
    deleteSelection: [
      { key: "Backspace", code: "Backspace", alt: false, ctrl: false, meta: false, shift: false },
      { key: "Delete", code: "Delete", alt: false, ctrl: false, meta: false, shift: false }
    ],
    startEdit: [{ key: "F2", code: "F2", alt: false, ctrl: false, meta: false, shift: false }],
    cancelPendingRelation: [{ key: "Escape", code: "Escape", alt: false, ctrl: false, meta: false, shift: false }]
  };
}
function mergeShortcutKeymaps(base2, override) {
  if (!override) return base2;
  const next = { ...base2 };
  for (const [action, combos] of Object.entries(override)) {
    next[action] = combos;
  }
  return next;
}
function resolveShortcutAction(event, context, keymap2) {
  if (context.editing) return null;
  if (context.dragging || context.panning) return null;
  const selection = context.selection;
  for (const action of priorityOrder) {
    if (action === "cancelPendingRelation" && !context.hasPendingRelation) continue;
    if (action === "addChild" && selection !== "node" && selection !== "summary") continue;
    if (action === "addSibling" && selection !== "node") continue;
    if (action === "deleteSelection" && selection === "none") continue;
    if (action === "startEdit" && selection !== "node" && selection !== "summary") continue;
    const combos = keymap2[action];
    if (!combos || combos.length === 0) continue;
    if (combos.some((combo) => matchesCombo(event, combo))) return action;
  }
  return null;
}
function isTypingTarget(target2) {
  if (!target2 || typeof target2 !== "object") return false;
  const element = target2;
  const tagName = typeof element.tagName === "string" ? element.tagName.toUpperCase() : "";
  if (tagName === "INPUT" || tagName === "TEXTAREA" || tagName === "SELECT") return true;
  return Boolean(element.isContentEditable);
}
function matchesCombo(event, combo) {
  const expectedAlt = combo.alt ?? false;
  const expectedCtrl = combo.ctrl ?? false;
  const expectedMeta = combo.meta ?? false;
  const expectedShift = combo.shift ?? false;
  if (event.altKey !== expectedAlt) return false;
  if (event.ctrlKey !== expectedCtrl) return false;
  if (event.metaKey !== expectedMeta) return false;
  if (event.shiftKey !== expectedShift) return false;
  if (combo.code && event.code !== combo.code) return false;
  if (combo.key) {
    const key = String(event.key ?? "");
    if (key.toLowerCase() !== String(combo.key).toLowerCase()) return false;
  }
  return Boolean(combo.code || combo.key);
}
function detectPlatform() {
  if (typeof navigator === "undefined") return "win";
  const raw = typeof navigator.platform === "string" ? navigator.platform : "";
  return /Mac|iPhone|iPad|iPod/i.test(raw) ? "mac" : "win";
}

// ../react/src/use-mindmap-state.ts
var import_react31 = __toESM(require_react(), 1);
function useMindMapState(core) {
  return (0, import_react31.useSyncExternalStore)(
    (listener) => core.subscribe(listener),
    () => core.getState(),
    () => core.getState()
  );
}

// ../react/src/mindmap-editor/import-freemind.ts
init_src();
function parseFreeMind(xmlText) {
  if (typeof DOMParser === "undefined") {
    throw new Error("\u5F53\u524D\u73AF\u5883\u4E0D\u652F\u6301 XML \u89E3\u6790\uFF08DOMParser \u7F3A\u5931\uFF09");
  }
  const xml = new DOMParser().parseFromString(xmlText, "text/xml");
  const map2 = xml.querySelector("map");
  if (!map2) {
    throw new Error("\u65E0\u6548\u7684 FreeMind \u6587\u4EF6\uFF1A\u7F3A\u5C11 <map> \u6839\u8282\u70B9");
  }
  const rootNodes = Array.from(map2.children).filter((node) => node.tagName.toLowerCase() === "node");
  if (rootNodes.length === 0) {
    throw new Error("\u65E0\u6548\u7684 FreeMind \u6587\u4EF6\uFF1A\u7F3A\u5C11 <node> \u5185\u5BB9");
  }
  const generateId = createImportIdGenerator();
  const nodes = {};
  const roots = [];
  const walk = (element, parentId) => {
    const id = generateId();
    const text5 = element.getAttribute("TEXT") ?? element.getAttribute("text") ?? "";
    const created = { id, parentId, children: [], text: text5, maxWidth: defaultMaxWidth };
    nodes[id] = created;
    const childElements = Array.from(element.children).filter((child) => child.tagName.toLowerCase() === "node");
    for (const childEl of childElements) {
      const childId = walk(childEl, id);
      created.children.push(childId);
    }
    return id;
  };
  for (const rootEl of rootNodes) {
    roots.push(walk(rootEl));
  }
  return {
    version: "1.0.0",
    roots,
    nodes,
    summaries: [],
    relations: []
  };
}
function createImportIdGenerator() {
  return () => createKmindId("n");
}

// ../react/src/mindmap-editor/ports.ts
function createFallbackDialogPort() {
  const global = globalThis;
  return {
    async alert(message) {
      try {
        global.alert?.(message);
      } catch {
      }
    },
    async confirm(message) {
      try {
        return global.confirm ? global.confirm(message) : false;
      } catch {
        return false;
      }
    },
    async prompt(args) {
      const label = args.title ? `${args.title}

${args.message}` : args.message;
      try {
        if (!global.prompt) return null;
        const value = global.prompt(label, args.initialValue ?? "");
        return value === null ? null : value;
      } catch {
        return null;
      }
    }
  };
}
function createFallbackClipboardPort() {
  const global = globalThis;
  const clipboard = global.navigator?.clipboard;
  if (!clipboard?.readText || !clipboard?.writeText) return null;
  return {
    readText() {
      return clipboard.readText();
    },
    writeText(text5) {
      return clipboard.writeText(text5);
    }
  };
}
function createFallbackStoragePort() {
  const global = globalThis;
  const storage = global.localStorage;
  if (!storage) return null;
  return {
    getItem(key) {
      try {
        return storage.getItem(key);
      } catch {
        return null;
      }
    },
    setItem(key, value) {
      try {
        storage.setItem(key, value);
      } catch {
      }
    },
    removeItem(key) {
      try {
        storage.removeItem(key);
      } catch {
      }
    }
  };
}

// ../react/src/mindmap-editor/embeds/default-embed-registry.ts
var defaultEmbedRegistry = {
  "demo:counter": {
    trust: "trusted",
    mount: (container) => {
      let count = 0;
      const button = document.createElement("button");
      button.type = "button";
      button.style.border = "1px solid rgba(148, 163, 184, 0.55)";
      button.style.borderRadius = "10px";
      button.style.background = "rgba(255, 255, 255, 0.9)";
      button.style.padding = "8px 10px";
      button.style.cursor = "pointer";
      button.style.fontSize = "12px";
      button.style.lineHeight = "16px";
      const render3 = () => {
        button.textContent = `Counter: ${count}`;
      };
      const onClick = (event) => {
        event.preventDefault();
        event.stopPropagation();
        count += 1;
        render3();
      };
      render3();
      button.addEventListener("click", onClick);
      container.innerHTML = "";
      container.appendChild(button);
      return () => {
        button.removeEventListener("click", onClick);
        button.remove();
      };
    }
  }
};

// ../react/src/mindmap-editor/hooks/use-asset-urls.ts
var import_react32 = __toESM(require_react(), 1);
function useAssetUrls(args) {
  const cacheRef = (0, import_react32.useRef)(/* @__PURE__ */ new Map());
  const pendingRef = (0, import_react32.useRef)(/* @__PURE__ */ new Set());
  const [version2, setVersion] = (0, import_react32.useState)(0);
  const assetObjectUrlById = (0, import_react32.useMemo)(() => cacheRef.current, [version2]);
  (0, import_react32.useEffect)(() => {
    const port = args.assetUrls;
    const cache = cacheRef.current;
    const pending = pendingRef.current;
    let canceled = false;
    const revoke = (url) => {
      try {
        if (port?.revokeObjectUrl) {
          port.revokeObjectUrl(url);
          return;
        }
        URL.revokeObjectURL(url);
      } catch {
      }
    };
    if (!port) {
      for (const url of cache.values()) revoke(url);
      cache.clear();
      pending.clear();
      setVersion((v) => v + 1);
      return () => {
        canceled = true;
      };
    }
    const required = /* @__PURE__ */ new Set();
    for (const node of Object.values(args.doc.nodes)) {
      for (const id of collectReferencedAssetIdsFromContent2(node.content)) {
        const asset = args.doc.assets?.[id];
        if (!asset) continue;
        if (asset.kind !== "image" && asset.kind !== "blob") continue;
        const url = asset.dataUrl;
        if (!url.startsWith(KMIND_ASSET_URL_PREFIX2)) continue;
        const storedId = url.slice(KMIND_ASSET_URL_PREFIX2.length).trim() || id;
        required.add(storedId);
      }
    }
    for (const summary of args.doc.summaries) {
      for (const id of collectReferencedAssetIdsFromContent2(summary.content)) {
        const asset = args.doc.assets?.[id];
        if (!asset) continue;
        if (asset.kind !== "image" && asset.kind !== "blob") continue;
        const url = asset.dataUrl;
        if (!url.startsWith(KMIND_ASSET_URL_PREFIX2)) continue;
        const storedId = url.slice(KMIND_ASSET_URL_PREFIX2.length).trim() || id;
        required.add(storedId);
      }
    }
    let changed = false;
    for (const [id, url] of Array.from(cache.entries())) {
      if (required.has(id)) continue;
      cache.delete(id);
      pending.delete(id);
      revoke(url);
      changed = true;
    }
    if (changed) setVersion((v) => v + 1);
    for (const id of required) {
      if (cache.has(id) || pending.has(id)) continue;
      pending.add(id);
      port.getObjectUrl(id).then((url) => {
        pending.delete(id);
        if (canceled) {
          if (url) revoke(url);
          return;
        }
        if (!url) return;
        cache.set(id, url);
        setVersion((v) => v + 1);
      }).catch(() => {
        pending.delete(id);
      });
    }
    return () => {
      canceled = true;
    };
  }, [args.assetUrls, args.doc]);
  (0, import_react32.useEffect)(() => {
    return () => {
      const port = args.assetUrls;
      const cache = cacheRef.current;
      const pending = pendingRef.current;
      const revoke = (url) => {
        try {
          if (port?.revokeObjectUrl) {
            port.revokeObjectUrl(url);
            return;
          }
          URL.revokeObjectURL(url);
        } catch {
        }
      };
      for (const url of cache.values()) revoke(url);
      cache.clear();
      pending.clear();
    };
  }, [args.assetUrls]);
  return { assetObjectUrlById, version: version2 };
}

// ../react/src/mindmap-editor/hooks/use-blur-view-state.ts
var import_react33 = __toESM(require_react(), 1);
init_src();

// ../react/src/mindmap-editor/utils/blur-view-state.ts
function tryParseBlurSnapshot(raw) {
  if (!raw) return null;
  try {
    const parsed = JSON.parse(raw);
    if (!parsed || typeof parsed !== "object") return null;
    const snapshot = parsed;
    if (snapshot.defaultVisibility !== "hidden" && snapshot.defaultVisibility !== "revealed") return null;
    return {
      defaultVisibility: snapshot.defaultVisibility,
      nodeOverrides: snapshot.nodeOverrides,
      segmentOverrides: snapshot.segmentOverrides
    };
  } catch {
    return null;
  }
}
function isBlurSnapshotEqual(next, current) {
  if (!current) return false;
  if (current.defaultVisibility !== next.defaultVisibility) return false;
  const stringify = (value) => JSON.stringify(value ?? {});
  return stringify(current.nodeOverrides) === stringify(next.nodeOverrides) && stringify(current.segmentOverrides) === stringify(next.segmentOverrides);
}

// ../react/src/mindmap-editor/hooks/use-blur-view-state.ts
function useBlurViewState(args) {
  const [blurViewState, setBlurViewState] = (0, import_react33.useState)(
    () => createBlurViewState({ revealPersistence: "session", defaultVisibility: "hidden" })
  );
  const blurViewStateRef = (0, import_react33.useRef)(blurViewState);
  (0, import_react33.useEffect)(() => {
    blurViewStateRef.current = blurViewState;
  }, [blurViewState]);
  const blurStorageKey = (0, import_react33.useMemo)(() => `kmind:blur:${args.core.id}`, [args.core.id]);
  (0, import_react33.useEffect)(() => {
    if (blurViewState.revealPersistence === "local") {
      if (!args.storage) return;
      const snapshot = tryParseBlurSnapshot(args.storage.getItem(blurStorageKey));
      if (!snapshot) return;
      setBlurViewState((prev) => ({
        ...prev,
        defaultVisibility: snapshot.defaultVisibility,
        nodeOverrides: snapshot.nodeOverrides,
        segmentOverrides: snapshot.segmentOverrides,
        revealPersistence: "local"
      }));
      return;
    }
    if (blurViewState.revealPersistence === "document") {
      const snapshot = args.doc.viewState?.blur;
      if (!snapshot) return;
      setBlurViewState((prev) => ({
        ...prev,
        defaultVisibility: snapshot.defaultVisibility,
        nodeOverrides: snapshot.nodeOverrides,
        segmentOverrides: snapshot.segmentOverrides,
        revealPersistence: "document"
      }));
    }
  }, [blurStorageKey, blurViewState.revealPersistence, args.doc.viewState?.blur, args.storage]);
  (0, import_react33.useEffect)(() => {
    const snapshot = {
      defaultVisibility: blurViewState.defaultVisibility,
      nodeOverrides: blurViewState.nodeOverrides,
      segmentOverrides: blurViewState.segmentOverrides
    };
    if (blurViewState.revealPersistence === "local") {
      if (!args.storage) return;
      try {
        args.storage.setItem(blurStorageKey, JSON.stringify(snapshot));
      } catch {
      }
      return;
    }
    if (blurViewState.revealPersistence === "document") {
      if (!isBlurSnapshotEqual(snapshot, args.doc.viewState?.blur)) {
        args.core.dispatch({ type: "set_blur_view_state", payload: { blur: snapshot } });
      }
    }
  }, [
    blurStorageKey,
    blurViewState.defaultVisibility,
    blurViewState.nodeOverrides,
    blurViewState.revealPersistence,
    blurViewState.segmentOverrides,
    args.core,
    args.doc.viewState?.blur,
    args.storage
  ]);
  return { blurViewState, setBlurViewState, blurViewStateRef };
}

// ../react/src/mindmap-editor/hooks/use-canvas-gestures.ts
var import_react34 = __toESM(require_react(), 1);
init_src();

// ../react/src/mindmap-editor/utils/drop-intent.ts
var intentDwellMs = 60;
var intentDwellFrames = 3;
function isSameDropIntent(a2, b2) {
  if (a2.kind !== b2.kind) return false;
  if (a2.kind === "none") return true;
  if (a2.kind === "invalid") return b2.kind === "invalid" && a2.reason === b2.reason;
  if (a2.kind === "as-child") {
    return b2.kind === "as-child" && a2.target.type === b2.target.type && a2.target.id === b2.target.id && a2.branchSide === b2.branchSide;
  }
  if (a2.kind === "as-sibling") {
    if (b2.kind !== "as-sibling") return false;
    if (a2.parent.type !== b2.parent.type) return false;
    if (a2.branchSide !== b2.branchSide) return false;
    if (a2.parent.type === "root") return b2.parent.type === "root" && a2.index === b2.index;
    return b2.parent.type !== "root" && a2.parent.id === b2.parent.id && a2.index === b2.index;
  }
  return false;
}
function stabilizeIntent(session, candidateIntent, now = Date.now()) {
  if (isSameDropIntent(candidateIntent, session.stableIntent)) {
    session.pendingIntent = null;
    return session.stableIntent;
  }
  const pending = session.pendingIntent;
  if (pending && isSameDropIntent(pending.intent, candidateIntent)) {
    pending.frames += 1;
    if (now - pending.since >= intentDwellMs && pending.frames >= intentDwellFrames) {
      session.stableIntent = candidateIntent;
      session.pendingIntent = null;
    }
    return session.stableIntent;
  }
  session.pendingIntent = { intent: candidateIntent, since: now, frames: 1 };
  return session.stableIntent;
}

// ../react/src/mindmap-editor/utils/dom.ts
function setSvgViewBox(svg, viewBox) {
  if (!svg) return;
  svg.setAttribute("viewBox", formatViewBox(viewBox));
}
function clearDomSelection() {
  if (typeof window === "undefined") return;
  try {
    const selection = window.getSelection?.();
    if (!selection) return;
    if (selection.rangeCount === 0) return;
    selection.removeAllRanges();
  } catch {
  }
}

// ../react/src/mindmap-editor/utils/multi-node-drag.ts
function resolveNodeDragGroup(args) {
  const anchorRect = args.layout.nodes[args.anchorNodeId];
  if (!args.doc.nodes[args.anchorNodeId] || !anchorRect) return null;
  const useSelection = args.selectedNodeIds.size > 1 && args.selectedNodeIds.has(args.anchorNodeId);
  const rawSelected = useSelection ? Array.from(args.selectedNodeIds) : [args.anchorNodeId];
  const existingSelected = rawSelected.filter((nodeId) => Boolean(args.doc.nodes[nodeId] && args.layout.nodes[nodeId]));
  const selectedNodeIds = existingSelected.length > 0 ? existingSelected : [args.anchorNodeId];
  const selectedSet = new Set(selectedNodeIds);
  const topLevel = sortNodeIdsForDrag(args.doc, args.layout, selectedNodeIds.filter((nodeId) => !hasSelectedNodeAncestor(args.doc, nodeId, selectedSet)));
  const nodeIds = topLevel.length > 0 ? topLevel : [args.anchorNodeId];
  const initialRects = {};
  const rects = [];
  const ignoreNodeIds = /* @__PURE__ */ new Set();
  const ignoreSummaryIds = /* @__PURE__ */ new Set();
  for (const nodeId of nodeIds) {
    const rect = args.layout.nodes[nodeId];
    if (!rect) continue;
    initialRects[nodeId] = { x: rect.x, y: rect.y, width: rect.width, height: rect.height };
    rects.push(initialRects[nodeId]);
    const subtree = collectSubtreeElements(args.doc, nodeId);
    for (const id of subtree.nodeIds) ignoreNodeIds.add(id);
    for (const id of subtree.summaryIds) ignoreSummaryIds.add(id);
  }
  const bounds = computeRectBounds(rects);
  if (!bounds) return null;
  return {
    anchorNodeId: args.anchorNodeId,
    nodeIds,
    selectedNodeIds,
    initialRects,
    bounds,
    ignoreNodeIds: Array.from(ignoreNodeIds),
    ignoreSummaryIds: Array.from(ignoreSummaryIds)
  };
}
function resolveDraggedGroupBounds(group, anchorGhost) {
  const anchorRect = group.initialRects[group.anchorNodeId];
  if (!anchorRect) return group.bounds;
  const dx = anchorGhost.x - anchorRect.x;
  const dy = anchorGhost.y - anchorRect.y;
  return {
    x: group.bounds.x + dx,
    y: group.bounds.y + dy,
    width: group.bounds.width,
    height: group.bounds.height
  };
}
function sortNodeIdsForDrag(doc3, layout, nodeIds) {
  const unique = Array.from(new Set(nodeIds)).filter((nodeId) => Boolean(doc3.nodes[nodeId] && layout.nodes[nodeId]));
  return unique.sort((a2, b2) => compareNodeDragOrder(doc3, layout, a2, b2));
}
function compareNodeDragOrder(doc3, layout, a2, b2) {
  const aContainer = resolveNodeContainer2(doc3, a2);
  const bContainer = resolveNodeContainer2(doc3, b2);
  if (aContainer && bContainer && aContainer.key === bContainer.key) {
    return aContainer.index - bContainer.index || compareByLayout(layout, a2, b2);
  }
  const aRootIndex = doc3.roots.indexOf(a2);
  const bRootIndex = doc3.roots.indexOf(b2);
  if (aRootIndex >= 0 && bRootIndex >= 0) return aRootIndex - bRootIndex || compareByLayout(layout, a2, b2);
  return compareByLayout(layout, a2, b2);
}
function compareByLayout(layout, a2, b2) {
  const rectA = layout.nodes[a2];
  const rectB = layout.nodes[b2];
  if (!rectA || !rectB) return a2.localeCompare(b2);
  const centerYA = rectA.y + rectA.height / 2;
  const centerYB = rectB.y + rectB.height / 2;
  const dy = centerYA - centerYB;
  if (Math.abs(dy) > 0.5) return dy;
  const centerXA = rectA.x + rectA.width / 2;
  const centerXB = rectB.x + rectB.width / 2;
  const dx = centerXA - centerXB;
  if (Math.abs(dx) > 0.5) return dx;
  return a2.localeCompare(b2);
}
function resolveNodeContainer2(doc3, nodeId) {
  const node = doc3.nodes[nodeId];
  if (!node) return null;
  if (node.parentId) {
    const parent = doc3.nodes[node.parentId];
    return parent ? { key: `node:${parent.id}`, index: parent.children.indexOf(nodeId) } : null;
  }
  if (node.parentSummaryId) {
    const summary = doc3.summaries.find((item) => item.id === node.parentSummaryId);
    return summary ? { key: `summary:${summary.id}`, index: summary.children.indexOf(nodeId) } : null;
  }
  const rootIndex = doc3.roots.indexOf(nodeId);
  return rootIndex >= 0 ? { key: "root", index: rootIndex } : null;
}
function hasSelectedNodeAncestor(doc3, nodeId, selectedNodeIds) {
  const summaryById = /* @__PURE__ */ new Map();
  for (const summary of doc3.summaries) summaryById.set(summary.id, summary);
  let node = doc3.nodes[nodeId];
  const visited = /* @__PURE__ */ new Set();
  while (node) {
    const key = `node:${node.id}`;
    if (visited.has(key)) return false;
    visited.add(key);
    if (node.parentId) {
      if (selectedNodeIds.has(node.parentId)) return true;
      node = doc3.nodes[node.parentId];
      continue;
    }
    if (node.parentSummaryId) {
      const parentNodeId = resolveSummaryParentNodeId2(doc3, summaryById, node.parentSummaryId, visited);
      if (!parentNodeId) return false;
      if (selectedNodeIds.has(parentNodeId)) return true;
      node = doc3.nodes[parentNodeId];
      continue;
    }
    return false;
  }
  return false;
}
function resolveSummaryParentNodeId2(doc3, summaryById, summaryId, visited) {
  let summary = summaryById.get(summaryId);
  while (summary) {
    const key = `summary:${summary.id}`;
    if (visited.has(key)) return null;
    visited.add(key);
    const parentId = summary.parentId;
    if (doc3.nodes[parentId]) return parentId;
    summary = summaryById.get(parentId);
  }
  return null;
}
function computeRectBounds(rects) {
  if (rects.length === 0) return null;
  let minX = Number.POSITIVE_INFINITY;
  let minY = Number.POSITIVE_INFINITY;
  let maxX = Number.NEGATIVE_INFINITY;
  let maxY = Number.NEGATIVE_INFINITY;
  for (const rect of rects) {
    minX = Math.min(minX, rect.x);
    minY = Math.min(minY, rect.y);
    maxX = Math.max(maxX, rect.x + rect.width);
    maxY = Math.max(maxY, rect.y + rect.height);
  }
  if (!Number.isFinite(minX) || !Number.isFinite(minY) || !Number.isFinite(maxX) || !Number.isFinite(maxY)) return null;
  return { x: minX, y: minY, width: maxX - minX, height: maxY - minY };
}

// ../react/src/mindmap-editor/hooks/use-canvas-gestures.ts
var dropTailSize = 80;
var childEnterPadding = 8;
var childLeavePadding = 22;
var siblingLanePadding = 44;
var siblingLanePaddingActive = 72;
var siblingEndPadding = 44;
var siblingEndPaddingActive = 72;
function resolveRelationEndpointLayout3(layout, endpoint) {
  return endpoint.kind === "summary" ? layout.summaries[endpoint.summaryId] : layout.nodes[endpoint.nodeId];
}
function useCanvasGestures(args) {
  const docRef = (0, import_react34.useRef)(args.doc);
  (0, import_react34.useEffect)(() => {
    docRef.current = args.doc;
  }, [args.doc]);
  const baseLayoutRef = (0, import_react34.useRef)(args.layout);
  (0, import_react34.useEffect)(() => {
    baseLayoutRef.current = args.layout;
  }, [args.layout]);
  const dragSessionRef = (0, import_react34.useRef)(null);
  const [dragUi, setDragUi] = (0, import_react34.useState)(null);
  const panSessionRef = (0, import_react34.useRef)(null);
  const pinchSessionRef = (0, import_react34.useRef)(null);
  const touchPointsRef = (0, import_react34.useRef)(/* @__PURE__ */ new Map());
  const [isPanning, setIsPanning] = (0, import_react34.useState)(false);
  const marqueeSessionRef = (0, import_react34.useRef)(null);
  const [marqueeRect, setMarqueeRect] = (0, import_react34.useState)(null);
  const resizeSessionRef = (0, import_react34.useRef)(null);
  const embedResizeSessionRef = (0, import_react34.useRef)(null);
  const relationControlPointSessionRef = (0, import_react34.useRef)(null);
  const lastNodePressRef = (0, import_react34.useRef)(null);
  const lastSummaryPressRef = (0, import_react34.useRef)(null);
  const lastResizeHandlePressRef = (0, import_react34.useRef)(null);
  const lastBlankPressRef = (0, import_react34.useRef)(null);
  const isMultiSelectModifier = (event) => event.ctrlKey || event.metaKey;
  const clearTrackedTouchPoints = () => {
    touchPointsRef.current.clear();
  };
  const clearDragSession = (pointerId) => {
    const session = dragSessionRef.current;
    dragSessionRef.current = null;
    setDragUi(null);
    if (session?.rafId) {
      const caf = typeof cancelAnimationFrame === "function" ? cancelAnimationFrame : clearTimeout;
      caf(session.rafId);
    }
    const svg = args.svgRef.current;
    if (!svg) return;
    try {
      svg.releasePointerCapture(pointerId);
    } catch {
    }
  };
  const clearPanSession = (pointerId) => {
    const session = panSessionRef.current;
    panSessionRef.current = null;
    setIsPanning(false);
    args.setCameraVersion((version2) => version2 + 1);
    if (session?.rafId) {
      const caf = typeof cancelAnimationFrame === "function" ? cancelAnimationFrame : clearTimeout;
      caf(session.rafId);
    }
    const svg = args.svgRef.current;
    if (!svg) return;
    try {
      svg.releasePointerCapture(pointerId);
    } catch {
    }
  };
  const clearPinchSession = () => {
    const session = pinchSessionRef.current;
    pinchSessionRef.current = null;
    setIsPanning(false);
    args.setCameraVersion((version2) => version2 + 1);
    if (session?.rafId) {
      const caf = typeof cancelAnimationFrame === "function" ? cancelAnimationFrame : clearTimeout;
      caf(session.rafId);
    }
    const svg = args.svgRef.current;
    if (!svg || !session) return;
    for (const pointerId of session.pointerIds) {
      try {
        svg.releasePointerCapture(pointerId);
      } catch {
      }
    }
  };
  const clearMarqueeSession = (pointerId) => {
    const session = marqueeSessionRef.current;
    marqueeSessionRef.current = null;
    setMarqueeRect(null);
    if (session?.rafId) {
      const caf = typeof cancelAnimationFrame === "function" ? cancelAnimationFrame : clearTimeout;
      caf(session.rafId);
    }
    const svg = args.svgRef.current;
    if (!svg) return;
    try {
      svg.releasePointerCapture(pointerId);
    } catch {
    }
  };
  const clearResizeSession = (pointerId) => {
    const session = resizeSessionRef.current;
    resizeSessionRef.current = null;
    args.setResizeDraft((prev) => prev ? null : prev);
    if (session?.rafId) {
      const caf = typeof cancelAnimationFrame === "function" ? cancelAnimationFrame : clearTimeout;
      caf(session.rafId);
    }
    const svg = args.svgRef.current;
    if (!svg) return;
    try {
      svg.releasePointerCapture(pointerId);
    } catch {
    }
  };
  const clearEmbedResizeSession = (pointerId, options) => {
    const session = embedResizeSessionRef.current;
    embedResizeSessionRef.current = null;
    args.setEmbedResizeDraft((prev) => prev ? null : prev);
    if (session?.rafId) {
      const caf = typeof cancelAnimationFrame === "function" ? cancelAnimationFrame : clearTimeout;
      caf(session.rafId);
    }
    if (options?.revert && session?.wrapEl) {
      try {
        session.wrapEl.style.width = `${session.startWidth}px`;
        session.wrapEl.style.height = `${session.startHeight}px`;
      } catch {
      }
    }
    const svg = args.svgRef.current;
    if (!svg) return;
    try {
      svg.releasePointerCapture(pointerId);
    } catch {
    }
  };
  const clearRelationControlPointSession = (pointerId) => {
    const session = relationControlPointSessionRef.current;
    relationControlPointSessionRef.current = null;
    args.setRelationCurveDraft(null);
    args.setRelationEndpointsDraft(null);
    if (session?.rafId) {
      const caf = typeof cancelAnimationFrame === "function" ? cancelAnimationFrame : clearTimeout;
      caf(session.rafId);
    }
    const svg = args.svgRef.current;
    if (!svg) return;
    try {
      svg.releasePointerCapture(pointerId);
    } catch {
    }
  };
  (0, import_react34.useEffect)(() => {
    if (!args.readOnly) return;
    clearTrackedTouchPoints();
    const drag = dragSessionRef.current;
    if (drag) clearDragSession(drag.pointerId);
    const pinch = pinchSessionRef.current;
    if (pinch) clearPinchSession();
    const marquee = marqueeSessionRef.current;
    if (marquee) clearMarqueeSession(marquee.pointerId);
    const resize = resizeSessionRef.current;
    if (resize) clearResizeSession(resize.pointerId);
    const embedResize = embedResizeSessionRef.current;
    if (embedResize) clearEmbedResizeSession(embedResize.pointerId, { revert: true });
    const rel2 = relationControlPointSessionRef.current;
    if (rel2) clearRelationControlPointSession(rel2.pointerId);
    args.setPendingRelationFromId(null);
  }, [args.readOnly]);
  (0, import_react34.useEffect)(() => {
    if (!args.isEditing) return;
    clearTrackedTouchPoints();
    const pinch = pinchSessionRef.current;
    if (pinch) clearPinchSession();
  }, [args.isEditing]);
  (0, import_react34.useEffect)(() => {
    const win = typeof window !== "undefined" ? window : null;
    if (!win) return;
    const shouldSkipForSvgHandler = (event) => {
      const svg = args.svgRef.current;
      if (!svg) return false;
      const native = event;
      const path2 = typeof native.composedPath === "function" ? native.composedPath() : [];
      return path2.includes(svg);
    };
    const cleanupTouchPointer = (event) => {
      if (event.pointerType !== "touch") return;
      if (shouldSkipForSvgHandler(event)) return;
      removeTouchPoint(event.pointerId);
      if (pinchSessionRef.current?.pointerIds.includes(event.pointerId)) {
        clearPinchSession();
      }
    };
    win.addEventListener("pointerup", cleanupTouchPointer, true);
    win.addEventListener("pointercancel", cleanupTouchPointer, true);
    return () => {
      win.removeEventListener("pointerup", cleanupTouchPointer, true);
      win.removeEventListener("pointercancel", cleanupTouchPointer, true);
    };
  }, [args.svgRef]);
  const clientToWorld = (clientX, clientY) => {
    const svg = args.svgRef.current;
    if (!svg) return null;
    const rect = svg.getBoundingClientRect();
    if (!rect.width || !rect.height) return null;
    const vb = args.viewBoxRef.current;
    const x5 = vb.x + (clientX - rect.left) / rect.width * vb.width;
    const y = vb.y + (clientY - rect.top) / rect.height * vb.height;
    return { x: x5, y };
  };
  const syncTouchPoint = (pointerId, event) => {
    touchPointsRef.current.set(pointerId, { clientX: event.clientX, clientY: event.clientY });
  };
  const removeTouchPoint = (pointerId) => {
    touchPointsRef.current.delete(pointerId);
  };
  const resolvePinchTouchPoints = (session) => {
    const points = touchPointsRef.current;
    if (session) {
      const first3 = points.get(session.pointerIds[0]);
      const second2 = points.get(session.pointerIds[1]);
      if (first3 && second2) return { first: first3, second: second2 };
    }
    const entries = Array.from(points.entries());
    if (entries.length < 2) return null;
    const [, first2] = entries[0];
    const [, second] = entries[1];
    return { first: first2, second };
  };
  const schedulePinchMove = () => {
    const session = pinchSessionRef.current;
    if (!session) return;
    if (session.rafId) return;
    const raf = typeof requestAnimationFrame === "function" ? requestAnimationFrame : (fn) => setTimeout(fn, 16);
    session.rafId = raf(() => {
      const currentSession = pinchSessionRef.current;
      if (!currentSession) return;
      currentSession.rafId = null;
      const pending = currentSession.pendingMove;
      if (!pending) return;
      currentSession.pendingMove = null;
      const svg = args.svgRef.current;
      if (!svg) return;
      const rect = svg.getBoundingClientRect();
      if (!rect.width || !rect.height) return;
      const currentDistance = Math.max(1, Math.hypot(
        pending.second.clientX - pending.first.clientX,
        pending.second.clientY - pending.first.clientY
      ));
      const nextZoom = clampCameraZoom(currentSession.startZoom * (currentDistance / currentSession.startDistance));
      const midClientX = (pending.first.clientX + pending.second.clientX) / 2;
      const midClientY = (pending.first.clientY + pending.second.clientY) / 2;
      const ratioX = (midClientX - rect.left) / rect.width;
      const ratioY = (midClientY - rect.top) / rect.height;
      if (!Number.isFinite(ratioX) || !Number.isFinite(ratioY)) return;
      const nextCamera = resolveAnchoredCamera({
        current: args.cameraRef.current,
        currentView: currentSession.startViewBox,
        viewport: { width: rect.width, height: rect.height },
        nextZoom,
        anchorRatio: { x: ratioX, y: ratioY },
        anchorWorld: currentSession.startMidWorld
      });
      args.cameraRef.current = nextCamera;
      const nextView = resolveViewBoxFromCamera(nextCamera, { width: rect.width, height: rect.height });
      args.viewBoxRef.current = nextView;
      setSvgViewBox(svg, nextView);
      if (currentSession.pendingMove) schedulePinchMove();
    });
  };
  const startPinch = () => {
    if (args.isEditing) return false;
    if (pinchSessionRef.current) return false;
    if (resizeSessionRef.current || embedResizeSessionRef.current || relationControlPointSessionRef.current) return false;
    const svg = args.svgRef.current;
    if (!svg) return false;
    const pinchPoints = resolvePinchTouchPoints();
    if (!pinchPoints) return false;
    const entries = Array.from(touchPointsRef.current.entries());
    if (entries.length < 2) return false;
    const [firstEntry, secondEntry] = entries;
    if (!firstEntry || !secondEntry) return false;
    const rect = svg.getBoundingClientRect();
    if (!rect.width || !rect.height) return false;
    const startDistance = Math.hypot(
      pinchPoints.second.clientX - pinchPoints.first.clientX,
      pinchPoints.second.clientY - pinchPoints.first.clientY
    );
    if (!Number.isFinite(startDistance) || startDistance < 8) return false;
    const midClientX = (pinchPoints.first.clientX + pinchPoints.second.clientX) / 2;
    const midClientY = (pinchPoints.first.clientY + pinchPoints.second.clientY) / 2;
    const ratioX = (midClientX - rect.left) / rect.width;
    const ratioY = (midClientY - rect.top) / rect.height;
    if (!Number.isFinite(ratioX) || !Number.isFinite(ratioY)) return false;
    const startViewBox = { ...args.viewBoxRef.current };
    const startMidWorld = {
      x: startViewBox.x + Math.max(0, Math.min(1, ratioX)) * startViewBox.width,
      y: startViewBox.y + Math.max(0, Math.min(1, ratioY)) * startViewBox.height
    };
    const drag = dragSessionRef.current;
    if (drag) clearDragSession(drag.pointerId);
    const pan = panSessionRef.current;
    if (pan) clearPanSession(pan.pointerId);
    const marquee = marqueeSessionRef.current;
    if (marquee) clearMarqueeSession(marquee.pointerId);
    pinchSessionRef.current = {
      pointerIds: [firstEntry[0], secondEntry[0]],
      startDistance,
      startZoom: args.cameraRef.current.zoom,
      startViewBox,
      startMidWorld,
      pendingMove: pinchPoints,
      rafId: null
    };
    setIsPanning(true);
    clearDomSelection();
    for (const pointerId of pinchSessionRef.current.pointerIds) {
      try {
        svg.setPointerCapture(pointerId);
      } catch {
      }
    }
    schedulePinchMove();
    return true;
  };
  const startPan = (event, options) => {
    if (event.button !== 0) return;
    if (args.isEditing) return;
    args.focusCanvas();
    const gesture = args.spaceGestureRef.current;
    if (args.spaceDownRef.current && gesture) gesture.consumed = true;
    const svg = args.svgRef.current;
    if (!svg) return;
    clearDragSession(event.pointerId);
    const rect = svg.getBoundingClientRect();
    const view = args.viewBoxRef.current;
    const scaleX = rect.width ? view.width / rect.width : 1;
    const scaleY = rect.height ? view.height / rect.height : 1;
    panSessionRef.current = {
      pointerId: event.pointerId,
      startClientX: event.clientX,
      startClientY: event.clientY,
      startViewBoxX: view.x,
      startViewBoxY: view.y,
      scaleX,
      scaleY,
      clearSelectionOnClick: Boolean(options?.clearSelectionOnClick),
      pendingMove: null,
      rafId: null
    };
    setIsPanning(true);
    try {
      svg.setPointerCapture(event.pointerId);
    } catch {
    }
  };
  const schedulePanMove = () => {
    const session = panSessionRef.current;
    if (!session) return;
    if (session.rafId) return;
    const raf = typeof requestAnimationFrame === "function" ? requestAnimationFrame : (fn) => setTimeout(fn, 16);
    session.rafId = raf(() => {
      const s = panSessionRef.current;
      if (!s) return;
      s.rafId = null;
      const pending = s.pendingMove;
      if (!pending) return;
      s.pendingMove = null;
      const dx = pending.clientX - s.startClientX;
      const dy = pending.clientY - s.startClientY;
      const next = {
        ...args.viewBoxRef.current,
        x: s.startViewBoxX - dx * s.scaleX,
        y: s.startViewBoxY - dy * s.scaleY
      };
      args.viewBoxRef.current = next;
      args.cameraRef.current = { ...args.cameraRef.current, x: next.x, y: next.y };
      setSvgViewBox(args.svgRef.current, next);
      if (s.pendingMove) schedulePanMove();
    });
  };
  const scheduleResizeMove = () => {
    const session = resizeSessionRef.current;
    if (!session) return;
    if (session.rafId) return;
    const raf = typeof requestAnimationFrame === "function" ? requestAnimationFrame : (fn) => setTimeout(fn, 16);
    session.rafId = raf(() => {
      const s = resizeSessionRef.current;
      if (!s) return;
      s.rafId = null;
      const pending = s.pendingMove;
      if (!pending) return;
      s.pendingMove = null;
      if (!s.isResizing) {
        const dx = pending.clientX - s.startClientX;
        if (Math.abs(dx) < 3) return;
        s.isResizing = true;
        clearDomSelection();
      }
      const world = clientToWorld(pending.clientX, pending.clientY);
      if (!world) return;
      const nextDraft = resolveResizeDraftFromWorldX(s, world.x);
      if (resizeSessionRef.current !== s) return;
      if (s.lastDraftWidth !== nextDraft.width || s.snappedToAuto !== nextDraft.snappedToAuto) {
        s.lastDraftWidth = nextDraft.width;
        s.snappedToAuto = nextDraft.snappedToAuto;
        args.setResizeDraft((prev) => {
          const prevContent = prev?.nodeId === s.nodeId ? prev.contentWidth : null;
          const nextContent = nextDraft.contentWidth;
          const sameContent = prevContent === nextContent || prevContent?.mode === nextContent?.mode && (prevContent?.mode === "auto" && nextContent?.mode === "auto" && prevContent.wrapWidth === nextContent.wrapWidth || prevContent?.mode === "fixed" && nextContent?.mode === "fixed" && prevContent.width === nextContent.width);
          if (prev && prev.nodeId === s.nodeId && sameContent) return prev;
          return { nodeId: s.nodeId, contentWidth: nextDraft.contentWidth };
        });
      }
      if (s.pendingMove) scheduleResizeMove();
    });
  };
  const scheduleEmbedResizeMove = () => {
    const session = embedResizeSessionRef.current;
    if (!session) return;
    if (session.rafId) return;
    const raf = typeof requestAnimationFrame === "function" ? requestAnimationFrame : (fn) => setTimeout(fn, 16);
    session.rafId = raf(() => {
      const s = embedResizeSessionRef.current;
      if (!s) return;
      s.rafId = null;
      const pending = s.pendingMove;
      if (!pending) return;
      s.pendingMove = null;
      if (!s.isResizing) {
        const dx = pending.clientX - s.startClientX;
        const dy = pending.clientY - s.startClientY;
        if (Math.hypot(dx, dy) < 3) return;
        s.isResizing = true;
        clearDomSelection();
      }
      const scaleX = Number.isFinite(s.scaleX) && s.scaleX > 0 ? s.scaleX : 1;
      const scaleY = Number.isFinite(s.scaleY) && s.scaleY > 0 ? s.scaleY : 1;
      const nextWidth = Math.round(Math.max(80, Math.min(2400, s.startWidth + (pending.clientX - s.startClientX) / scaleX)));
      const nextHeight = Math.round(Math.max(80, Math.min(2400, s.startHeight + (pending.clientY - s.startClientY) / scaleY)));
      if (s.wrapEl) {
        try {
          s.wrapEl.style.width = `${nextWidth}px`;
          s.wrapEl.style.height = `${nextHeight}px`;
        } catch {
        }
      }
      if (embedResizeSessionRef.current !== s) return;
      if (s.lastDraftWidth !== nextWidth || s.lastDraftHeight !== nextHeight) {
        s.lastDraftWidth = nextWidth;
        s.lastDraftHeight = nextHeight;
        args.setEmbedResizeDraft((prev) => {
          if (prev && prev.nodeId === s.nodeId && prev.blockId === s.blockId && prev.width === nextWidth && prev.height === nextHeight) return prev;
          return { nodeId: s.nodeId, blockId: s.blockId, width: nextWidth, height: nextHeight };
        });
      }
      if (s.pendingMove) scheduleEmbedResizeMove();
    });
  };
  const scheduleRelationControlPointMove = () => {
    const session = relationControlPointSessionRef.current;
    if (!session) return;
    if (session.rafId) return;
    const raf = typeof requestAnimationFrame === "function" ? requestAnimationFrame : (fn) => setTimeout(fn, 16);
    session.rafId = raf(() => {
      const s = relationControlPointSessionRef.current;
      if (!s) return;
      s.rafId = null;
      const pending = s.pendingMove;
      if (!pending) return;
      s.pendingMove = null;
      const world = clientToWorld(pending.clientX, pending.clientY);
      if (!world) return;
      const fromLayout = resolveRelationEndpointLayout3(baseLayoutRef.current, s.fromEndpoint);
      const toLayout = resolveRelationEndpointLayout3(baseLayoutRef.current, s.toEndpoint);
      if (!fromLayout || !toLayout) return;
      const anchorLayout = s.handle === "control1" ? fromLayout : toLayout;
      const anchor = resolvePortAndRatioFromRay(anchorLayout, world);
      if (!anchor) return;
      const nextFromPort = s.handle === "control1" ? anchor.port : s.baseFromPort;
      const nextFromPortRatio = s.handle === "control1" ? anchor.portRatio : s.baseFromPortRatio;
      const nextToPort = s.handle === "control2" ? anchor.port : s.baseToPort;
      const nextToPortRatio = s.handle === "control2" ? anchor.portRatio : s.baseToPortRatio;
      args.setRelationEndpointsDraft({
        relationId: s.relationId,
        fromPort: nextFromPort,
        fromPortRatio: nextFromPortRatio,
        toPort: nextToPort,
        toPortRatio: nextToPortRatio
      });
      const start = resolvePortPoint3(fromLayout, nextFromPort, nextFromPortRatio);
      const end = resolvePortPoint3(toLayout, nextToPort, nextToPortRatio);
      const nextControl1 = s.handle === "control1" ? { x: world.x - start.x, y: world.y - start.y } : s.startControl1;
      const nextControl2 = s.handle === "control2" ? { x: world.x - end.x, y: world.y - end.y } : s.startControl2;
      args.setRelationCurveDraft({
        relationId: s.relationId,
        curve: {
          schemaVersion: 1,
          kind: "cubic",
          control1: nextControl1,
          control2: nextControl2
        }
      });
      if (s.pendingMove) scheduleRelationControlPointMove();
    });
  };
  const scheduleMarqueeMove = () => {
    const session = marqueeSessionRef.current;
    if (!session) return;
    if (session.rafId) return;
    const raf = typeof requestAnimationFrame === "function" ? requestAnimationFrame : (fn) => setTimeout(fn, 16);
    session.rafId = raf(() => {
      const s = marqueeSessionRef.current;
      if (!s) return;
      s.rafId = null;
      const pending = s.pendingMove;
      if (!pending) return;
      s.pendingMove = null;
      const world = clientToWorld(pending.clientX, pending.clientY);
      if (!world) return;
      const minX = Math.min(s.startWorld.x, world.x);
      const minY = Math.min(s.startWorld.y, world.y);
      const maxX = Math.max(s.startWorld.x, world.x);
      const maxY = Math.max(s.startWorld.y, world.y);
      setMarqueeRect({
        x: minX,
        y: minY,
        width: Math.max(0, maxX - minX),
        height: Math.max(0, maxY - minY)
      });
      if (s.pendingMove) scheduleMarqueeMove();
    });
  };
  const startMarquee = (event) => {
    if (event.button !== 0) return;
    if (args.isEditing) return;
    args.focusCanvas();
    const svg = args.svgRef.current;
    if (!svg) return;
    const world = clientToWorld(event.clientX, event.clientY);
    if (!world) return;
    args.clearSelection();
    args.setHoveredNodeId(null);
    clearDomSelection();
    marqueeSessionRef.current = {
      pointerId: event.pointerId,
      startClientX: event.clientX,
      startClientY: event.clientY,
      startWorld: world,
      pendingMove: null,
      rafId: null
    };
    setMarqueeRect({ x: world.x, y: world.y, width: 0, height: 0 });
    try {
      svg.setPointerCapture(event.pointerId);
    } catch {
    }
  };
  const measureRenderedNodeMainWidth = (nodeId) => {
    const svg = args.svgRef.current;
    if (!svg) return null;
    const svgRect = svg.getBoundingClientRect();
    if (!svgRect.width) return null;
    const group = svg.querySelector(`[data-node-id="${nodeId}"]`);
    if (!group) return null;
    const mainEl = group.querySelector(".km-node-region-main");
    if (!mainEl) return null;
    const rect = mainEl.getBoundingClientRect();
    if (!rect.width) return null;
    const vb = args.viewBoxRef.current;
    const worldPerClientPx = vb.width / svgRect.width;
    return rect.width * worldPerClientPx;
  };
  const resolveResizeLayoutType = (nodeId) => {
    return args.containerLayoutTypeById?.[nodeId] ?? docRef.current.nodes[nodeId]?.layout ?? "logical-right";
  };
  const resolveResizeDraftFromWorldX = (session, worldX) => {
    return resolveNodeWidthDraftFromDrag({
      startWidth: session.startWidth,
      deltaX: worldX - session.startWorldX,
      direction: session.direction,
      autoWidth: session.autoBaselineWidth,
      restoreContentWidth: session.restoreContentWidth
    });
  };
  const resolveOriginParent = (nodeId) => {
    const node = docRef.current.nodes[nodeId];
    if (!node) return null;
    if (node.parentId) return { type: "node", id: node.parentId };
    if (node.parentSummaryId) return { type: "summary", id: node.parentSummaryId };
    return null;
  };
  const resolveGhostPosition = (session, world, altKey) => {
    const raw = { x: world.x - session.offsetX, y: world.y - session.offsetY };
    if (!session.isRoot) return raw;
    const gridSize = 20;
    const snapDistance = 6;
    if (altKey) return raw;
    const snap = (value) => Math.round(value / gridSize) * gridSize;
    const snappedX = snap(raw.x);
    const snappedY = snap(raw.y);
    const x5 = Math.abs(snappedX - raw.x) <= snapDistance ? snappedX : raw.x;
    const y = Math.abs(snappedY - raw.y) <= snapDistance ? snappedY : raw.y;
    return { x: x5, y };
  };
  const createDragGroup = (nodeId) => {
    return resolveNodeDragGroup({
      anchorNodeId: nodeId,
      doc: docRef.current,
      layout: baseLayoutRef.current,
      selectedNodeIds: args.selectedNodeIds
    });
  };
  const resolveGroupNodePosition = (session, nodeId, anchorGhost) => {
    const anchorRect = session.groupInitialRects[session.nodeId];
    const rect = session.groupInitialRects[nodeId];
    if (!anchorRect || !rect) return anchorGhost;
    return {
      x: rect.x + (anchorGhost.x - anchorRect.x),
      y: rect.y + (anchorGhost.y - anchorRect.y)
    };
  };
  const resolveNodeContainer3 = (doc3, nodeId) => {
    const node = doc3.nodes[nodeId];
    if (!node) return null;
    if (node.parentId) {
      const parent = doc3.nodes[node.parentId];
      return parent ? { key: `node:${parent.id}`, index: parent.children.indexOf(nodeId) } : null;
    }
    if (node.parentSummaryId) {
      const summary = doc3.summaries.find((item) => item.id === node.parentSummaryId);
      return summary ? { key: `summary:${summary.id}`, index: summary.children.indexOf(nodeId) } : null;
    }
    const rootIndex = doc3.roots.indexOf(nodeId);
    return rootIndex >= 0 ? { key: "root", index: rootIndex } : null;
  };
  const resolveSiblingCommandOrder = (doc3, groupNodeIds, targetKey, targetIndex) => {
    const sameContainerIndexes = groupNodeIds.map((nodeId) => resolveNodeContainer3(doc3, nodeId)).filter((container) => Boolean(container && container.key === targetKey && container.index >= 0)).map((container) => container.index);
    if (sameContainerIndexes.length === 0) return groupNodeIds;
    const firstSameContainerIndex = Math.min(...sameContainerIndexes);
    return targetIndex > firstSameContainerIndex ? [...groupNodeIds].reverse() : groupNodeIds;
  };
  const buildMoveCommandsForDrag = (input) => {
    const { detached, ghost, intent, session, stableIntent } = input;
    const doc3 = docRef.current;
    const groupNodeIds = session.groupNodeIds.length > 0 ? sortNodeIdsForDrag(doc3, baseLayoutRef.current, session.groupNodeIds) : [session.nodeId];
    if (stableIntent.kind === "as-child") {
      return groupNodeIds.map(
        (nodeId) => stableIntent.target.type === "node" ? {
          type: "move_node",
          payload: {
            nodeId,
            to: {
              type: "node",
              parentId: stableIntent.target.id,
              index: Number.MAX_SAFE_INTEGER,
              ...stableIntent.branchSide ? { branchSide: stableIntent.branchSide } : {}
            }
          }
        } : { type: "move_node", payload: { nodeId, to: { type: "summary", summaryId: stableIntent.target.id, index: Number.MAX_SAFE_INTEGER } } }
      );
    }
    if (stableIntent.kind === "as-sibling") {
      const targetKey = stableIntent.parent.type === "root" ? "root" : `${stableIntent.parent.type}:${stableIntent.parent.id}`;
      const ordered = resolveSiblingCommandOrder(doc3, groupNodeIds, targetKey, stableIntent.index);
      return ordered.map((nodeId) => {
        const orderIndex = groupNodeIds.indexOf(nodeId);
        const index = stableIntent.index + Math.max(0, orderIndex);
        if (stableIntent.parent.type === "node") {
          return {
            type: "move_node",
            payload: {
              nodeId,
              to: {
                type: "node",
                parentId: stableIntent.parent.id,
                index,
                ...stableIntent.branchSide ? { branchSide: stableIntent.branchSide } : {}
              }
            }
          };
        }
        if (stableIntent.parent.type === "summary") {
          return {
            type: "move_node",
            payload: { nodeId, to: { type: "summary", summaryId: stableIntent.parent.id, index } }
          };
        }
        return {
          type: "move_node",
          payload: { nodeId, to: { type: "root", index, position: resolveGroupNodePosition(session, nodeId, ghost) } }
        };
      });
    }
    if (session.isRoot || detached && intent.kind === "none") {
      return groupNodeIds.map((nodeId) => ({
        type: "move_node",
        payload: { nodeId, to: { type: "root", position: resolveGroupNodePosition(session, nodeId, ghost) } }
      }));
    }
    return [];
  };
  const resolveParentAnchor = (layout, originParent, layoutType) => {
    if (originParent.type === "node") {
      const parent = layout.nodes[originParent.id];
      if (!parent) return null;
      return layoutType === "tree-down" ? { x: parent.x + parent.width / 2, y: parent.y + parent.height } : { x: parent.x + parent.width, y: parent.y + parent.height / 2 };
    }
    const summary = layout.summaries[originParent.id];
    if (!summary) return null;
    return layoutType === "tree-down" ? { x: summary.x + summary.width / 2, y: summary.y + summary.height } : { x: summary.x + summary.width, y: summary.y + summary.height / 2 };
  };
  const resolveDetachState = (input) => {
    const { session, intent, ghost, layout } = input;
    const threshold = 140;
    const now = Date.now();
    if (session.isRoot) {
      session.detached = false;
      session.breakRipple = null;
      return { detached: false, breakRipple: null };
    }
    if (intent.kind !== "none") {
      session.detached = false;
      session.breakRipple = null;
      return { detached: false, breakRipple: null };
    }
    if (!session.originParent) {
      session.detached = false;
      session.breakRipple = null;
      return { detached: false, breakRipple: null };
    }
    const draggedLayout = layout.nodes[session.nodeId];
    if (!draggedLayout) return { detached: session.detached, breakRipple: null };
    const layoutType = resolveContainerLayout(docRef.current, session.originParent.id);
    const ghostAnchor = layoutType === "tree-down" ? { x: ghost.x + draggedLayout.width / 2, y: ghost.y } : { x: ghost.x, y: ghost.y + draggedLayout.height / 2 };
    const parentAnchor = resolveParentAnchor(layout, session.originParent, layoutType);
    if (!parentAnchor) return { detached: session.detached, breakRipple: null };
    const distance = Math.hypot(ghostAnchor.x - parentAnchor.x, ghostAnchor.y - parentAnchor.y);
    if (!session.detached && distance > threshold) {
      session.detached = true;
      session.breakRippleKey += 1;
      session.breakRipple = { x: parentAnchor.x, y: parentAnchor.y, key: session.breakRippleKey, expiresAt: now + 260 };
      return { detached: true, breakRipple: { x: session.breakRipple.x, y: session.breakRipple.y, key: session.breakRipple.key } };
    }
    if (session.breakRipple && session.breakRipple.expiresAt > now) {
      return { detached: session.detached, breakRipple: { x: session.breakRipple.x, y: session.breakRipple.y, key: session.breakRipple.key } };
    }
    session.breakRipple = null;
    return { detached: session.detached, breakRipple: null };
  };
  const scheduleDragMove = () => {
    const session = dragSessionRef.current;
    if (!session) return;
    if (session.rafId) return;
    const raf = typeof requestAnimationFrame === "function" ? requestAnimationFrame : (fn) => setTimeout(fn, 16);
    session.rafId = raf(() => {
      const s = dragSessionRef.current;
      if (!s) return;
      s.rafId = null;
      const pending = s.pendingMove;
      if (!pending) return;
      s.pendingMove = null;
      if (!s.isDragging) return;
      const world = clientToWorld(pending.clientX, pending.clientY);
      if (!world) return;
      const layoutForHitTest = baseLayoutRef.current;
      const ghost = resolveGhostPosition(s, world, pending.altKey);
      const draggedLayout = layoutForHitTest.nodes[s.nodeId];
      if (!draggedLayout) return;
      const draggedRect = { x: ghost.x, y: ghost.y, width: draggedLayout.width, height: draggedLayout.height };
      const ignoreNodeIds = new Set(s.subtreeNodeIds);
      const ignoreSummaryIds = new Set(s.subtreeSummaryIds);
      const candidateIntent = resolveDropIntentV2({
        doc: docRef.current,
        layout: layoutForHitTest,
        draggedNodeId: s.nodeId,
        draggedRect,
        ignoreNodeIds,
        ignoreSummaryIds,
        currentIntent: s.stableIntent,
        options: {
          tailSize: dropTailSize,
          childEnterPadding,
          childLeavePadding,
          siblingLanePadding,
          siblingLanePaddingActive,
          siblingEndPadding,
          siblingEndPaddingActive
        }
      });
      const intent = stabilizeIntent(s, candidateIntent);
      const detachmentGateIntent = candidateIntent.kind === "none" ? intent : candidateIntent;
      const { detached, breakRipple } = resolveDetachState({ session: s, intent: detachmentGateIntent, ghost, layout: layoutForHitTest });
      setDragUi({
        kind: "node",
        nodeId: s.nodeId,
        isRoot: s.isRoot,
        pointerId: s.pointerId,
        world,
        ghost,
        groupBounds: s.groupNodeIds.length > 1 ? resolveDraggedGroupBounds({ anchorNodeId: s.nodeId, bounds: s.groupBounds, initialRects: s.groupInitialRects }, ghost) : null,
        groupNodeIds: s.groupNodeIds,
        altKey: pending.altKey,
        intent,
        detached,
        originParent: s.originParent,
        subtreeNodeIds: s.subtreeNodeIds,
        subtreeSummaryIds: s.subtreeSummaryIds,
        breakRipple
      });
      if (s.pendingMove) scheduleDragMove();
    });
  };
  const onSvgPointerDownCapture = (event) => {
    if (event.button !== 0) return;
    if (args.isEditing) {
      if (event.pointerType === "touch") {
        removeTouchPoint(event.pointerId);
      }
      return;
    }
    if (event.pointerType === "touch") {
      syncTouchPoint(event.pointerId, event);
      if (touchPointsRef.current.size >= 2 && startPinch()) {
        event.preventDefault();
        event.stopPropagation();
        return;
      }
      if (pinchSessionRef.current) {
        event.preventDefault();
        event.stopPropagation();
        return;
      }
    }
    if (dragSessionRef.current || pinchSessionRef.current || panSessionRef.current || marqueeSessionRef.current || resizeSessionRef.current || embedResizeSessionRef.current || relationControlPointSessionRef.current) return;
    if (args.readOnly && isElementLike(event.target)) {
      if (event.target.closest("[data-relation-id]")) {
        event.preventDefault();
        event.stopPropagation();
        startPan(event);
        return;
      }
    }
    const target2 = event.target;
    const isInteractive = (() => {
      if (isElementLike(target2)) {
        if (target2.closest("[data-node-id],[data-summary-id],[data-relation-id]")) return true;
      }
      const native = event.nativeEvent;
      const path2 = typeof native.composedPath === "function" ? native.composedPath() : [];
      for (const item of path2) {
        if (!isElementLike(item)) continue;
        if (item.matches("[data-node-id],[data-summary-id],[data-relation-id]")) return true;
        if (item.tagName.toLowerCase() === "foreignobject") return true;
      }
      return false;
    })();
    if (!args.readOnly && !isInteractive && !args.spaceDownRef.current && isMultiSelectModifier(event)) {
      event.preventDefault();
      event.stopPropagation();
      startMarquee(event);
      return;
    }
    const shouldPan = args.spaceDownRef.current || !isInteractive;
    if (!shouldPan) return;
    event.preventDefault();
    event.stopPropagation();
    startPan(event, { clearSelectionOnClick: !isInteractive && !args.spaceDownRef.current });
  };
  const onNodeResizeHandlePointerDown = (nodeId, event) => {
    if (event.button !== 0) return;
    if (args.isEditing) return;
    if (args.isMetaPopoverEditing) return;
    if (args.readOnly) return;
    if (dragSessionRef.current || panSessionRef.current || marqueeSessionRef.current || resizeSessionRef.current || embedResizeSessionRef.current || relationControlPointSessionRef.current) return;
    const node = docRef.current.nodes[nodeId];
    if (!node) return;
    if (node.attrs?.locked || node.attrs?.readonly) return;
    const svg = args.svgRef.current;
    if (!svg) return;
    event.preventDefault();
    event.stopPropagation();
    args.focusCanvas();
    args.selectSingleNode(nodeId);
    const now = typeof performance !== "undefined" && typeof performance.now === "function" ? performance.now() : Date.now();
    const last = lastResizeHandlePressRef.current;
    const isDoublePress = event.detail >= 2 || last !== null && last.nodeId === nodeId && now - last.at <= 520;
    lastResizeHandlePressRef.current = { nodeId, at: now };
    if (isDoublePress) {
      lastResizeHandlePressRef.current = null;
      args.onNodeAction?.({
        type: "node.width.reset",
        nodeId,
        wrapWidth: resolveNodeAutoContentWidth(node).wrapWidth
      });
      return;
    }
    const world = clientToWorld(event.clientX, event.clientY);
    if (!world) return;
    const currentContentWidth = resolveNodeContentWidth(node);
    const renderedWidth = measureRenderedNodeMainWidth(nodeId);
    const startWidth = clampNodeMainWidth(renderedWidth ?? currentContentWidth.width);
    const autoBaselineWidth = currentContentWidth.mode === "auto" ? startWidth : args.autoMainWidthByNodeId?.[nodeId] ?? null;
    const layoutType = resolveResizeLayoutType(nodeId);
    const restoreContentWidth = resolveNodeAutoContentWidth(node);
    resizeSessionRef.current = {
      nodeId,
      pointerId: event.pointerId,
      startClientX: event.clientX,
      startClientY: event.clientY,
      startWorldX: world.x,
      startWidth,
      autoBaselineWidth,
      restoreContentWidth,
      direction: resolveNodeWidthResizeDirection(layoutType),
      lastDraftWidth: startWidth,
      snappedToAuto: currentContentWidth.mode === "auto",
      isResizing: false,
      pendingMove: null,
      rafId: null
    };
    try {
      svg.setPointerCapture(event.pointerId);
    } catch {
    }
  };
  const onNodePointerDown = (nodeId, event) => {
    if (event.button !== 0) return;
    if (args.isEditing) return;
    if (args.spaceDownRef.current) {
      event.preventDefault();
      event.stopPropagation();
      startPan(event);
      return;
    }
    const target2 = event.target;
    if (isElementLike(target2)) {
      if (target2.closest("[data-km-embed-host]") && !target2.closest("[data-km-embed-drag-handle]")) return;
      const linkEl = target2.closest(".km-node-richtext a[href]");
      if (linkEl) {
        const href = (linkEl.getAttribute("href") ?? "").trim();
        if (!href) return;
        if (args.external) {
          event.preventDefault();
          event.stopPropagation();
          void args.external.openUrl(href);
        }
        return;
      }
      const clozeEl = target2.closest("[data-km-cloze][data-km-cloze-id]");
      if (clozeEl) {
        const id = clozeEl.getAttribute("data-km-cloze-id") ?? "";
        const revealMode = clozeEl.getAttribute("data-km-reveal-mode") ?? "click";
        if (id && (revealMode === "click" || revealMode === "manual")) {
          event.preventDefault();
          event.stopPropagation();
          args.setBlurViewState((prev) => toggleBlurForSegment(prev, id));
          return;
        }
      }
    }
    if (isElementLike(target2)) {
      const actionEl = target2.closest("[data-km-action]");
      const action = actionEl?.getAttribute("data-km-action") ?? "";
      if (args.readOnly && action) {
        event.preventDefault();
        event.stopPropagation();
        args.focusCanvas();
        return;
      }
      if (action === "embed.resize" && actionEl) {
        if (dragSessionRef.current || panSessionRef.current || marqueeSessionRef.current || resizeSessionRef.current || embedResizeSessionRef.current || relationControlPointSessionRef.current) return;
        if (args.isMetaPopoverEditing) return;
        const node = docRef.current.nodes[nodeId];
        if (!node) return;
        if (node.attrs?.locked || node.attrs?.readonly) return;
        const blockId = (actionEl.getAttribute("data-km-embed-block-id") ?? "").trim();
        if (!blockId) return;
        if (node.content?.schemaVersion !== 1 || node.content.kind !== "blocks") return;
        const block = node.content.blocks.find((item) => item.type === "embed" && item.id === blockId);
        if (!block || block.type !== "embed") return;
        const svg2 = args.svgRef.current;
        if (!svg2) return;
        event.preventDefault();
        event.stopPropagation();
        args.focusCanvas();
        args.selectSingleNode(nodeId);
        const startWidth = Math.max(40, block.width ?? 180);
        const startHeight = Math.max(40, block.height ?? 120);
        const wrapEl = actionEl.closest(".km-node-embed-wrap") ?? (() => {
          if (!isElementLike(event.currentTarget)) return null;
          const escaped = typeof CSS !== "undefined" && typeof CSS.escape === "function" ? CSS.escape(blockId) : blockId.replaceAll('"', '\\"');
          return event.currentTarget.querySelector(`.km-node-embed-wrap[data-km-embed-block-id="${escaped}"]`);
        })();
        const rect = wrapEl?.getBoundingClientRect() ?? null;
        const scaleX = rect && rect.width > 0 && startWidth > 0 ? rect.width / startWidth : 1;
        const scaleY = rect && rect.height > 0 && startHeight > 0 ? rect.height / startHeight : 1;
        embedResizeSessionRef.current = {
          nodeId,
          blockId,
          pointerId: event.pointerId,
          startClientX: event.clientX,
          startClientY: event.clientY,
          startWidth,
          startHeight,
          scaleX,
          scaleY,
          lastDraftWidth: startWidth,
          lastDraftHeight: startHeight,
          isResizing: false,
          wrapEl,
          pendingMove: null,
          rafId: null
        };
        args.setEmbedResizeDraft({ nodeId, blockId, width: startWidth, height: startHeight });
        try {
          svg2.setPointerCapture(event.pointerId);
        } catch {
        }
        return;
      }
      if (action === "task.toggle") {
        event.preventDefault();
        event.stopPropagation();
        args.selectSingleNode(nodeId);
        args.onNodeAction?.({ type: "task.toggle", nodeId });
        return;
      }
      if (action === "notes.open") {
        event.preventDefault();
        event.stopPropagation();
        args.selectSingleNode(nodeId);
        args.openMetaPopover({ kind: "notes", nodeId, mode: "edit" });
        return;
      }
      if (action === "comments.open") {
        event.preventDefault();
        event.stopPropagation();
        args.selectSingleNode(nodeId);
        args.openMetaPopover({ kind: "comments", nodeId, mode: "edit" });
        return;
      }
      if (action === "icons.open") {
        event.preventDefault();
        event.stopPropagation();
        args.selectSingleNode(nodeId);
        const rect = actionEl ? actionEl.getBoundingClientRect() : null;
        args.requestSelectionToolbarPopover?.({
          popoverId: "builtin.icons",
          nodeId,
          anchorClientRect: rect ? { left: rect.left, top: rect.top, width: rect.width, height: rect.height } : null
        });
        return;
      }
    }
    if (args.readOnly) {
      args.focusCanvas();
      event.preventDefault();
      event.stopPropagation();
      startPan(event);
      return;
    }
    args.focusCanvas();
    event.preventDefault();
    event.stopPropagation();
    if (args.pendingRelationFromId) {
      const targetEndpoint = { kind: "node", nodeId, port: "left" };
      if (relationEndpointKey(args.pendingRelationFromId) === relationEndpointKey(targetEndpoint)) {
        args.setPendingRelationFromId(null);
        args.selectSingleNode(nodeId);
        return;
      }
      const result = args.core.dispatch({
        type: "create_relation",
        payload: {
          from: args.pendingRelationFromId,
          to: targetEndpoint
        }
      });
      if (!result.ok) {
        void args.dialog.alert(result.error);
      }
      args.setPendingRelationFromId(null);
      args.selectSingleNode(nodeId);
      return;
    }
    if (isMultiSelectModifier(event)) {
      lastNodePressRef.current = null;
      const next = new Set(args.selectedNodeIds);
      const wasSelected = next.has(nodeId);
      if (wasSelected) next.delete(nodeId);
      else next.add(nodeId);
      if (next.size === 0) {
        args.setSelectedNodeIds(next);
        args.setSelection(null);
        return;
      }
      const nextPrimary = wasSelected ? args.selection?.type === "node" && args.selection.id !== nodeId && next.has(args.selection.id) ? args.selection.id : next.values().next().value : nodeId;
      args.setSelectedNodeIds(next);
      args.setSelection({ type: "node", id: nextPrimary });
      return;
    }
    const now = typeof performance !== "undefined" && typeof performance.now === "function" ? performance.now() : Date.now();
    const last = lastNodePressRef.current;
    const isDoublePress = event.detail >= 2 || last !== null && last.nodeId === nodeId && now - last.at <= 520;
    lastNodePressRef.current = { nodeId, at: now };
    if (isDoublePress) {
      lastNodePressRef.current = null;
      args.startEditNode(nodeId);
      return;
    }
    const dragGroup = createDragGroup(nodeId);
    const preserveMultiSelection = Boolean(dragGroup && dragGroup.nodeIds.length > 1 && args.selectedNodeIds.has(nodeId));
    if (preserveMultiSelection) {
      args.setSelection({ type: "node", id: nodeId });
    } else {
      args.selectSingleNode(nodeId);
    }
    const svg = args.svgRef.current;
    if (!svg) return;
    const world = clientToWorld(event.clientX, event.clientY);
    const nodeLayout = baseLayoutRef.current.nodes[nodeId];
    if (!world || !nodeLayout || !dragGroup) return;
    const isRoot = args.doc.roots.includes(nodeId);
    dragSessionRef.current = {
      nodeId,
      isRoot,
      pointerId: event.pointerId,
      startClientX: event.clientX,
      startClientY: event.clientY,
      offsetX: world.x - nodeLayout.x,
      offsetY: world.y - nodeLayout.y,
      isDragging: false,
      subtreeNodeIds: dragGroup.ignoreNodeIds,
      subtreeSummaryIds: dragGroup.ignoreSummaryIds,
      groupNodeIds: dragGroup.nodeIds,
      groupSelectedNodeIds: dragGroup.selectedNodeIds,
      groupInitialRects: dragGroup.initialRects,
      groupBounds: dragGroup.bounds,
      originParent: isRoot ? null : resolveOriginParent(nodeId),
      detached: false,
      stableIntent: { kind: "none" },
      pendingIntent: null,
      breakRippleKey: 0,
      breakRipple: null,
      pendingMove: null,
      rafId: null
    };
    try {
      svg.setPointerCapture(event.pointerId);
    } catch {
    }
  };
  const onSummaryPointerDown = (summaryId, event) => {
    if (event.button !== 0) return;
    if (args.isEditing) return;
    if (args.spaceDownRef.current) {
      event.preventDefault();
      event.stopPropagation();
      startPan(event);
      return;
    }
    const target2 = event.target;
    if (isElementLike(target2)) {
      const linkEl = target2.closest(".km-node-richtext a[href]");
      if (linkEl) {
        const href = (linkEl.getAttribute("href") ?? "").trim();
        if (!href) return;
        if (args.external) {
          event.preventDefault();
          event.stopPropagation();
          void args.external.openUrl(href);
        }
        return;
      }
      const clozeEl = target2.closest("[data-km-cloze][data-km-cloze-id]");
      if (clozeEl) {
        const id = clozeEl.getAttribute("data-km-cloze-id") ?? "";
        const revealMode = clozeEl.getAttribute("data-km-reveal-mode") ?? "click";
        if (id && (revealMode === "click" || revealMode === "manual")) {
          event.preventDefault();
          event.stopPropagation();
          args.setBlurViewState((prev) => toggleBlurForSegment(prev, id));
          return;
        }
      }
    }
    if (args.readOnly) {
      args.focusCanvas();
      event.preventDefault();
      event.stopPropagation();
      startPan(event);
      return;
    }
    args.focusCanvas();
    event.preventDefault();
    event.stopPropagation();
    if (args.pendingRelationFromId) {
      const targetEndpoint = { kind: "summary", summaryId, port: "left" };
      if (relationEndpointKey(args.pendingRelationFromId) === relationEndpointKey(targetEndpoint)) {
        args.setPendingRelationFromId(null);
        args.selectSummary(summaryId);
        return;
      }
      const result = args.core.dispatch({
        type: "create_relation",
        payload: {
          from: args.pendingRelationFromId,
          to: targetEndpoint
        }
      });
      if (!result.ok) {
        void args.dialog.alert(result.error);
      }
      args.setPendingRelationFromId(null);
      args.selectSummary(summaryId);
      return;
    }
    const now = typeof performance !== "undefined" && typeof performance.now === "function" ? performance.now() : Date.now();
    const last = lastSummaryPressRef.current;
    const isDoublePress = event.detail >= 2 || last !== null && last.summaryId === summaryId && now - last.at <= 520;
    lastSummaryPressRef.current = { summaryId, at: now };
    if (isDoublePress) {
      lastSummaryPressRef.current = null;
      args.startEditSummary(summaryId);
      return;
    }
    args.selectSummary(summaryId);
  };
  const onSvgPointerMove = (event) => {
    if (event.pointerType === "touch") {
      syncTouchPoint(event.pointerId, event);
    }
    const pinch = pinchSessionRef.current;
    if (pinch && pinch.pointerIds.includes(event.pointerId)) {
      event.preventDefault();
      event.stopPropagation();
      const pinchPoints = resolvePinchTouchPoints(pinch);
      if (!pinchPoints) return;
      pinch.pendingMove = pinchPoints;
      schedulePinchMove();
      return;
    }
    const relControl = relationControlPointSessionRef.current;
    if (relControl && relControl.pointerId === event.pointerId) {
      event.preventDefault();
      event.stopPropagation();
      relControl.pendingMove = { clientX: event.clientX, clientY: event.clientY };
      scheduleRelationControlPointMove();
      return;
    }
    const resize = resizeSessionRef.current;
    if (resize && resize.pointerId === event.pointerId) {
      event.preventDefault();
      event.stopPropagation();
      resize.pendingMove = { clientX: event.clientX, clientY: event.clientY };
      scheduleResizeMove();
      return;
    }
    const embedResize = embedResizeSessionRef.current;
    if (embedResize && embedResize.pointerId === event.pointerId) {
      event.preventDefault();
      event.stopPropagation();
      embedResize.pendingMove = { clientX: event.clientX, clientY: event.clientY };
      scheduleEmbedResizeMove();
      return;
    }
    const marquee = marqueeSessionRef.current;
    if (marquee && marquee.pointerId === event.pointerId) {
      event.preventDefault();
      event.stopPropagation();
      marquee.pendingMove = { clientX: event.clientX, clientY: event.clientY };
      scheduleMarqueeMove();
      return;
    }
    const pan = panSessionRef.current;
    if (pan && pan.pointerId === event.pointerId) {
      event.preventDefault();
      pan.pendingMove = { clientX: event.clientX, clientY: event.clientY };
      schedulePanMove();
      return;
    }
    const session = dragSessionRef.current;
    if (!session) return;
    if (session.pointerId !== event.pointerId) return;
    if (!session.isDragging) {
      const distance = Math.hypot(event.clientX - session.startClientX, event.clientY - session.startClientY);
      if (distance < 6) return;
      session.isDragging = true;
      lastNodePressRef.current = null;
      clearDomSelection();
      args.crossPaneDrag?.onMapNodeDragStart?.({
        nodeId: session.nodeId,
        pointerId: session.pointerId,
        clientX: event.clientX,
        clientY: event.clientY
      });
    }
    event.preventDefault();
    session.pendingMove = { clientX: event.clientX, clientY: event.clientY, altKey: event.altKey };
    args.crossPaneDrag?.onMapNodeDragMove?.({
      nodeId: session.nodeId,
      pointerId: session.pointerId,
      clientX: event.clientX,
      clientY: event.clientY
    });
    scheduleDragMove();
  };
  const onSvgPointerCancel = (event) => {
    if (event.pointerType === "touch") {
      removeTouchPoint(event.pointerId);
    }
    const pinch = pinchSessionRef.current;
    if (pinch && pinch.pointerIds.includes(event.pointerId)) {
      clearPinchSession();
      clearDomSelection();
      return;
    }
    const relControl = relationControlPointSessionRef.current;
    if (relControl && relControl.pointerId === event.pointerId) {
      clearRelationControlPointSession(event.pointerId);
      clearDomSelection();
      return;
    }
    const resize = resizeSessionRef.current;
    if (resize && resize.pointerId === event.pointerId) {
      clearResizeSession(event.pointerId);
      clearDomSelection();
      return;
    }
    const embedResize = embedResizeSessionRef.current;
    if (embedResize && embedResize.pointerId === event.pointerId) {
      clearEmbedResizeSession(event.pointerId, { revert: true });
      clearDomSelection();
      return;
    }
    const marquee = marqueeSessionRef.current;
    if (marquee && marquee.pointerId === event.pointerId) {
      clearMarqueeSession(event.pointerId);
      clearDomSelection();
      return;
    }
    const pan = panSessionRef.current;
    if (pan && pan.pointerId === event.pointerId) {
      const distance = Math.hypot(event.clientX - pan.startClientX, event.clientY - pan.startClientY);
      const shouldClearSelection = pan.clearSelectionOnClick && distance < 4;
      clearPanSession(event.pointerId);
      clearDomSelection();
      if (shouldClearSelection) {
        args.setPendingRelationFromId(null);
        args.stopEdit();
        args.clearSelection();
      }
      return;
    }
    const session = dragSessionRef.current;
    if (!session) return;
    if (session.pointerId !== event.pointerId) return;
    args.crossPaneDrag?.onMapNodeDragCancel?.({ nodeId: session.nodeId, pointerId: session.pointerId });
    clearDragSession(event.pointerId);
    clearDomSelection();
  };
  const onSvgPointerUp = (event) => {
    if (event.pointerType === "touch") {
      removeTouchPoint(event.pointerId);
    }
    const pinch = pinchSessionRef.current;
    if (pinch && pinch.pointerIds.includes(event.pointerId)) {
      event.preventDefault();
      event.stopPropagation();
      clearPinchSession();
      clearDomSelection();
      return;
    }
    const relControl = relationControlPointSessionRef.current;
    if (relControl && relControl.pointerId === event.pointerId) {
      event.preventDefault();
      event.stopPropagation();
      if (args.readOnly) {
        clearRelationControlPointSession(event.pointerId);
        clearDomSelection();
        return;
      }
      const moved = Math.hypot(event.clientX - relControl.startClientX, event.clientY - relControl.startClientY) >= 3;
      const world2 = clientToWorld(event.clientX, event.clientY);
      const relationId = relControl.relationId;
      const handle = relControl.handle;
      const fromEndpoint = relControl.fromEndpoint;
      const toEndpoint = relControl.toEndpoint;
      const baseFromPort = relControl.baseFromPort;
      const baseFromPortRatio = relControl.baseFromPortRatio;
      const baseToPort = relControl.baseToPort;
      const baseToPortRatio = relControl.baseToPortRatio;
      const startControl1 = relControl.startControl1;
      const startControl2 = relControl.startControl2;
      clearRelationControlPointSession(event.pointerId);
      clearDomSelection();
      if (moved && world2) {
        const fromLayout = resolveRelationEndpointLayout3(baseLayoutRef.current, fromEndpoint);
        const toLayout = resolveRelationEndpointLayout3(baseLayoutRef.current, toEndpoint);
        const anchorLayout = handle === "control1" ? fromLayout : toLayout;
        const anchor = anchorLayout ? resolvePortAndRatioFromRay(anchorLayout, world2) : null;
        if (fromLayout && toLayout && anchor) {
          const nextFromPort = handle === "control1" ? anchor.port : baseFromPort;
          const nextFromPortRatio = handle === "control1" ? anchor.portRatio : baseFromPortRatio;
          const nextToPort = handle === "control2" ? anchor.port : baseToPort;
          const nextToPortRatio = handle === "control2" ? anchor.portRatio : baseToPortRatio;
          const start = resolvePortPoint3(fromLayout, nextFromPort, nextFromPortRatio);
          const end = resolvePortPoint3(toLayout, nextToPort, nextToPortRatio);
          const nextControl1 = handle === "control1" ? { x: world2.x - start.x, y: world2.y - start.y } : startControl1;
          const nextControl2 = handle === "control2" ? { x: world2.x - end.x, y: world2.y - end.y } : startControl2;
          const batch = args.core.dispatchBatch([
            {
              type: "set_relation_endpoint",
              payload: {
                relationId,
                endpoint: handle === "control1" ? "from" : "to",
                port: anchor.port,
                portRatio: anchor.portRatio
              }
            },
            {
              type: "set_relation_curve",
              payload: {
                relationId,
                curve: {
                  schemaVersion: 1,
                  kind: "cubic",
                  control1: nextControl1,
                  control2: nextControl2
                }
              }
            }
          ]);
          if (!batch.ok) {
            void args.dialog.alert(batch.error);
          }
        }
      }
      return;
    }
    const resize = resizeSessionRef.current;
    if (resize && resize.pointerId === event.pointerId) {
      event.preventDefault();
      event.stopPropagation();
      if (args.readOnly) {
        clearResizeSession(event.pointerId);
        clearDomSelection();
        return;
      }
      const moved = Math.abs(event.clientX - resize.startClientX) >= 3;
      const world2 = clientToWorld(event.clientX, event.clientY);
      const nodeId = resize.nodeId;
      const finalDraft = world2 ? resolveResizeDraftFromWorldX(resize, world2.x) : {
        width: resize.lastDraftWidth,
        snappedToAuto: resize.snappedToAuto,
        contentWidth: resize.snappedToAuto ? resize.restoreContentWidth : { mode: "fixed", width: resize.lastDraftWidth }
      };
      clearResizeSession(event.pointerId);
      clearDomSelection();
      if (moved) {
        if (finalDraft.snappedToAuto) {
          args.onNodeAction?.({
            type: "node.width.reset",
            nodeId,
            wrapWidth: finalDraft.contentWidth?.mode === "auto" ? finalDraft.contentWidth.wrapWidth : void 0
          });
        } else {
          args.onNodeAction?.({ type: "node.width.set", nodeId, width: finalDraft.width, mode: "fixed" });
        }
      }
      return;
    }
    const embedResize = embedResizeSessionRef.current;
    if (embedResize && embedResize.pointerId === event.pointerId) {
      event.preventDefault();
      event.stopPropagation();
      if (args.readOnly) {
        clearEmbedResizeSession(event.pointerId, { revert: true });
        clearDomSelection();
        return;
      }
      const moved = Math.hypot(event.clientX - embedResize.startClientX, event.clientY - embedResize.startClientY) >= 3;
      const scaleX = Number.isFinite(embedResize.scaleX) && embedResize.scaleX > 0 ? embedResize.scaleX : 1;
      const scaleY = Number.isFinite(embedResize.scaleY) && embedResize.scaleY > 0 ? embedResize.scaleY : 1;
      const nextWidth = Math.round(
        Math.max(80, Math.min(2400, embedResize.startWidth + (event.clientX - embedResize.startClientX) / scaleX))
      );
      const nextHeight = Math.round(
        Math.max(80, Math.min(2400, embedResize.startHeight + (event.clientY - embedResize.startClientY) / scaleY))
      );
      const nodeId = embedResize.nodeId;
      const blockId = embedResize.blockId;
      clearEmbedResizeSession(event.pointerId);
      clearDomSelection();
      if (moved) {
        const node = docRef.current.nodes[nodeId];
        if (node?.content?.schemaVersion === 1 && node.content.kind === "blocks") {
          const index = node.content.blocks.findIndex((block) => block.type === "embed" && block.id === blockId);
          if (index >= 0) {
            const target2 = node.content.blocks[index];
            if (!target2) return;
            if (target2.type === "embed") {
              const nextBlocks = node.content.blocks.slice();
              nextBlocks[index] = { ...target2, width: nextWidth, height: nextHeight };
              const nextContent = { ...node.content, blocks: nextBlocks };
              const result2 = args.core.dispatch({
                type: "set_node_content",
                payload: { nodeId, content: nextContent, plainText: node.text }
              });
              if (!result2.ok) {
                void args.dialog.alert(result2.error);
              }
            }
          }
        }
      }
      return;
    }
    const marquee = marqueeSessionRef.current;
    if (marquee && marquee.pointerId === event.pointerId) {
      if (args.readOnly) {
        clearMarqueeSession(event.pointerId);
        return;
      }
      const world2 = clientToWorld(event.clientX, event.clientY);
      if (!world2) {
        clearMarqueeSession(event.pointerId);
        return;
      }
      const minX = Math.min(marquee.startWorld.x, world2.x);
      const minY = Math.min(marquee.startWorld.y, world2.y);
      const maxX = Math.max(marquee.startWorld.x, world2.x);
      const maxY = Math.max(marquee.startWorld.y, world2.y);
      const rect = { x: minX, y: minY, width: Math.max(0, maxX - minX), height: Math.max(0, maxY - minY) };
      const intersects = (a2, b2) => {
        if (a2.width <= 0 || a2.height <= 0) return false;
        return a2.x < b2.x + b2.width && a2.x + a2.width > b2.x && a2.y < b2.y + b2.height && a2.y + a2.height > b2.y;
      };
      const nextSelected = /* @__PURE__ */ new Set();
      for (const [id, nodeLayout] of Object.entries(baseLayoutRef.current.nodes)) {
        if (intersects(rect, nodeLayout)) {
          nextSelected.add(id);
        }
      }
      args.setSelectedNodeIds(nextSelected);
      if (nextSelected.size === 0) {
        args.setSelection(null);
      } else {
        const first2 = nextSelected.values().next().value;
        if (first2) args.setSelection({ type: "node", id: first2 });
      }
      clearMarqueeSession(event.pointerId);
      clearDomSelection();
      return;
    }
    const pan = panSessionRef.current;
    if (pan && pan.pointerId === event.pointerId) {
      event.preventDefault();
      event.stopPropagation();
      const distance = Math.hypot(event.clientX - pan.startClientX, event.clientY - pan.startClientY);
      const shouldClearSelection = pan.clearSelectionOnClick && distance < 4;
      const shouldCreateRootOnDoublePress = shouldClearSelection && Boolean(args.onBlankDoublePress) && !args.readOnly && event.pointerType !== "mouse";
      clearPanSession(event.pointerId);
      clearDomSelection();
      if (shouldClearSelection) {
        args.setPendingRelationFromId(null);
        args.stopEdit();
        args.clearSelection();
      }
      if (shouldCreateRootOnDoublePress) {
        const world2 = clientToWorld(event.clientX, event.clientY);
        if (world2) {
          const now = typeof performance !== "undefined" && typeof performance.now === "function" ? performance.now() : Date.now();
          const last = lastBlankPressRef.current;
          const isDoublePress = last !== null && now - last.at <= 520 && Math.hypot(event.clientX - last.clientX, event.clientY - last.clientY) <= 32;
          lastBlankPressRef.current = { clientX: event.clientX, clientY: event.clientY, at: now };
          if (isDoublePress) {
            lastBlankPressRef.current = null;
            args.onBlankDoublePress?.({ x: world2.x, y: world2.y });
          }
        }
      }
      return;
    }
    const session = dragSessionRef.current;
    if (!session) return;
    if (session.pointerId !== event.pointerId) return;
    if (args.readOnly) {
      clearDragSession(event.pointerId);
      clearDomSelection();
      return;
    }
    const wasDragging = session.isDragging;
    const handledByCrossPane = wasDragging && args.crossPaneDrag?.onMapNodeDragEnd?.({
      nodeId: session.nodeId,
      pointerId: session.pointerId,
      clientX: event.clientX,
      clientY: event.clientY
    }) === true;
    const world = clientToWorld(event.clientX, event.clientY);
    if (!world) {
      clearDragSession(event.pointerId);
      return;
    }
    const ghost = resolveGhostPosition(session, world, event.altKey);
    let commands = [];
    if (wasDragging) {
      const baseLayout = baseLayoutRef.current;
      const draggedLayout = baseLayout.nodes[session.nodeId];
      if (!draggedLayout) {
        clearDragSession(event.pointerId);
        return;
      }
      const draggedRect = { x: ghost.x, y: ghost.y, width: draggedLayout.width, height: draggedLayout.height };
      const ignoreNodeIds = new Set(session.subtreeNodeIds);
      const ignoreSummaryIds = new Set(session.subtreeSummaryIds);
      const intent = resolveDropIntentV2({
        doc: docRef.current,
        layout: baseLayout,
        draggedNodeId: session.nodeId,
        draggedRect,
        ignoreNodeIds,
        ignoreSummaryIds,
        currentIntent: session.stableIntent,
        options: {
          tailSize: dropTailSize,
          childEnterPadding,
          childLeavePadding,
          siblingLanePadding,
          siblingLanePaddingActive,
          siblingEndPadding,
          siblingEndPaddingActive
        }
      });
      const stableIntent = stabilizeIntent(session, intent);
      const detachmentGateIntent = intent.kind === "none" ? stableIntent : intent;
      const { detached } = resolveDetachState({ session, intent: detachmentGateIntent, ghost, layout: baseLayout });
      commands = buildMoveCommandsForDrag({ detached, ghost, intent, session, stableIntent });
    }
    clearDragSession(event.pointerId);
    if (wasDragging) {
      clearDomSelection();
    }
    if (handledByCrossPane) return;
    if (!wasDragging) return;
    if (commands.length === 0) return;
    const result = commands.length === 1 ? args.core.dispatch(commands[0]) : args.core.dispatchBatch(commands);
    if (!result.ok) {
      void args.dialog.alert(result.error);
      return;
    }
    if (session.groupNodeIds.length > 1) {
      const nextDoc = args.core.getState().document;
      const selected = session.groupSelectedNodeIds.filter((nodeId) => Boolean(nextDoc.nodes[nodeId]));
      args.setSelectedNodeIds(new Set(selected.length > 0 ? selected : session.groupNodeIds.filter((nodeId) => Boolean(nextDoc.nodes[nodeId]))));
      args.setSelection({ type: "node", id: nextDoc.nodes[session.nodeId] ? session.nodeId : selected[0] ?? session.groupNodeIds[0] ?? session.nodeId });
    } else {
      args.selectSingleNode(session.nodeId);
    }
  };
  const onRelationControlHandlePointerDown = (info, event) => {
    if (event.button !== 0) return;
    if (args.isEditing) return;
    if (args.isMetaPopoverEditing) return;
    if (args.readOnly) return;
    if (dragSessionRef.current || panSessionRef.current || marqueeSessionRef.current || resizeSessionRef.current || relationControlPointSessionRef.current) return;
    const svg = args.svgRef.current;
    if (!svg) return;
    event.preventDefault();
    event.stopPropagation();
    args.focusCanvas();
    args.setSelectedNodeIds((prev) => prev.size === 0 ? prev : /* @__PURE__ */ new Set());
    args.setSelection({ type: "relation", id: info.relationId });
    const relation = docRef.current.relations.find((rel2) => rel2.id === info.relationId);
    if (!relation) return;
    const baseFromPort = relation.from.port ?? "right";
    const baseFromPortRatio = normalizePortRatio(relation.from.portRatio);
    const baseToPort = relation.to.port ?? "left";
    const baseToPortRatio = normalizePortRatio(relation.to.portRatio);
    relationControlPointSessionRef.current = {
      relationId: info.relationId,
      handle: info.handle,
      fromEndpoint: relation.from,
      toEndpoint: relation.to,
      pointerId: event.pointerId,
      startClientX: event.clientX,
      startClientY: event.clientY,
      startControl1: info.control1,
      startControl2: info.control2,
      baseFromPort,
      baseFromPortRatio,
      baseToPort,
      baseToPortRatio,
      pendingMove: null,
      rafId: null
    };
    args.setRelationEndpointsDraft({
      relationId: info.relationId,
      fromPort: baseFromPort,
      fromPortRatio: baseFromPortRatio,
      toPort: baseToPort,
      toPortRatio: baseToPortRatio
    });
    args.setRelationCurveDraft({
      relationId: info.relationId,
      curve: {
        schemaVersion: 1,
        kind: "cubic",
        control1: info.control1,
        control2: info.control2
      }
    });
    try {
      svg.setPointerCapture(event.pointerId);
    } catch {
    }
  };
  return {
    dragUi,
    isPanning,
    marqueeRect,
    onSvgPointerDownCapture,
    onSvgPointerMove,
    onSvgPointerUp,
    onSvgPointerCancel,
    onNodePointerDown,
    onSummaryPointerDown,
    onNodeResizeHandlePointerDown,
    onRelationControlHandlePointerDown
  };
}

// ../react/src/mindmap-editor/hooks/use-canvas-shortcuts.ts
var import_react35 = __toESM(require_react(), 1);
function useCanvasShortcuts(params) {
  const {
    core,
    doc: doc3,
    layout,
    containerLayoutTypeById,
    selection,
    readOnly,
    isEditing,
    isDragging,
    isPanning,
    pendingRelationFromId,
    setPendingRelationFromId,
    keymapOverride,
    undo: undo2,
    redo: redo2,
    addChild,
    addSibling,
    deleteSelected,
    startEditNode,
    startEditSummary,
    selectSingleNode,
    spaceDownRef,
    setSpaceDown,
    spaceGestureRef
  } = params;
  const shortcutKeymap = (0, import_react35.useMemo)(() => {
    const base2 = createDefaultShortcutKeymap(detectPlatform());
    return mergeShortcutKeymaps(base2, keymapOverride);
  }, [keymapOverride]);
  const resetSpaceState = (0, import_react35.useCallback)(() => {
    spaceDownRef.current = false;
    setSpaceDown(false);
    spaceGestureRef.current = null;
  }, [setSpaceDown, spaceDownRef, spaceGestureRef]);
  const onCanvasKeyDownCapture = (0, import_react35.useCallback)(
    (event) => {
      if (isEditing) return;
      const native = event.nativeEvent;
      if (isTypingTarget(native.target)) return;
      if (isDragging || isPanning) return;
      if (native.code === "Space") {
        if (spaceDownRef.current || native.repeat) return;
        spaceDownRef.current = true;
        setSpaceDown(true);
        spaceGestureRef.current = {
          downAt: typeof performance !== "undefined" && typeof performance.now === "function" ? performance.now() : Date.now(),
          consumed: false
        };
        event.preventDefault();
        event.stopPropagation();
        return;
      }
      if (!readOnly && selection?.type === "node") {
        const direction = native.code === "ArrowUp" ? "up" : native.code === "ArrowDown" ? "down" : native.code === "ArrowLeft" ? "left" : native.code === "ArrowRight" ? "right" : null;
        if (direction) {
          event.preventDefault();
          event.stopPropagation();
          const nav2 = resolveArrowNavigation({
            doc: doc3,
            layout,
            fromNodeId: selection.id,
            direction,
            containerLayoutTypeById
          });
          if (!nav2) return;
          if (nav2.type === "toggleCollapse") {
            core.dispatch({ type: "toggle_node_collapsed", payload: { nodeId: nav2.nodeId } });
            return;
          }
          selectSingleNode(nav2.nodeId);
          return;
        }
      }
      const selectionKind = selection ? selection.type : "none";
      const context = {
        selection: selectionKind,
        editing: Boolean(isEditing),
        dragging: Boolean(isDragging),
        panning: Boolean(isPanning),
        hasPendingRelation: Boolean(pendingRelationFromId)
      };
      const action = resolveShortcutAction(native, context, shortcutKeymap);
      if (!action) return;
      if (readOnly) {
        if (action !== "cancelPendingRelation") return;
        event.preventDefault();
        event.stopPropagation();
        setPendingRelationFromId(null);
        return;
      }
      event.preventDefault();
      event.stopPropagation();
      if (action === "undo") {
        undo2();
        return;
      }
      if (action === "redo") {
        redo2();
        return;
      }
      if (action === "addChild") {
        addChild();
        return;
      }
      if (action === "addSibling") {
        addSibling();
        return;
      }
      if (action === "deleteSelection") {
        deleteSelected();
        return;
      }
      if (action === "startEdit") {
        if (selection?.type === "node") startEditNode(selection.id);
        if (selection?.type === "summary") startEditSummary(selection.id);
        return;
      }
      if (action === "cancelPendingRelation") {
        setPendingRelationFromId(null);
      }
    },
    [
      addChild,
      addSibling,
      core,
      deleteSelected,
      doc3,
      layout,
      containerLayoutTypeById,
      isDragging,
      isEditing,
      isPanning,
      pendingRelationFromId,
      redo2,
      selectSingleNode,
      selection,
      setPendingRelationFromId,
      setSpaceDown,
      shortcutKeymap,
      spaceDownRef,
      spaceGestureRef,
      startEditNode,
      startEditSummary,
      undo2
    ]
  );
  const onCanvasKeyUpCapture = (0, import_react35.useCallback)(
    (event) => {
      if (isEditing) return;
      const native = event.nativeEvent;
      if (native.code !== "Space") return;
      if (!spaceDownRef.current) return;
      spaceDownRef.current = false;
      setSpaceDown(false);
      event.preventDefault();
      event.stopPropagation();
      const gesture = spaceGestureRef.current;
      spaceGestureRef.current = null;
      if (!gesture) return;
      if (gesture.consumed) return;
      const now = typeof performance !== "undefined" && typeof performance.now === "function" ? performance.now() : Date.now();
      const duration = now - gesture.downAt;
      if (duration > 260) return;
      if (readOnly) return;
      if (selection?.type !== "node") return;
      startEditNode(selection.id);
    },
    [isEditing, readOnly, selection, setSpaceDown, spaceDownRef, spaceGestureRef, startEditNode]
  );
  const onCanvasBlur = (0, import_react35.useCallback)(() => {
    resetSpaceState();
  }, [resetSpaceState]);
  return { onCanvasBlur, onCanvasKeyDownCapture, onCanvasKeyUpCapture };
}

// ../react/src/mindmap-editor/hooks/use-clipboard-controller.ts
var import_react36 = __toESM(require_react(), 1);
var KMIND_NODE_CONTENT_MIME = "application/x-kmind-nodecontent+json";
var KMIND_SUBTREE_MIME = "application/x-kmind-subtree+json";
function useClipboardController(params) {
  const { core, doc: doc3, dialog, clipboard, selectedNodeId } = params;
  const writeClipboard = (0, import_react36.useCallback)(
    async (payload) => {
      try {
        if (typeof ClipboardItem !== "undefined" && navigator.clipboard?.write) {
          await navigator.clipboard.write([
            new ClipboardItem({
              [payload.mime]: new Blob([payload.json], { type: payload.mime }),
              "text/plain": new Blob([payload.plainText], { type: "text/plain" })
            })
          ]);
          return;
        }
        if (!clipboard) {
          await dialog.alert("\u5F53\u524D\u73AF\u5883\u4E0D\u652F\u6301\u5199\u5165\u526A\u8D34\u677F\u3002");
          return;
        }
        await clipboard.writeText(payload.json);
      } catch {
        await dialog.alert("\u5199\u5165\u526A\u8D34\u677F\u5931\u8D25\uFF08\u6D4F\u89C8\u5668\u53EF\u80FD\u62E6\u622A\u4E86\u6743\u9650\uFF09\u3002");
      }
    },
    [clipboard, dialog]
  );
  const readClipboardPrefer = (0, import_react36.useCallback)(
    async (mime) => {
      try {
        if (navigator.clipboard?.read) {
          const items = await navigator.clipboard.read();
          for (const item of items) {
            if (!item.types.includes(mime)) continue;
            const blob = await item.getType(mime);
            return await blob.text();
          }
        }
      } catch {
      }
      if (!clipboard) return null;
      try {
        return await clipboard.readText();
      } catch {
        return null;
      }
    },
    [clipboard]
  );
  const copyNodeContent = (0, import_react36.useCallback)(async () => {
    if (!selectedNodeId) return;
    const node = doc3.nodes[selectedNodeId];
    if (!node) return;
    const assets = collectReferencedAssets(doc3, [selectedNodeId]);
    const payload = {
      type: "kmind-nodecontent@1",
      plainText: node.text,
      content: node.content ?? { schemaVersion: 1, kind: "plain-text", text: node.text },
      assets
    };
    await writeClipboard({ mime: KMIND_NODE_CONTENT_MIME, json: JSON.stringify(payload), plainText: node.text });
  }, [doc3, selectedNodeId, writeClipboard]);
  const pasteNodeContent = (0, import_react36.useCallback)(async () => {
    if (!selectedNodeId) return;
    const raw = await readClipboardPrefer(KMIND_NODE_CONTENT_MIME);
    if (!raw) {
      await dialog.alert("\u8BFB\u53D6\u526A\u8D34\u677F\u5931\u8D25\uFF08\u9700\u8981\u7528\u6237\u6388\u6743\uFF09\u3002");
      return;
    }
    try {
      const parsed = JSON.parse(raw);
      if (parsed.type !== "kmind-nodecontent@1" || !parsed.content || typeof parsed.plainText !== "string") {
        await dialog.alert("\u526A\u8D34\u677F\u5185\u5BB9\u4E0D\u662F KMind \u8282\u70B9\u5185\u5BB9\u6570\u636E\u3002");
        return;
      }
      const remapped = remapIncomingAssets({ doc: doc3, content: parsed.content, assets: parsed.assets ?? {} });
      const result = core.dispatch({
        type: "set_node_content",
        payload: {
          nodeId: selectedNodeId,
          content: remapped.content,
          plainText: parsed.plainText,
          assets: remapped.assets
        }
      });
      if (!result.ok) {
        await dialog.alert(result.error);
      }
    } catch {
      await dialog.alert("\u89E3\u6790\u526A\u8D34\u677F\u5931\u8D25\uFF08\u5185\u5BB9\u4E0D\u662F JSON\uFF09\u3002");
    }
  }, [core, dialog, doc3, readClipboardPrefer, selectedNodeId]);
  const copySubtree = (0, import_react36.useCallback)(async () => {
    if (!selectedNodeId) return;
    const selected = doc3.nodes[selectedNodeId];
    if (!selected) return;
    const subtreeIds = collectSubtreeNodeIds2(doc3, selectedNodeId);
    const nodes = {};
    for (const id of subtreeIds) {
      const node = doc3.nodes[id];
      if (!node) continue;
      nodes[id] = node;
    }
    const assets = collectReferencedAssets(doc3, subtreeIds);
    const payload = { type: "kmind-subtree@2", roots: [selectedNodeId], nodes, assets };
    await writeClipboard({ mime: KMIND_SUBTREE_MIME, json: JSON.stringify(payload), plainText: selected.text });
  }, [doc3, selectedNodeId, writeClipboard]);
  const pasteSubtree = (0, import_react36.useCallback)(async () => {
    const raw = await readClipboardPrefer(KMIND_SUBTREE_MIME);
    if (!raw) {
      await dialog.alert("\u8BFB\u53D6\u526A\u8D34\u677F\u5931\u8D25\uFF08\u9700\u8981\u7528\u6237\u6388\u6743\uFF09\u3002");
      return;
    }
    try {
      const parsed = JSON.parse(raw);
      if (parsed.type !== "kmind-subtree@2" || !parsed.roots || !parsed.nodes) {
        await dialog.alert("\u526A\u8D34\u677F\u5185\u5BB9\u4E0D\u662F KMind \u5B50\u6811\u6570\u636E\u3002");
        return;
      }
      const parentId = selectedNodeId;
      const result = core.dispatch({
        type: "insert_subtree",
        payload: { parentId, subtree: { roots: parsed.roots, nodes: parsed.nodes, assets: parsed.assets ?? {} } }
      });
      if (!result.ok) {
        await dialog.alert(result.error);
      }
    } catch {
      await dialog.alert("\u8BFB\u53D6/\u89E3\u6790\u526A\u8D34\u677F\u5931\u8D25\uFF08\u9700\u8981\u7528\u6237\u6388\u6743\u6216\u526A\u8D34\u677F\u5185\u5BB9\u4E0D\u662F JSON\uFF09\u3002");
    }
  }, [core, dialog, doc3.nodes, readClipboardPrefer, selectedNodeId]);
  return {
    copyNodeContent,
    pasteNodeContent,
    copySubtree,
    pasteSubtree
  };
}

// ../react/src/mindmap-editor/hooks/use-export-controller.ts
var import_react37 = __toESM(require_react(), 1);
init_src();
function useExportController(args) {
  const [svgExportMode, setSvgExportMode] = (0, import_react37.useState)("fidelity");
  const [pngExportMode, setPngExportMode] = (0, import_react37.useState)("fast");
  const [exportScope, setExportScope] = (0, import_react37.useState)("current");
  const [exportExpandedActive, setExportExpandedActive] = (0, import_react37.useState)(false);
  const [exportFullActive, setExportFullActive] = (0, import_react37.useState)(false);
  const [exportActive, setExportActive] = (0, import_react37.useState)(false);
  const exportActiveCounterRef = (0, import_react37.useRef)(0);
  const beginExport = (0, import_react37.useCallback)(() => {
    exportActiveCounterRef.current += 1;
    setExportActive(true);
  }, []);
  const endExport = (0, import_react37.useCallback)(() => {
    exportActiveCounterRef.current = Math.max(0, exportActiveCounterRef.current - 1);
    if (exportActiveCounterRef.current === 0) setExportActive(false);
  }, []);
  const exportScopeRef = (0, import_react37.useRef)(exportScope);
  (0, import_react37.useEffect)(() => {
    exportScopeRef.current = exportScope;
  }, [exportScope]);
  const exportExpandedSvgRef = (0, import_react37.useRef)(null);
  const exportFullSvgRef = (0, import_react37.useRef)(null);
  const hasCollapsedNodes = Boolean(args.doc.viewState?.collapsedNodeIds && Object.keys(args.doc.viewState.collapsedNodeIds).length > 0);
  const exportExpandedEnabled = hasCollapsedNodes && (exportScope === "expanded" || exportExpandedActive);
  const exportExpandedDoc = (0, import_react37.useMemo)(() => {
    if (!exportExpandedEnabled) return args.doc;
    const viewState = args.doc.viewState;
    if (!viewState) return args.doc;
    const { collapsedNodeIds: _removed, ...rest } = viewState;
    const nextViewState = Object.keys(rest).length > 0 ? rest : void 0;
    return { ...args.doc, viewState: nextViewState };
  }, [args.doc, exportExpandedEnabled]);
  (0, import_react37.useEffect)(() => {
    if (hasCollapsedNodes) return;
    setExportScope((prev) => prev === "expanded" ? "current" : prev);
  }, [hasCollapsedNodes]);
  const exportExpandedLayout = (0, import_react37.useMemo)(() => {
    if (!exportExpandedEnabled) return args.layout;
    return layoutMindMap(exportExpandedDoc, args.effectiveNodeSizes, args.summarySizes, {
      horizontalGap: args.layoutOptions.horizontalGap,
      verticalGap: args.layoutOptions.verticalGap,
      rootGap: args.layoutOptions.rootGap,
      rootOptions: args.layoutOptions.rootOptions,
      engine: args.layoutEngine ?? "tidy",
      tidy: args.layoutOptions.tidy
    });
  }, [args.effectiveNodeSizes, args.layout, args.layoutEngine, args.layoutOptions, args.summarySizes, exportExpandedDoc, exportExpandedEnabled]);
  const exportSceneRef = (0, import_react37.useRef)({ current: { doc: args.doc, layout: args.layout }, expanded: null });
  (0, import_react37.useEffect)(() => {
    exportSceneRef.current = {
      current: { doc: args.doc, layout: args.layout },
      expanded: exportExpandedEnabled ? { doc: exportExpandedDoc, layout: exportExpandedLayout } : null
    };
  }, [args.doc, args.layout, exportExpandedDoc, exportExpandedEnabled, exportExpandedLayout]);
  const nextFrame = (0, import_react37.useCallback)(
    () => new Promise((resolve) => {
      const raf = typeof requestAnimationFrame === "function" ? requestAnimationFrame : (fn) => setTimeout(fn, 16);
      raf(() => resolve());
    }),
    []
  );
  const exportSvgFromCanvas = (0, import_react37.useCallback)(
    async (exportArgs = {}) => {
      const mode = exportArgs.mode === "portable" ? "portable" : "fidelity";
      const scope = exportArgs.scope === "expanded" ? "expanded" : "current";
      const currentDoc = exportSceneRef.current.current.doc;
      const hasCollapsed = Boolean(currentDoc.viewState?.collapsedNodeIds && Object.keys(currentDoc.viewState.collapsedNodeIds).length > 0);
      const wantsExpanded = scope === "expanded" && hasCollapsed;
      const wantsFull = Boolean(args.exportFullSceneEnabled) && !wantsExpanded;
      try {
        beginExport();
        if (wantsExpanded) {
          if (!exportExpandedSvgRef.current || !exportSceneRef.current.expanded) {
            setExportExpandedActive(true);
            for (let i = 0; i < 30; i += 1) {
              await nextFrame();
              if (exportExpandedSvgRef.current && exportSceneRef.current.expanded) break;
            }
          }
          const svg2 = exportExpandedSvgRef.current;
          const scene2 = exportSceneRef.current.expanded;
          if (!svg2 || !scene2) throw new Error("Expanded export view is not ready.");
          const theme2 = args.documentThemeRef.current;
          return await exportMindMapSvgBlob(svg2, scene2, {
            mode,
            padding: exportPadding,
            textStyle: {
              fontFamily: theme2.layout.fontFamily,
              fontSize: theme2.layout.fontSize,
              lineHeight: theme2.layout.lineHeight,
              paddingX: theme2.layout.paddingX,
              paddingY: theme2.layout.paddingY,
              color: theme2.paint.text
            }
          });
        }
        if (wantsFull) {
          if (!exportFullSvgRef.current) {
            setExportFullActive(true);
            for (let i = 0; i < 30; i += 1) {
              await nextFrame();
              if (exportFullSvgRef.current) break;
            }
          }
          const svg2 = exportFullSvgRef.current;
          const scene2 = exportSceneRef.current.current;
          if (!svg2) throw new Error("Export view is not ready.");
          const theme2 = args.documentThemeRef.current;
          return await exportMindMapSvgBlob(svg2, scene2, {
            mode,
            padding: exportPadding,
            textStyle: {
              fontFamily: theme2.layout.fontFamily,
              fontSize: theme2.layout.fontSize,
              lineHeight: theme2.layout.lineHeight,
              paddingX: theme2.layout.paddingX,
              paddingY: theme2.layout.paddingY,
              color: theme2.paint.text
            }
          });
        }
        const svg = args.svgRef.current;
        const scene = exportSceneRef.current.current;
        if (!svg) throw new Error("Export canvas is not ready.");
        const theme = args.documentThemeRef.current;
        return await exportMindMapSvgBlob(svg, scene, {
          mode,
          padding: exportPadding,
          textStyle: {
            fontFamily: theme.layout.fontFamily,
            fontSize: theme.layout.fontSize,
            lineHeight: theme.layout.lineHeight,
            paddingX: theme.layout.paddingX,
            paddingY: theme.layout.paddingY,
            color: theme.paint.text
          }
        });
      } finally {
        if (wantsExpanded && exportScopeRef.current !== "expanded") {
          setExportExpandedActive(false);
        }
        if (wantsFull) {
          setExportFullActive(false);
        }
        endExport();
      }
    },
    [args.documentThemeRef, args.exportFullSceneEnabled, args.svgRef, beginExport, endExport, nextFrame]
  );
  const exportPngFromCanvas = (0, import_react37.useCallback)(
    async (exportArgs = {}) => {
      const mode = exportArgs.mode === "accurate" ? "accurate" : "fast";
      const scope = exportArgs.scope === "expanded" ? "expanded" : "current";
      const scale = Math.max(0.5, Math.min(6, exportArgs.scale ?? 2));
      const currentDoc = exportSceneRef.current.current.doc;
      const hasCollapsed = Boolean(currentDoc.viewState?.collapsedNodeIds && Object.keys(currentDoc.viewState.collapsedNodeIds).length > 0);
      const wantsExpanded = scope === "expanded" && hasCollapsed;
      const wantsFull = Boolean(args.exportFullSceneEnabled) && !wantsExpanded;
      try {
        beginExport();
        if (wantsExpanded) {
          const viewState = exportSceneRef.current.current.doc.viewState;
          const expandedDoc = (() => {
            if (!viewState) return exportSceneRef.current.current.doc;
            const { collapsedNodeIds: _removed, ...rest } = viewState;
            const nextViewState = Object.keys(rest).length > 0 ? rest : void 0;
            return { ...exportSceneRef.current.current.doc, viewState: nextViewState };
          })();
          const expandedLayout = layoutMindMap(expandedDoc, args.effectiveNodeSizes, args.summarySizes, {
            horizontalGap: args.layoutOptions.horizontalGap,
            verticalGap: args.layoutOptions.verticalGap,
            rootGap: args.layoutOptions.rootGap,
            rootOptions: args.layoutOptions.rootOptions,
            engine: args.layoutEngine ?? "tidy",
            tidy: args.layoutOptions.tidy
          });
          assertPngExportSafe(expandedLayout.bounds, { padding: exportPadding, scale, mode });
        } else {
          assertPngExportSafe(exportSceneRef.current.current.layout.bounds, { padding: exportPadding, scale, mode });
        }
        if (wantsExpanded) {
          if (!exportExpandedSvgRef.current || !exportSceneRef.current.expanded) {
            setExportExpandedActive(true);
            for (let i = 0; i < 30; i += 1) {
              await nextFrame();
              if (exportExpandedSvgRef.current && exportSceneRef.current.expanded) break;
            }
          }
          const svg2 = exportExpandedSvgRef.current;
          const scene2 = exportSceneRef.current.expanded;
          if (!svg2 || !scene2) throw new Error("Expanded export view is not ready.");
          const theme2 = args.documentThemeRef.current;
          const background2 = theme2.background?.color ?? theme2.paint.bg;
          return await exportMindMapPngBlob(svg2, scene2, {
            mode,
            scale,
            background: background2,
            padding: exportPadding,
            beautify: exportArgs.beautify,
            textStyle: {
              fontFamily: theme2.layout.fontFamily,
              fontSize: theme2.layout.fontSize,
              lineHeight: theme2.layout.lineHeight,
              paddingX: theme2.layout.paddingX,
              paddingY: theme2.layout.paddingY,
              color: theme2.paint.text
            }
          });
        }
        if (wantsFull) {
          if (!exportFullSvgRef.current) {
            setExportFullActive(true);
            for (let i = 0; i < 30; i += 1) {
              await nextFrame();
              if (exportFullSvgRef.current) break;
            }
          }
          const svg2 = exportFullSvgRef.current;
          const scene2 = exportSceneRef.current.current;
          if (!svg2) throw new Error("Export view is not ready.");
          const theme2 = args.documentThemeRef.current;
          const background2 = theme2.background?.color ?? theme2.paint.bg;
          return await exportMindMapPngBlob(svg2, scene2, {
            mode,
            scale,
            background: background2,
            padding: exportPadding,
            beautify: exportArgs.beautify,
            textStyle: {
              fontFamily: theme2.layout.fontFamily,
              fontSize: theme2.layout.fontSize,
              lineHeight: theme2.layout.lineHeight,
              paddingX: theme2.layout.paddingX,
              paddingY: theme2.layout.paddingY,
              color: theme2.paint.text
            }
          });
        }
        const svg = args.svgRef.current;
        const scene = exportSceneRef.current.current;
        if (!svg) throw new Error("Export canvas is not ready.");
        const theme = args.documentThemeRef.current;
        const background = theme.background?.color ?? theme.paint.bg;
        return await exportMindMapPngBlob(svg, scene, {
          mode,
          scale,
          background,
          padding: exportPadding,
          beautify: exportArgs.beautify,
          textStyle: {
            fontFamily: theme.layout.fontFamily,
            fontSize: theme.layout.fontSize,
            lineHeight: theme.layout.lineHeight,
            paddingX: theme.layout.paddingX,
            paddingY: theme.layout.paddingY,
            color: theme.paint.text
          }
        });
      } finally {
        if (wantsExpanded && exportScopeRef.current !== "expanded") {
          setExportExpandedActive(false);
        }
        if (wantsFull) {
          setExportFullActive(false);
        }
        endExport();
      }
    },
    [args.documentThemeRef, args.exportFullSceneEnabled, args.svgRef, beginExport, endExport, nextFrame]
  );
  return {
    exportActive,
    svgExportMode,
    setSvgExportMode,
    pngExportMode,
    setPngExportMode,
    exportScope,
    setExportScope,
    hasCollapsedNodes,
    exportExpandedEnabled,
    exportExpandedDoc,
    exportExpandedLayout,
    exportExpandedSvgRef,
    exportFullActive,
    exportFullSvgRef,
    exportSvgFromCanvas,
    exportPngFromCanvas
  };
}

// ../react/src/mindmap-editor/hooks/use-camera.ts
var import_react38 = __toESM(require_react(), 1);
function useCamera(args) {
  const { layout, viewportSize } = args;
  const scopeId = typeof args.scopeId === "string" && args.scopeId.trim().length > 0 ? args.scopeId : null;
  const storage = args.storage ?? null;
  const persistMode = args.persistMode ?? "full";
  const cameraRef = (0, import_react38.useRef)({ x: 0, y: 0, zoom: 1 });
  const didInitCameraRef = (0, import_react38.useRef)(false);
  const cameraByScopeRef = (0, import_react38.useRef)(/* @__PURE__ */ new Map());
  const persistedByScopeRef = (0, import_react38.useRef)(/* @__PURE__ */ new Map());
  const lastScopeIdRef = (0, import_react38.useRef)(scopeId);
  const [cameraVersion, setCameraVersion] = (0, import_react38.useState)(0);
  const saveTimerRef = (0, import_react38.useRef)(null);
  const lastSavedSignatureRef = (0, import_react38.useRef)(null);
  const signatureOf = (docId, camera) => `${docId}:${camera.x}:${camera.y}:${camera.zoom}`;
  const resolveCameraToPersist = (docId, current) => {
    if (persistMode === "none") return null;
    if (persistMode === "full") return current;
    const persisted = persistedByScopeRef.current.get(docId);
    if (!persisted) return { x: current.x, y: current.y, zoom: current.zoom };
    return { x: persisted.x, y: persisted.y, zoom: current.zoom };
  };
  (0, import_react38.useLayoutEffect)(() => {
    const hasViewport = viewportSize.width > 1 && viewportSize.height > 1;
    const lastScopeId = lastScopeIdRef.current;
    if (lastScopeId !== scopeId) {
      if (lastScopeId && didInitCameraRef.current) {
        cameraByScopeRef.current.set(lastScopeId, cameraRef.current);
        if (storage) {
          try {
            const payload = resolveCameraToPersist(lastScopeId, cameraRef.current);
            if (payload) {
              writeWorkspaceCameraV1(storage, lastScopeId, payload);
              persistedByScopeRef.current.set(lastScopeId, payload);
              lastSavedSignatureRef.current = signatureOf(lastScopeId, payload);
            }
          } catch {
          }
        }
      }
      lastScopeIdRef.current = scopeId;
      didInitCameraRef.current = false;
    }
    if (didInitCameraRef.current) return;
    if (scopeId) {
      const saved = cameraByScopeRef.current.get(scopeId);
      if (saved) {
        cameraRef.current = saved;
        didInitCameraRef.current = true;
        persistedByScopeRef.current.set(scopeId, saved);
        lastSavedSignatureRef.current = signatureOf(scopeId, saved);
        setCameraVersion((version2) => version2 + 1);
        return;
      }
      if (storage) {
        const persisted = tryParseWorkspaceCameraV1(storage.getItem(makeWorkspaceCameraKeyV1(scopeId)));
        if (persisted) {
          const next2 = { x: persisted.x, y: persisted.y, zoom: persisted.zoom };
          cameraRef.current = next2;
          cameraByScopeRef.current.set(scopeId, next2);
          didInitCameraRef.current = true;
          persistedByScopeRef.current.set(scopeId, next2);
          lastSavedSignatureRef.current = signatureOf(scopeId, next2);
          setCameraVersion((version2) => version2 + 1);
          return;
        }
      }
      if (!hasViewport) return;
      const padding = 80;
      const targetWidth = Math.max(1, layout.bounds.width + padding * 2);
      const targetHeight = Math.max(1, layout.bounds.height + padding * 2);
      const fitZoom = Math.min(4, Math.max(0.1, Math.min(viewportSize.width / targetWidth, viewportSize.height / targetHeight)));
      const zoom = Math.min(1, fitZoom);
      const viewWidth = viewportSize.width / zoom;
      const viewHeight = viewportSize.height / zoom;
      const centerX = layout.bounds.minX + layout.bounds.width / 2;
      const centerY = layout.bounds.minY + layout.bounds.height / 2;
      const next = {
        ...cameraRef.current,
        zoom,
        x: Math.round(centerX - viewWidth / 2),
        y: Math.round(centerY - viewHeight / 2)
      };
      cameraRef.current = next;
      cameraByScopeRef.current.set(scopeId, next);
      didInitCameraRef.current = true;
      persistedByScopeRef.current.set(scopeId, next);
      lastSavedSignatureRef.current = signatureOf(scopeId, next);
      setCameraVersion((version2) => version2 + 1);
      return;
    }
    if (!hasViewport) return;
    const view = resolveViewBoxFromCamera(cameraRef.current, viewportSize);
    const { bounds } = layout;
    cameraRef.current = {
      ...cameraRef.current,
      x: Math.round(bounds.minX + bounds.width / 2 - view.width / 2),
      y: Math.round(bounds.minY + bounds.height / 2 - view.height / 2)
    };
    didInitCameraRef.current = true;
    setCameraVersion((version2) => version2 + 1);
  }, [layout, scopeId, storage, viewportSize.height, viewportSize.width]);
  const viewBox = (0, import_react38.useMemo)(() => resolveViewBoxFromCamera(cameraRef.current, viewportSize), [cameraVersion, viewportSize]);
  const viewBoxRef = (0, import_react38.useRef)(viewBox);
  (0, import_react38.useEffect)(() => {
    viewBoxRef.current = viewBox;
  }, [viewBox]);
  (0, import_react38.useEffect)(() => {
    if (!scopeId) return;
    cameraByScopeRef.current.set(scopeId, cameraRef.current);
  }, [cameraVersion, scopeId]);
  const clampZoom2 = (zoom) => Math.min(4, Math.max(0.1, zoom));
  const applyCamera = (next) => {
    cameraRef.current = next;
    didInitCameraRef.current = true;
    setCameraVersion((version2) => version2 + 1);
  };
  const zoomTo = (nextZoomRaw) => {
    if (viewportSize.width <= 1 || viewportSize.height <= 1) return;
    const current = cameraRef.current;
    const nextZoom = clampZoom2(nextZoomRaw);
    const view = resolveViewBoxFromCamera(current, viewportSize);
    const centerX = current.x + view.width / 2;
    const centerY = current.y + view.height / 2;
    const nextViewWidth = viewportSize.width / nextZoom;
    const nextViewHeight = viewportSize.height / nextZoom;
    applyCamera({
      ...current,
      zoom: nextZoom,
      x: Math.round(centerX - nextViewWidth / 2),
      y: Math.round(centerY - nextViewHeight / 2)
    });
  };
  const zoomIn = () => zoomTo(cameraRef.current.zoom * 1.12);
  const zoomOut = () => zoomTo(cameraRef.current.zoom / 1.12);
  const fitView = () => {
    if (viewportSize.width <= 1 || viewportSize.height <= 1) return;
    const padding = 80;
    const targetWidth = Math.max(1, layout.bounds.width + padding * 2);
    const targetHeight = Math.max(1, layout.bounds.height + padding * 2);
    const nextZoom = clampZoom2(Math.min(viewportSize.width / targetWidth, viewportSize.height / targetHeight));
    const viewWidth = viewportSize.width / nextZoom;
    const viewHeight = viewportSize.height / nextZoom;
    const centerX = layout.bounds.minX + layout.bounds.width / 2;
    const centerY = layout.bounds.minY + layout.bounds.height / 2;
    applyCamera({
      ...cameraRef.current,
      zoom: nextZoom,
      x: Math.round(centerX - viewWidth / 2),
      y: Math.round(centerY - viewHeight / 2)
    });
  };
  (0, import_react38.useEffect)(() => {
    if (!scopeId) return;
    if (!storage) return;
    if (!didInitCameraRef.current) return;
    if (persistMode === "none") return;
    if (saveTimerRef.current !== null) window.clearTimeout(saveTimerRef.current);
    saveTimerRef.current = window.setTimeout(() => {
      saveTimerRef.current = null;
      const current = cameraRef.current;
      const payload = resolveCameraToPersist(scopeId, current);
      if (!payload) return;
      const signature = signatureOf(scopeId, payload);
      if (signature === lastSavedSignatureRef.current) return;
      lastSavedSignatureRef.current = signature;
      try {
        writeWorkspaceCameraV1(storage, scopeId, payload);
        persistedByScopeRef.current.set(scopeId, payload);
      } catch {
      }
    }, 260);
    return () => {
      if (saveTimerRef.current !== null) {
        window.clearTimeout(saveTimerRef.current);
        saveTimerRef.current = null;
      }
    };
  }, [cameraVersion, persistMode, scopeId, storage]);
  (0, import_react38.useEffect)(() => {
    if (!scopeId) return;
    if (!storage) return;
    if (persistMode === "none") return;
    const flush = () => {
      if (!didInitCameraRef.current) return;
      if (saveTimerRef.current !== null) {
        window.clearTimeout(saveTimerRef.current);
        saveTimerRef.current = null;
      }
      const current = cameraRef.current;
      const payload = resolveCameraToPersist(scopeId, current);
      if (!payload) return;
      const signature = signatureOf(scopeId, payload);
      if (signature === lastSavedSignatureRef.current) return;
      lastSavedSignatureRef.current = signature;
      try {
        writeWorkspaceCameraV1(storage, scopeId, payload);
        persistedByScopeRef.current.set(scopeId, payload);
      } catch {
      }
    };
    const onVisibility = () => {
      if (typeof document === "undefined") return;
      if (document.visibilityState === "hidden") flush();
    };
    window.addEventListener("pagehide", flush);
    document.addEventListener("visibilitychange", onVisibility);
    return () => {
      if (lastScopeIdRef.current === scopeId) flush();
      window.removeEventListener("pagehide", flush);
      document.removeEventListener("visibilitychange", onVisibility);
    };
  }, [persistMode, scopeId, storage]);
  return { cameraRef, setCameraVersion, viewBox, viewBoxRef, zoomIn, zoomOut, fitView };
}

// ../react/src/mindmap-editor/hooks/use-node-overlays.ts
var import_react39 = __toESM(require_react(), 1);
function clamp3(value, min, max) {
  return Math.min(max, Math.max(min, value));
}
function useNodeOverlays(params) {
  const { doc: doc3, isEditing } = params;
  const readOnly = Boolean(params.readOnly);
  const [linksPanel, setLinksPanel] = (0, import_react39.useState)(null);
  const linksPanelPinnedRef = (0, import_react39.useRef)(false);
  const linksPanelCloseTimerRef = (0, import_react39.useRef)(null);
  const linksPanelHoverRef = (0, import_react39.useRef)(false);
  const linksPanelIconHoverRef = (0, import_react39.useRef)(false);
  const [metaPopover, setMetaPopover] = (0, import_react39.useState)(null);
  const metaPopoverCommitRef = (0, import_react39.useRef)(null);
  const metaPopoverCloseTimerRef = (0, import_react39.useRef)(null);
  const metaPopoverHoverRef = (0, import_react39.useRef)(false);
  const clearLinksPanelCloseTimer = (0, import_react39.useCallback)(() => {
    const timer = linksPanelCloseTimerRef.current;
    if (timer === null) return;
    linksPanelCloseTimerRef.current = null;
    window.clearTimeout(timer);
  }, []);
  const scheduleCloseLinksPanel = (0, import_react39.useCallback)(
    (delayMs) => {
      clearLinksPanelCloseTimer();
      linksPanelCloseTimerRef.current = window.setTimeout(() => {
        linksPanelCloseTimerRef.current = null;
        if (linksPanelPinnedRef.current) return;
        if (linksPanelHoverRef.current) return;
        if (linksPanelIconHoverRef.current) return;
        setLinksPanel(null);
      }, delayMs);
    },
    [clearLinksPanelCloseTimer]
  );
  const closeLinksPanel = (0, import_react39.useCallback)(() => {
    clearLinksPanelCloseTimer();
    linksPanelPinnedRef.current = false;
    linksPanelHoverRef.current = false;
    linksPanelIconHoverRef.current = false;
    setLinksPanel(null);
  }, [clearLinksPanelCloseTimer]);
  const openLinksPanel = (0, import_react39.useCallback)(
    (nodeId, mode = "preview") => {
      if (readOnly) mode = "preview";
      clearLinksPanelCloseTimer();
      linksPanelPinnedRef.current = true;
      setMetaPopover(null);
      setLinksPanel({ nodeId, mode });
    },
    [clearLinksPanelCloseTimer, readOnly]
  );
  const onRequestLinksPanelModeChange = (0, import_react39.useCallback)(
    (mode) => {
      if (readOnly && mode === "edit") return;
      setLinksPanel((prev) => {
        if (!prev) return prev;
        if (prev.mode === mode) return prev;
        return { ...prev, mode };
      });
      if (mode === "edit") {
        linksPanelPinnedRef.current = true;
        setMetaPopover(null);
      }
    },
    [readOnly]
  );
  const onLinksPanelIconHoverChange = (0, import_react39.useCallback)(
    (nodeId, hovered) => {
      if (isEditing) return;
      if (metaPopover?.mode === "edit") return;
      if (linksPanelPinnedRef.current) return;
      linksPanelIconHoverRef.current = hovered;
      if (hovered) {
        clearLinksPanelCloseTimer();
        setLinksPanel({ nodeId, mode: "preview" });
        return;
      }
      scheduleCloseLinksPanel(140);
    },
    [clearLinksPanelCloseTimer, isEditing, metaPopover?.mode, scheduleCloseLinksPanel]
  );
  const onLinksPanelHoverChange = (0, import_react39.useCallback)(
    (hovered) => {
      linksPanelHoverRef.current = hovered;
      if (hovered) {
        clearLinksPanelCloseTimer();
        return;
      }
      if (linksPanelPinnedRef.current) return;
      scheduleCloseLinksPanel(140);
    },
    [clearLinksPanelCloseTimer, scheduleCloseLinksPanel]
  );
  const clearMetaPopoverCloseTimer = (0, import_react39.useCallback)(() => {
    const timer = metaPopoverCloseTimerRef.current;
    if (timer === null) return;
    metaPopoverCloseTimerRef.current = null;
    window.clearTimeout(timer);
  }, []);
  const scheduleCloseMetaPopover = (0, import_react39.useCallback)(
    (delayMs) => {
      clearMetaPopoverCloseTimer();
      metaPopoverCloseTimerRef.current = window.setTimeout(() => {
        metaPopoverCloseTimerRef.current = null;
        if (metaPopoverHoverRef.current) return;
        setMetaPopover((prev) => prev?.mode === "preview" ? null : prev);
      }, delayMs);
    },
    [clearMetaPopoverCloseTimer]
  );
  const openMetaPopover = (0, import_react39.useCallback)(
    (next) => {
      if (readOnly && next.mode === "edit") next = { ...next, mode: "preview" };
      clearMetaPopoverCloseTimer();
      if (next.mode === "edit") {
        linksPanelPinnedRef.current = false;
        setLinksPanel(null);
      }
      setMetaPopover((prev) => {
        if (prev?.mode === "edit") {
          if (prev.nodeId === next.nodeId && prev.kind === next.kind) return prev;
          return next;
        }
        if (prev && prev.nodeId === next.nodeId && prev.kind === next.kind && prev.mode === next.mode) return prev;
        return next;
      });
    },
    [clearMetaPopoverCloseTimer, readOnly]
  );
  const closeMetaPopover = (0, import_react39.useCallback)(() => {
    clearMetaPopoverCloseTimer();
    setMetaPopover(null);
  }, [clearMetaPopoverCloseTimer]);
  const onMetaPopoverHoverChange = (0, import_react39.useCallback)(
    (hovered) => {
      metaPopoverHoverRef.current = hovered;
      if (hovered) clearMetaPopoverCloseTimer();
      else if (metaPopover?.mode === "preview") scheduleCloseMetaPopover(140);
    },
    [clearMetaPopoverCloseTimer, metaPopover?.mode, scheduleCloseMetaPopover]
  );
  const onRequestMetaPopoverModeChange = (0, import_react39.useCallback)(
    (mode) => {
      if (!metaPopover) return;
      if (readOnly && mode === "edit") return;
      openMetaPopover({ ...metaPopover, mode });
    },
    [metaPopover, openMetaPopover, readOnly]
  );
  const onNodePointerMove = (0, import_react39.useCallback)(
    (nodeId, event) => {
      if (isEditing) return;
      if (metaPopover?.mode === "edit") return;
      if (linksPanelPinnedRef.current) return;
      if (!isElementLike(event.target)) return;
      const actionEl = event.target.closest("[data-km-action]");
      const action = actionEl?.getAttribute("data-km-action") ?? "";
      if (action === "links.open") {
        clearLinksPanelCloseTimer();
        linksPanelIconHoverRef.current = true;
        setMetaPopover((prev) => prev?.mode === "preview" ? null : prev);
        setLinksPanel({ nodeId, mode: "preview" });
        return;
      }
      const kind = action === "notes.open" ? "notes" : action === "comments.open" ? "comments" : null;
      if (kind) {
        clearLinksPanelCloseTimer();
        linksPanelPinnedRef.current = false;
        linksPanelHoverRef.current = false;
        linksPanelIconHoverRef.current = false;
        setLinksPanel(null);
        openMetaPopover({ kind, nodeId, mode: "preview" });
        return;
      }
      if (linksPanel?.mode === "preview" && linksPanel.nodeId === nodeId && linksPanelCloseTimerRef.current === null) {
        linksPanelIconHoverRef.current = false;
        scheduleCloseLinksPanel(140);
      }
      if (metaPopover?.mode === "preview" && metaPopover.nodeId === nodeId && metaPopoverCloseTimerRef.current === null) {
        scheduleCloseMetaPopover(140);
      }
    },
    [clearLinksPanelCloseTimer, isEditing, linksPanel?.mode, linksPanel?.nodeId, metaPopover, openMetaPopover, scheduleCloseLinksPanel, scheduleCloseMetaPopover]
  );
  const onNodeHoverChange = (0, import_react39.useCallback)(
    (nodeId) => {
      if (nodeId) return;
      if (!linksPanelPinnedRef.current) {
        linksPanelIconHoverRef.current = false;
        if (linksPanel?.mode === "preview") scheduleCloseLinksPanel(140);
      }
      if (metaPopover?.mode === "preview") scheduleCloseMetaPopover(140);
    },
    [linksPanel?.mode, metaPopover?.mode, scheduleCloseLinksPanel, scheduleCloseMetaPopover]
  );
  (0, import_react39.useEffect)(() => {
    return () => {
      clearLinksPanelCloseTimer();
      clearMetaPopoverCloseTimer();
    };
  }, [clearLinksPanelCloseTimer, clearMetaPopoverCloseTimer]);
  (0, import_react39.useEffect)(() => {
    if (!linksPanel) return;
    if (doc3.nodes[linksPanel.nodeId]) return;
    setLinksPanel(null);
  }, [doc3.nodes, linksPanel]);
  (0, import_react39.useEffect)(() => {
    if (metaPopover?.mode === "edit") return;
    metaPopoverCommitRef.current = null;
  }, [metaPopover?.kind, metaPopover?.mode, metaPopover?.nodeId]);
  (0, import_react39.useEffect)(() => {
    if (!metaPopover) return;
    if (!doc3.nodes[metaPopover.nodeId]) setMetaPopover(null);
  }, [doc3.nodes, metaPopover]);
  (0, import_react39.useEffect)(() => {
    if (!isEditing) return;
    closeLinksPanel();
    closeMetaPopover();
  }, [closeLinksPanel, closeMetaPopover, isEditing]);
  (0, import_react39.useEffect)(() => {
    if (!readOnly) return;
    setLinksPanel((prev) => prev?.mode === "edit" ? { ...prev, mode: "preview" } : prev);
    setMetaPopover((prev) => prev?.mode === "edit" ? { ...prev, mode: "preview" } : prev);
  }, [readOnly]);
  return {
    linksPanel,
    closeLinksPanel,
    openLinksPanel,
    onRequestLinksPanelModeChange,
    onLinksPanelHoverChange,
    onLinksPanelIconHoverChange,
    metaPopover,
    metaPopoverCommitRef,
    closeMetaPopover,
    openMetaPopover,
    onMetaPopoverHoverChange,
    onRequestMetaPopoverModeChange,
    onNodeHoverChange,
    onNodePointerMove,
    isMetaPopoverEditing: metaPopover?.mode === "edit"
  };
}
function useNodeOverlayPositions(params) {
  const { layout, viewBox, viewportSize, linksPanel, metaPopover } = params;
  const linksPanelPosition = (0, import_react39.useMemo)(() => {
    const nodeId = linksPanel?.nodeId ?? null;
    if (!nodeId) return null;
    const nodeLayout = layout.nodes[nodeId];
    if (!nodeLayout) return null;
    const scaleX = viewportSize.width / viewBox.width;
    const scaleY = viewportSize.height / viewBox.height;
    const nodeLeft = (nodeLayout.x - viewBox.x) * scaleX;
    const nodeTop = (nodeLayout.y - viewBox.y) * scaleY;
    const nodeWidth = nodeLayout.width * scaleX;
    const padding = 12;
    const width = Math.max(1, Math.min(320, viewportSize.width - padding * 2));
    const maxHeight = Math.max(1, Math.min(520, viewportSize.height - padding * 2));
    const preferRight = nodeLeft + nodeWidth + 10 + width + padding <= viewportSize.width;
    const left = clamp3(
      preferRight ? nodeLeft + nodeWidth + 10 : nodeLeft - width - 10,
      padding,
      Math.max(padding, viewportSize.width - padding - width)
    );
    const top = clamp3(nodeTop, padding, Math.max(padding, viewportSize.height - padding - maxHeight));
    return { left, top, width, maxHeight };
  }, [layout.nodes, linksPanel?.nodeId, viewBox.height, viewBox.width, viewBox.x, viewBox.y, viewportSize.height, viewportSize.width]);
  const metaPopoverPosition = (0, import_react39.useMemo)(() => {
    if (!metaPopover) return null;
    const nodeLayout = layout.nodes[metaPopover.nodeId];
    if (!nodeLayout) return null;
    const scaleX = viewportSize.width / viewBox.width;
    const scaleY = viewportSize.height / viewBox.height;
    const nodeLeft = (nodeLayout.x - viewBox.x) * scaleX;
    const nodeTop = (nodeLayout.y - viewBox.y) * scaleY;
    const nodeWidth = nodeLayout.width * scaleX;
    const nodeHeight = nodeLayout.height * scaleY;
    const padding = 12;
    const width = Math.max(1, Math.min(360, viewportSize.width - padding * 2));
    const maxHeight = Math.max(1, Math.min(420, viewportSize.height - padding * 2));
    const preferRight = nodeLeft + nodeWidth + 10 + width + padding <= viewportSize.width;
    const left = clamp3(
      preferRight ? nodeLeft + nodeWidth + 10 : nodeLeft - width - 10,
      padding,
      Math.max(padding, viewportSize.width - padding - width)
    );
    const top = clamp3(nodeTop, padding, Math.max(padding, viewportSize.height - padding - maxHeight));
    return { left, top, width, maxHeight };
  }, [layout.nodes, metaPopover, viewBox.height, viewBox.width, viewBox.x, viewBox.y, viewportSize.height, viewportSize.width]);
  return { linksPanelPosition, metaPopoverPosition };
}

// ../react/src/mindmap-editor/hooks/use-scene-sizes.ts
var import_react40 = __toESM(require_react(), 1);
init_src();

// ../react/src/measure-cache.ts
function makeNodeSizeCacheKey(args) {
  return `${args.maxWidth}::${args.layoutFingerprint}::${args.measureKey}`;
}
function makeSummarySizeCacheKey(args) {
  return `${args.maxWidth}::${args.layoutFingerprint}::${args.measureKey}`;
}

// ../react/src/mindmap-editor/hooks/use-scene-sizes.ts
var CARD_V1_COLUMN_GAP = 10;
var CARD_V1_MEDIA_FALLBACK_WIDTH = 160;
var CARD_V1_EMBED_FALLBACK_WIDTH = 180;
var CARD_V1_LEFT_REGION_ITEM_GAP = 8;
var CARD_V1_RIGHT_REGION_ITEM_GAP = 6;
var CARD_V1_NODE_TASK_TOGGLE_WIDTH = 18;
var CARD_V1_META_BUTTON_WIDTH = 18;
var CARD_V1_BUILTIN_ICON_WIDTH = 16;
var CARD_V1_ICON_ROW_GAP = 6;
var nowMs = () => typeof performance !== "undefined" ? performance.now() : Date.now();
function resolveCardV1SideColumnWidths(doc3, nodeId) {
  const node = doc3.nodes[nodeId];
  if (!node) return { left: 0, right: 0 };
  const content = node.content;
  if (!content || content.schemaVersion !== 1) return { left: 0, right: 0 };
  if (content.kind !== "blocks") return { left: 0, right: 0 };
  const leftItems = [];
  const rightItems = [];
  const assets = doc3.assets ?? {};
  for (const block of content.blocks) {
    if (!block) continue;
    if (block.type === "notes" || block.type === "comments") {
      rightItems.push(CARD_V1_META_BUTTON_WIDTH);
      continue;
    }
    if (block.region !== "left" && block.region !== "right") continue;
    const target2 = block.region === "left" ? leftItems : rightItems;
    if (block.type === "image") {
      const asset = assets[block.assetId];
      const assetWidth = asset && asset.kind === "image" ? asset.width : void 0;
      const width = Math.max(20, block.width ?? assetWidth ?? CARD_V1_MEDIA_FALLBACK_WIDTH);
      target2.push(width);
      continue;
    }
    if (block.type === "embed") {
      const width = Math.max(40, block.width ?? CARD_V1_EMBED_FALLBACK_WIDTH);
      target2.push(width);
      continue;
    }
    if (block.type === "tasks") {
      const first2 = block.items[0];
      const isNodeTask = block.items.length === 1 && Boolean(first2) && String(first2?.text ?? "").trim().length === 0;
      if (isNodeTask) target2.push(CARD_V1_NODE_TASK_TOGGLE_WIDTH);
      continue;
    }
    if (block.type === "icons") {
      const count = block.icons.length;
      if (count <= 0) continue;
      const width = count * CARD_V1_BUILTIN_ICON_WIDTH + Math.max(0, count - 1) * CARD_V1_ICON_ROW_GAP;
      target2.push(width);
      continue;
    }
  }
  const sum = (items, gap) => items.reduce((acc, width) => acc + width, 0) + Math.max(0, items.length - 1) * gap;
  return {
    left: sum(leftItems, CARD_V1_LEFT_REGION_ITEM_GAP),
    right: sum(rightItems, CARD_V1_RIGHT_REGION_ITEM_GAP)
  };
}
function useSceneSizes(args) {
  const {
    doc: doc3,
    sharedResources,
    embedRegistry,
    nodeBodyLayout,
    externalLinkPlacement,
    nodeThemeById,
    summaryThemeById,
    backlinksIndex,
    supportsExternal,
    supportsSubmap,
    canGoBack,
    submapBackAnchorNodeId,
    resizeDraft,
    embedResizeDraft,
    editingLayoutMode,
    editing,
    editingDraftSize,
    perfStatsRef
  } = args;
  const sizeCacheRef = (0, import_react40.useRef)(/* @__PURE__ */ new Map());
  const autoMainWidthCacheRef = (0, import_react40.useRef)(/* @__PURE__ */ new Map());
  const summarySizeCacheRef = (0, import_react40.useRef)(/* @__PURE__ */ new Map());
  const resolvedExternalLinkPlacement = externalLinkPlacement ?? "chrome";
  const measurerRef = (0, import_react40.useRef)(null);
  const [measurerVersion, setMeasurerVersion] = (0, import_react40.useState)(0);
  (0, import_react40.useEffect)(() => {
    if (sharedResources) {
      measurerRef.current = sharedResources.measurer;
      sizeCacheRef.current.clear();
      autoMainWidthCacheRef.current.clear();
      summarySizeCacheRef.current.clear();
      setMeasurerVersion((version2) => version2 + 1);
      return;
    }
    const created = createDomNodeContentMeasurer({ cssText: nodeRichTextCssText });
    measurerRef.current = created;
    sizeCacheRef.current.clear();
    autoMainWidthCacheRef.current.clear();
    summarySizeCacheRef.current.clear();
    setMeasurerVersion((version2) => version2 + 1);
    return () => {
      created.destroy();
      measurerRef.current = null;
    };
  }, [sharedResources]);
  const nodeSizes = (0, import_react40.useMemo)(() => {
    const measurer = measurerRef.current;
    if (!measurer) {
      const perf2 = perfStatsRef?.current;
      if (perf2) {
        perf2.measure.nodeSizeMs = 0;
        perf2.measure.nodeSizeScanned = 0;
        perf2.measure.nodeSizeMeasured = 0;
      }
      return {};
    }
    const next = {};
    const startedAt = nowMs();
    let scanned = 0;
    let measured = 0;
    for (const node of Object.values(doc3.nodes)) {
      scanned += 1;
      const draft = resizeDraft?.nodeId === node.id ? resizeDraft : null;
      const embedDraft = embedResizeDraft?.nodeId === node.id ? embedResizeDraft : null;
      const contentWidthState = draft ? resolveNodeContentWidth({ contentWidth: draft.contentWidth ?? void 0, maxWidth: void 0, contentWidthMode: void 0 }) : resolveNodeContentWidth(node);
      const baseMainMaxWidth = clampNodeMainWidth(contentWidthState.width);
      const { hasExclusiveEmbedNode, exclusiveEmbedWidth } = (() => {
        const content = node.content;
        if (!content || content.schemaVersion !== 1 || content.kind !== "blocks") {
          return { hasExclusiveEmbedNode: false, exclusiveEmbedWidth: null };
        }
        const mainEmbeds = content.blocks.filter(
          (block) => block.type === "embed" && block.region === "main"
        );
        if (mainEmbeds.length === 0) return { hasExclusiveEmbedNode: false, exclusiveEmbedWidth: null };
        const hasExclusive = mainEmbeds.some((block) => {
          const props = block.embed.props;
          if (!props || typeof props !== "object" || Array.isArray(props)) return false;
          return props.exclusive === true;
        });
        if (!hasExclusive) return { hasExclusiveEmbedNode: false, exclusiveEmbedWidth: null };
        if (embedDraft && mainEmbeds.some((block) => block.id === embedDraft.blockId)) {
          return { hasExclusiveEmbedNode: true, exclusiveEmbedWidth: embedDraft.width };
        }
        const max = mainEmbeds.reduce((acc, block) => Math.max(acc, Math.max(40, block.width ?? CARD_V1_EMBED_FALLBACK_WIDTH)), 0);
        return { hasExclusiveEmbedNode: true, exclusiveEmbedWidth: max > 0 ? max : null };
      })();
      const mainMaxWidth = clampNodeMainWidth(
        exclusiveEmbedWidth && Number.isFinite(exclusiveEmbedWidth) ? Math.max(baseMainMaxWidth, exclusiveEmbedWidth) : baseMainMaxWidth
      );
      const embedFrame = resolveExclusiveEmbedFrameProfile(node, embedRegistry);
      const paddingX = (() => {
        const value = embedFrame?.layout?.paddingX ?? nodeThemeById[node.id]?.layout?.paddingX;
        if (typeof value !== "number" || !Number.isFinite(value)) return nodePaddingX;
        return Math.max(0, Math.round(value));
      })();
      const paddingY = (() => {
        const value = embedFrame?.layout?.paddingY ?? nodeThemeById[node.id]?.layout?.paddingY;
        if (typeof value !== "number" || !Number.isFinite(value)) return nodePaddingY;
        return Math.max(0, Math.round(value));
      })();
      const effectivePaddingX = hasExclusiveEmbedNode && !(typeof embedFrame?.layout?.paddingX === "number") ? Math.min(paddingX, exclusiveEmbedPaddingX) : paddingX;
      const effectivePaddingY = hasExclusiveEmbedNode && !(typeof embedFrame?.layout?.paddingY === "number") ? Math.min(paddingY, exclusiveEmbedPaddingY) : paddingY;
      const cardSide = nodeBodyLayout === "card-v1" ? resolveCardV1SideColumnWidths(doc3, node.id) : { left: 0, right: 0 };
      const cardRequiredWidth = cardSide.left + cardSide.right + CARD_V1_COLUMN_GAP * 2;
      const measureMaxWidth = (() => {
        if (nodeBodyLayout !== "card-v1") return mainMaxWidth;
        const allowance = Math.max(cardV1SideAllowance, cardRequiredWidth);
        return mainMaxWidth + allowance + effectivePaddingX * 2;
      })();
      const contentWidthMode = contentWidthState.mode;
      const nodeTheme = nodeThemeById[node.id];
      const layoutFingerprint = nodeTheme?.layoutFingerprint ?? "theme:none";
      const effectiveNodeShape = embedFrame?.nodeShape ?? nodeTheme?.nodeShape;
      const embedShapeFingerprint = embedFrame?.nodeShape ? `|embedShape:${[
        embedFrame.nodeShape.type,
        typeof embedFrame.nodeShape.radius === "number" ? embedFrame.nodeShape.radius : "",
        typeof embedFrame.nodeShape.strokeWidth === "number" ? embedFrame.nodeShape.strokeWidth : "",
        typeof embedFrame.nodeShape.dasharray === "string" ? embedFrame.nodeShape.dasharray : ""
      ].join(":")}` : "";
      const embedDraftFingerprint = embedDraft ? `|embedDraft:${embedDraft.blockId}:${embedDraft.width}x${embedDraft.height}` : "";
      const links = getNodeLinks(node);
      const hasChromeTop = (() => {
        if (nodeBodyLayout !== "card-v1") return false;
        const externalCount = links.filter((link) => link.kind === "external").length;
        const hasExternal = resolvedExternalLinkPlacement === "title-leading" ? externalCount > 1 : externalCount > 0;
        const hasInternal = links.some((link) => link.kind === "internal");
        const hasBacklinks = (backlinksIndex[node.id] ?? []).length > 0;
        const showBack = Boolean(supportsSubmap && canGoBack && submapBackAnchorNodeId === node.id);
        const showLocked = Boolean(node.attrs?.locked);
        const showExternal = Boolean(supportsExternal && hasExternal);
        const showLinksPanel = hasInternal || hasBacklinks;
        const showSubmap = Boolean(supportsSubmap && node.subMapId);
        return showBack || showLocked || showExternal || showLinksPanel || showSubmap;
      })();
      const key = makeNodeSizeCacheKey({
        maxWidth: measureMaxWidth,
        layoutFingerprint: `${layoutFingerprint}|body:${nodeBodyLayout}|externalPlacement:${resolvedExternalLinkPlacement}|widthMode:${contentWidthMode}|chromeTop:${hasChromeTop ? "1" : "0"}${embedDraftFingerprint}${embedShapeFingerprint}`,
        measureKey: buildNodeMeasureKey(node, doc3)
      });
      const cached = sizeCacheRef.current.get(node.id);
      if (cached?.key === key) {
        next[node.id] = cached.size;
        continue;
      }
      const sharedCache = sharedResources?.nodeSizeCache;
      const sharedSize = sharedCache?.get(key);
      if (!sharedSize) measured += 1;
      const overrideContent = (() => {
        if (!embedDraft) return void 0;
        const content = node.content;
        if (!content || content.schemaVersion !== 1 || content.kind !== "blocks") return void 0;
        const index = content.blocks.findIndex((block) => block.type === "embed" && block.id === embedDraft.blockId);
        if (index < 0) return void 0;
        const target2 = content.blocks[index];
        if (!target2 || target2.type !== "embed") return void 0;
        const nextBlocks = content.blocks.slice();
        nextBlocks[index] = { ...target2, width: embedDraft.width, height: embedDraft.height };
        return { ...content, blocks: nextBlocks };
      })();
      const html = buildNodeMeasureHtml(
        doc3,
        node.id,
        draft || overrideContent ? { contentWidth: draft?.contentWidth, content: overrideContent } : void 0,
        {
          nodeBodyLayout,
          hasChromeTop,
          leadingExternalLink: resolvedExternalLinkPlacement === "title-leading" ? links.find((link) => link.kind === "external") ? {
            url: "siyuan-preview-measure",
            label: "SiYuan"
          } : null : null
        }
      );
      const baseSize = sharedSize ?? measurer.measure({
        html,
        text: node.text,
        maxWidth: measureMaxWidth,
        options: (() => {
          const base2 = toMeasurerOptions({ layout: nodeTheme?.layout, cssText: nodeRichTextCssText }) ?? {};
          const next2 = { ...base2 };
          next2.paddingX = effectivePaddingX;
          next2.paddingY = effectivePaddingY;
          const align = embedFrame?.layout?.textAlign;
          if (align === "left" || align === "center" || align === "right") next2.textAlign = align;
          else if (hasExclusiveEmbedNode) next2.textAlign = "left";
          const fontFamily = embedFrame?.layout?.fontFamily;
          if (typeof fontFamily === "string" && fontFamily.trim()) next2.fontFamily = fontFamily;
          const fontSize = embedFrame?.layout?.fontSize;
          if (typeof fontSize === "number" && Number.isFinite(fontSize) && fontSize > 0) next2.fontSize = fontSize;
          const fontWeight = embedFrame?.layout?.fontWeight;
          if (typeof fontWeight === "number" && Number.isFinite(fontWeight)) next2.fontWeight = fontWeight;
          const lineHeight = embedFrame?.layout?.lineHeight;
          if (typeof lineHeight === "number" && Number.isFinite(lineHeight) && lineHeight > 0) next2.lineHeight = lineHeight;
          return next2;
        })()
      });
      const size = nodeBodyLayout === "card-v1" ? inflateCardV1NodeSizeForShape(baseSize, effectiveNodeShape) : baseSize;
      sharedCache?.set(key, baseSize);
      sizeCacheRef.current.set(node.id, { key, size });
      next[node.id] = size;
    }
    const perf = perfStatsRef?.current;
    if (perf) {
      perf.measure.nodeSizeMs = nowMs() - startedAt;
      perf.measure.nodeSizeScanned = scanned;
      perf.measure.nodeSizeMeasured = measured;
    }
    return next;
  }, [
    backlinksIndex,
    canGoBack,
    doc3,
    embedRegistry,
    measurerVersion,
    nodeBodyLayout,
    nodeThemeById,
    resizeDraft,
    embedResizeDraft,
    perfStatsRef,
    resolvedExternalLinkPlacement,
    sharedResources,
    supportsExternal,
    supportsSubmap,
    submapBackAnchorNodeId
  ]);
  const summarySizes = (0, import_react40.useMemo)(() => {
    const measurer = measurerRef.current;
    if (!measurer) {
      const perf2 = perfStatsRef?.current;
      if (perf2) {
        perf2.measure.summarySizeMs = 0;
        perf2.measure.summarySizeScanned = 0;
        perf2.measure.summarySizeMeasured = 0;
      }
      return {};
    }
    const next = {};
    const startedAt = nowMs();
    let scanned = 0;
    let measured = 0;
    for (const summary of doc3.summaries) {
      scanned += 1;
      const maxWidth = summary.maxWidth ?? defaultMaxWidth;
      const summaryTheme = summaryThemeById[summary.id];
      const layoutFingerprint = summaryTheme?.layoutFingerprint ?? "theme:none";
      const key = makeSummarySizeCacheKey({ maxWidth, layoutFingerprint, measureKey: buildSummaryMeasureKey(summary) });
      const cached = summarySizeCacheRef.current.get(summary.id);
      if (cached?.key === key) {
        next[summary.id] = cached.size;
        continue;
      }
      const sharedCache = sharedResources?.summarySizeCache;
      const sharedSize = sharedCache?.get(key);
      if (!sharedSize) measured += 1;
      const html = buildSummaryMeasureHtmlFromContent(doc3, summary.id, { content: summary.content, text: summary.text });
      const size = sharedSize ?? measurer.measure({
        html,
        text: summary.text,
        maxWidth,
        options: toMeasurerOptions({ layout: summaryTheme?.layout, cssText: nodeRichTextCssText })
      });
      sharedCache?.set(key, size);
      summarySizeCacheRef.current.set(summary.id, { key, size });
      next[summary.id] = size;
    }
    const perf = perfStatsRef?.current;
    if (perf) {
      perf.measure.summarySizeMs = nowMs() - startedAt;
      perf.measure.summarySizeScanned = scanned;
      perf.measure.summarySizeMeasured = measured;
    }
    return next;
  }, [doc3.summaries, measurerVersion, perfStatsRef, sharedResources, summaryThemeById]);
  const autoMainWidthByNodeId = (0, import_react40.useMemo)(() => {
    const measurer = measurerRef.current;
    if (!measurer) {
      const perf2 = perfStatsRef?.current;
      if (perf2) {
        perf2.measure.autoWidthMs = 0;
        perf2.measure.autoWidthScanned = 0;
        perf2.measure.autoWidthMeasured = 0;
      }
      return {};
    }
    const next = {};
    const startedAt = nowMs();
    let scanned = 0;
    let measured = 0;
    for (const node of Object.values(doc3.nodes)) {
      if (resolveNodeContentWidth(node).mode !== "fixed") continue;
      scanned += 1;
      const embedDraft = embedResizeDraft?.nodeId === node.id ? embedResizeDraft : null;
      const autoContentWidth = resolveNodeAutoContentWidth(node);
      const autoContentWidthState = resolveNodeContentWidth({
        contentWidth: autoContentWidth,
        maxWidth: void 0,
        contentWidthMode: void 0
      });
      const baseMainMaxWidth = clampNodeMainWidth(autoContentWidthState.width);
      const { hasExclusiveEmbedNode, exclusiveEmbedWidth } = (() => {
        const content = node.content;
        if (!content || content.schemaVersion !== 1 || content.kind !== "blocks") {
          return { hasExclusiveEmbedNode: false, exclusiveEmbedWidth: null };
        }
        const mainEmbeds = content.blocks.filter(
          (block) => block.type === "embed" && block.region === "main"
        );
        if (mainEmbeds.length === 0) return { hasExclusiveEmbedNode: false, exclusiveEmbedWidth: null };
        const hasExclusive = mainEmbeds.some((block) => {
          const props = block.embed.props;
          if (!props || typeof props !== "object" || Array.isArray(props)) return false;
          return props.exclusive === true;
        });
        if (!hasExclusive) return { hasExclusiveEmbedNode: false, exclusiveEmbedWidth: null };
        if (embedDraft && mainEmbeds.some((block) => block.id === embedDraft.blockId)) {
          return { hasExclusiveEmbedNode: true, exclusiveEmbedWidth: embedDraft.width };
        }
        const max = mainEmbeds.reduce((acc, block) => Math.max(acc, Math.max(40, block.width ?? CARD_V1_EMBED_FALLBACK_WIDTH)), 0);
        return { hasExclusiveEmbedNode: true, exclusiveEmbedWidth: max > 0 ? max : null };
      })();
      const mainMaxWidth = clampNodeMainWidth(
        exclusiveEmbedWidth && Number.isFinite(exclusiveEmbedWidth) ? Math.max(baseMainMaxWidth, exclusiveEmbedWidth) : baseMainMaxWidth
      );
      const embedFrame = resolveExclusiveEmbedFrameProfile(node, embedRegistry);
      const paddingX = (() => {
        const value = embedFrame?.layout?.paddingX ?? nodeThemeById[node.id]?.layout?.paddingX;
        if (typeof value !== "number" || !Number.isFinite(value)) return nodePaddingX;
        return Math.max(0, Math.round(value));
      })();
      const effectivePaddingX = hasExclusiveEmbedNode && !(typeof embedFrame?.layout?.paddingX === "number") ? Math.min(paddingX, exclusiveEmbedPaddingX) : paddingX;
      const side = nodeBodyLayout === "card-v1" ? resolveCardV1SideColumnWidths(doc3, node.id) : { left: 0, right: 0 };
      const required = side.left + side.right + CARD_V1_COLUMN_GAP * 2;
      const allowance = Math.max(cardV1SideAllowance, required);
      const measureMaxWidth = nodeBodyLayout === "card-v1" ? mainMaxWidth + allowance + effectivePaddingX * 2 : mainMaxWidth;
      const nodeTheme = nodeThemeById[node.id];
      const layoutFingerprint = nodeTheme?.layoutFingerprint ?? "theme:none";
      const effectiveNodeShape = embedFrame?.nodeShape ?? nodeTheme?.nodeShape;
      const embedShapeFingerprint = embedFrame?.nodeShape ? `|embedShape:${[
        embedFrame.nodeShape.type,
        typeof embedFrame.nodeShape.radius === "number" ? embedFrame.nodeShape.radius : "",
        typeof embedFrame.nodeShape.strokeWidth === "number" ? embedFrame.nodeShape.strokeWidth : "",
        typeof embedFrame.nodeShape.dasharray === "string" ? embedFrame.nodeShape.dasharray : ""
      ].join(":")}` : "";
      const embedDraftFingerprint = embedDraft ? `|embedDraft:${embedDraft.blockId}:${embedDraft.width}x${embedDraft.height}` : "";
      const links = getNodeLinks(node);
      const hasChromeTop = (() => {
        if (nodeBodyLayout !== "card-v1") return false;
        const externalCount = links.filter((link) => link.kind === "external").length;
        const hasExternal = resolvedExternalLinkPlacement === "title-leading" ? externalCount > 1 : externalCount > 0;
        const hasInternal = links.some((link) => link.kind === "internal");
        const hasBacklinks = (backlinksIndex[node.id] ?? []).length > 0;
        const showBack = Boolean(supportsSubmap && canGoBack && submapBackAnchorNodeId === node.id);
        if (hasExternal || hasInternal || hasBacklinks || showBack) return true;
        const content = node.content;
        if (!content || content.schemaVersion !== 1 || content.kind !== "blocks") return false;
        return content.blocks.some((block) => block.type === "progress");
      })();
      const measureKey = buildNodeMeasureKey(node, doc3);
      const autoKey = [
        measureKey,
        `body:${nodeBodyLayout}`,
        `externalPlacement:${resolvedExternalLinkPlacement}`,
        `chromeTop:${hasChromeTop ? "1" : "0"}`,
        `auto:${JSON.stringify(autoContentWidth)}`,
        `layout:${layoutFingerprint}`,
        embedDraftFingerprint,
        embedShapeFingerprint
      ].join("|");
      const cached = autoMainWidthCacheRef.current.get(node.id);
      if (cached?.key === autoKey) {
        next[node.id] = cached.width;
        continue;
      }
      measured += 1;
      const html = buildNodeMeasureHtml(
        doc3,
        node.id,
        { contentWidth: autoContentWidth },
        {
          nodeBodyLayout,
          hasChromeTop,
          embedRegistry,
          leadingExternalLink: resolvedExternalLinkPlacement === "title-leading" ? links.find((link) => link.kind === "external") ? {
            url: "siyuan-preview-measure",
            label: "SiYuan"
          } : null : null
        }
      );
      const measuredSize = measurer.measure({
        html,
        text: node.text,
        maxWidth: measureMaxWidth,
        querySelector: ".km-node-region-main",
        options: toMeasurerOptions({ layout: nodeTheme?.layout, cssText: nodeRichTextCssText })
      });
      const width = clampNodeMainWidth(measuredSize.width);
      autoMainWidthCacheRef.current.set(node.id, { key: autoKey, width });
      next[node.id] = width;
    }
    const perf = perfStatsRef?.current;
    if (perf) {
      perf.measure.autoWidthMs = nowMs() - startedAt;
      perf.measure.autoWidthScanned = scanned;
      perf.measure.autoWidthMeasured = measured;
    }
    return next;
  }, [
    backlinksIndex,
    canGoBack,
    doc3,
    embedRegistry,
    embedResizeDraft,
    resolvedExternalLinkPlacement,
    measurerVersion,
    nodeBodyLayout,
    nodeThemeById,
    perfStatsRef,
    sharedResources,
    submapBackAnchorNodeId,
    supportsSubmap
  ]);
  const effectiveNodeSizes = (0, import_react40.useMemo)(() => {
    if (editingLayoutMode !== "live-preview") return nodeSizes;
    if (!editing || editing.type !== "node") return nodeSizes;
    const draft = editingDraftSize;
    if (!draft || draft.nodeId !== editing.id) return nodeSizes;
    const current = nodeSizes[editing.id];
    if (current && current.width === draft.size.width && current.height === draft.size.height) return nodeSizes;
    return { ...nodeSizes, [editing.id]: draft.size };
  }, [editing, editingDraftSize, editingLayoutMode, nodeSizes]);
  return { autoMainWidthByNodeId, effectiveNodeSizes, measurerRef, nodeSizes, summarySizes };
}

// ../react/src/mindmap-editor/hooks/use-selection-state.ts
var import_react41 = __toESM(require_react(), 1);

// ../react/src/mindmap-editor/utils/selection-state.ts
function isSameSelection(a2, b2) {
  if (a2 === b2) return true;
  if (!a2 || !b2) return false;
  return a2.type === b2.type && a2.id === b2.id;
}
function resolveValidSelection(args) {
  const selection = args.selection;
  if (!selection) return null;
  if (selection.type === "node") {
    if (args.doc.nodes[selection.id]) return selection;
    for (const fallbackId of args.selectedNodeIds) {
      if (args.doc.nodes[fallbackId]) return { type: "node", id: fallbackId };
    }
    const rootId = args.doc.roots[0];
    return rootId ? { type: "node", id: rootId } : null;
  }
  if (selection.type === "summary") {
    if (args.doc.summaries.some((summary) => summary.id === selection.id)) return selection;
    const rootId = args.doc.roots[0];
    return rootId ? { type: "node", id: rootId } : null;
  }
  if (selection.type === "relation") {
    if (args.doc.relations.some((rel2) => rel2.id === selection.id)) return selection;
    const rootId = args.doc.roots[0];
    return rootId ? { type: "node", id: rootId } : null;
  }
  return null;
}

// ../react/src/mindmap-editor/hooks/use-selection-state.ts
function useSelectionState(args) {
  const initialSelection = args.initialSelection ?? "root";
  const readOnly = Boolean(args.readOnly);
  const [selection, setSelectionInternal] = (0, import_react41.useState)(() => {
    if (readOnly) return null;
    if (initialSelection === "none") return null;
    return args.doc.roots[0] ? { type: "node", id: args.doc.roots[0] } : null;
  });
  const [hoveredNodeId, setHoveredNodeId] = (0, import_react41.useState)(null);
  const [selectedNodeIds, setSelectedNodeIdsInternal] = (0, import_react41.useState)(() => {
    if (readOnly) return /* @__PURE__ */ new Set();
    if (initialSelection === "none") return /* @__PURE__ */ new Set();
    return args.doc.roots[0] ? /* @__PURE__ */ new Set([args.doc.roots[0]]) : /* @__PURE__ */ new Set();
  });
  const [editing, setEditingInternal] = (0, import_react41.useState)(null);
  const setSelection = (0, import_react41.useCallback)(
    (next) => {
      if (readOnly) return;
      setSelectionInternal(next);
    },
    [readOnly]
  );
  const setSelectedNodeIds = (0, import_react41.useCallback)(
    (next) => {
      if (readOnly) return;
      setSelectedNodeIdsInternal(next);
    },
    [readOnly]
  );
  const setEditing = (0, import_react41.useCallback)(
    (next) => {
      if (readOnly) return;
      setEditingInternal(next);
    },
    [readOnly]
  );
  const lastDocumentIdRef = (0, import_react41.useRef)(args.documentId);
  (0, import_react41.useEffect)(() => {
    if (!args.documentId) return;
    if (lastDocumentIdRef.current === args.documentId) return;
    lastDocumentIdRef.current = args.documentId;
    const rootId = args.doc.roots[0];
    if (readOnly) {
      setSelectionInternal(null);
      setSelectedNodeIdsInternal(/* @__PURE__ */ new Set());
      setEditingInternal(null);
      setHoveredNodeId(null);
      return;
    }
    if (initialSelection === "none") {
      setSelection(null);
      setSelectedNodeIds(/* @__PURE__ */ new Set());
      setEditing(null);
      setHoveredNodeId(null);
      return;
    }
    setSelection(rootId ? { type: "node", id: rootId } : null);
    setSelectedNodeIds(rootId ? /* @__PURE__ */ new Set([rootId]) : /* @__PURE__ */ new Set());
    setEditing(null);
    setHoveredNodeId(null);
  }, [args.doc.roots, args.documentId, initialSelection]);
  (0, import_react41.useEffect)(() => {
    if (readOnly) return;
    const next = resolveValidSelection({ doc: args.doc, selection, selectedNodeIds });
    if (!isSameSelection(next, selection)) setSelection(next);
  }, [args.doc, selection, selectedNodeIds]);
  (0, import_react41.useEffect)(() => {
    if (readOnly) return;
    if (!selection || selection.type !== "node") {
      setSelectedNodeIds((prev) => prev.size === 0 ? prev : /* @__PURE__ */ new Set());
      return;
    }
    setSelectedNodeIds((prev) => {
      if (prev.has(selection.id)) return prev;
      const next = new Set(prev);
      next.add(selection.id);
      return next;
    });
  }, [selection]);
  (0, import_react41.useEffect)(() => {
    if (readOnly) return;
    setSelectedNodeIds((prev) => {
      if (prev.size === 0) return prev;
      let changed = false;
      const next = /* @__PURE__ */ new Set();
      for (const nodeId of prev) {
        if (args.doc.nodes[nodeId]) {
          next.add(nodeId);
        } else {
          changed = true;
        }
      }
      return changed ? next : prev;
    });
  }, [args.doc.nodes]);
  (0, import_react41.useEffect)(() => {
    if (!readOnly) return;
    setSelectionInternal(null);
    setSelectedNodeIdsInternal(/* @__PURE__ */ new Set());
    setEditingInternal(null);
  }, [readOnly]);
  const onSelectionChangeRef = (0, import_react41.useRef)(args.onSelectionChange);
  (0, import_react41.useEffect)(() => {
    onSelectionChangeRef.current = args.onSelectionChange;
  }, [args.onSelectionChange]);
  (0, import_react41.useEffect)(() => {
    onSelectionChangeRef.current?.(selection);
  }, [selection]);
  return {
    selection,
    setSelection,
    hoveredNodeId,
    setHoveredNodeId,
    selectedNodeIds,
    setSelectedNodeIds,
    editing,
    setEditing
  };
}

// ../react/src/mindmap-editor/hooks/use-viewport-size.ts
var import_react42 = __toESM(require_react(), 1);
function useViewportSize(args) {
  const { ref, watch } = args;
  const [viewportSize, setViewportSize] = (0, import_react42.useState)({ width: 1, height: 1 });
  (0, import_react42.useLayoutEffect)(() => {
    const el = ref.current;
    if (!el) return;
    const update = () => {
      const width = Math.max(1, el.clientWidth);
      const height = Math.max(1, el.clientHeight);
      setViewportSize((prev) => prev.width === width && prev.height === height ? prev : { width, height });
    };
    update();
    if (typeof ResizeObserver === "undefined") {
      window.addEventListener("resize", update);
      return () => window.removeEventListener("resize", update);
    }
    const ro = new ResizeObserver(update);
    ro.observe(el);
    return () => ro.disconnect();
  }, [ref, watch]);
  return viewportSize;
}

// ../react/src/mindmap-editor/hooks/use-theme-resolver-env.ts
var import_react43 = __toESM(require_react(), 1);
init_src();
function readHostColorScheme() {
  if (typeof window === "undefined" || typeof document === "undefined") return "light";
  const html = document.documentElement;
  const body = document.body;
  const datasetMode = html.dataset.themeMode ?? body?.dataset?.themeMode ?? null;
  if (datasetMode === "dark" || datasetMode === "light") return datasetMode;
  const hasDarkClass = html.classList.contains("theme-dark") || html.classList.contains("b3-theme-dark") || Boolean(body && (body.classList.contains("theme-dark") || body.classList.contains("b3-theme-dark")));
  if (hasDarkClass) return "dark";
  const hasLightClass = html.classList.contains("theme-light") || html.classList.contains("b3-theme-light") || Boolean(body && (body.classList.contains("theme-light") || body.classList.contains("b3-theme-light")));
  if (hasLightClass) return "light";
  if (typeof window.matchMedia === "function") {
    return window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light";
  }
  return "light";
}
function useThemeResolverEnv(policy) {
  const [systemPrefersDark, setSystemPrefersDark] = (0, import_react43.useState)(false);
  const [hostColorScheme, setHostColorScheme] = (0, import_react43.useState)("light");
  const [now, setNow] = (0, import_react43.useState)(() => /* @__PURE__ */ new Date(0));
  const hostExternalEnabled = policy?.mode === "external" && policy.external.key === HOST_COLOR_SCHEME_EXTERNAL_KEY;
  (0, import_react43.useEffect)(() => {
    if (policy?.mode !== "system") {
      setSystemPrefersDark(false);
      return;
    }
    if (typeof window === "undefined" || typeof window.matchMedia !== "function") return;
    const media = window.matchMedia("(prefers-color-scheme: dark)");
    const update = () => setSystemPrefersDark(Boolean(media.matches));
    update();
    const listener = () => update();
    if ("addEventListener" in media) {
      media.addEventListener("change", listener);
      return () => media.removeEventListener("change", listener);
    }
    media.addListener(listener);
    return () => media.removeListener(listener);
  }, [policy?.mode]);
  (0, import_react43.useEffect)(() => {
    if (!hostExternalEnabled) {
      setHostColorScheme("light");
      return;
    }
    if (typeof window === "undefined" || typeof document === "undefined") return;
    const update = () => setHostColorScheme(readHostColorScheme());
    update();
    const html = document.documentElement;
    const body = document.body;
    const observer = typeof MutationObserver !== "undefined" ? new MutationObserver(() => update()) : null;
    observer?.observe(html, { attributes: true, attributeFilter: ["class", "data-theme-mode"] });
    if (body) observer?.observe(body, { attributes: true, attributeFilter: ["class", "data-theme-mode"] });
    const media = typeof window.matchMedia === "function" ? window.matchMedia("(prefers-color-scheme: dark)") : null;
    const mediaListener = () => update();
    if (media) {
      if ("addEventListener" in media) {
        media.addEventListener("change", mediaListener);
      } else {
        media.addListener(mediaListener);
      }
    }
    return () => {
      observer?.disconnect();
      if (media) {
        if ("removeEventListener" in media) {
          media.removeEventListener("change", mediaListener);
        } else {
          media.removeListener(mediaListener);
        }
      }
    };
  }, [hostExternalEnabled]);
  (0, import_react43.useEffect)(() => {
    if (policy?.mode !== "time") {
      setNow(/* @__PURE__ */ new Date(0));
      return;
    }
    const update = () => setNow(/* @__PURE__ */ new Date());
    update();
    const id = window.setInterval(update, 6e4);
    return () => window.clearInterval(id);
  }, [policy?.mode]);
  return (0, import_react43.useMemo)(
    () => ({
      systemPrefersDark,
      now: policy?.mode === "time" ? now : void 0,
      external: hostExternalEnabled ? { [HOST_COLOR_SCHEME_EXTERNAL_KEY]: hostColorScheme } : void 0
    }),
    [hostColorScheme, hostExternalEnabled, now, policy?.mode, systemPrefersDark]
  );
}

// ../react/src/mindmap-editor/utils/container-layout-type-by-id.ts
function buildResolvedContainerLayoutTypeById(doc3, layout) {
  const summaryById = new Map(doc3.summaries.map((summary) => [summary.id, summary]));
  const memo2 = {};
  const visiting = /* @__PURE__ */ new Set();
  const resolve = (id) => {
    const cached = memo2[id];
    if (cached) return cached;
    if (visiting.has(id)) return "logical-right";
    visiting.add(id);
    const node = doc3.nodes[id];
    if (node) {
      const inherited = node.parentId ? resolve(node.parentId) : node.parentSummaryId ? resolve(node.parentSummaryId) : "logical-right";
      const resolved = (() => {
        if (node.layout) return node.layout;
        if (inherited === "mindmap-both") return node.branchSide === "left" ? "logical-left" : "logical-right";
        if (inherited === "mindmap-both-auto") {
          if (node.branchSide === "left") return "logical-left";
          if (node.branchSide === "right") return "logical-right";
          const parentId = node.parentId;
          const parentRect = parentId ? layout?.nodes[parentId] : null;
          const rect = layout?.nodes[node.id];
          if (parentRect && rect) {
            return rect.x + rect.width / 2 < parentRect.x + parentRect.width / 2 ? "logical-left" : "logical-right";
          }
          return "logical-right";
        }
        if (inherited === "fishbone-left") return "logical-right";
        if (inherited === "fishbone-right") return "logical-left";
        return inherited;
      })();
      memo2[id] = resolved;
      visiting.delete(id);
      return resolved;
    }
    const summary = summaryById.get(id);
    if (summary) {
      const inherited = resolve(String(summary.parentId));
      const resolveSummarySideInMindmapBoth = () => {
        const summaryRect = layout?.summaries?.[summary.id];
        const parentId = String(summary.parentId);
        const parentRect = layout?.nodes?.[parentId] ?? layout?.summaries?.[parentId];
        if (summaryRect && parentRect) {
          const summaryCx = summaryRect.x + summaryRect.width / 2;
          const parentCx = parentRect.x + parentRect.width / 2;
          if (Number.isFinite(summaryCx) && Number.isFinite(parentCx)) {
            return summaryCx < parentCx ? "logical-left" : "logical-right";
          }
        }
        const childIds = Array.isArray(summary.childIds) ? summary.childIds : [];
        if (childIds.length === 0) return null;
        const resolvedSides = childIds.map((childId) => {
          if (typeof childId !== "string") return null;
          const child = doc3.nodes[childId];
          if (!child) return null;
          if (child.branchSide === "left") return "logical-left";
          if (child.branchSide === "right") return "logical-right";
          const parentRect2 = layout?.nodes?.[parentId] ?? layout?.summaries?.[parentId] ?? null;
          const childRect = layout?.nodes?.[child.id] ?? null;
          if (parentRect2 && childRect) {
            const parentCx = parentRect2.x + parentRect2.width / 2;
            const childCx = childRect.x + childRect.width / 2;
            if (Number.isFinite(parentCx) && Number.isFinite(childCx)) {
              return childCx < parentCx ? "logical-left" : "logical-right";
            }
          }
          const resolved2 = resolve(child.id);
          if (resolved2 === "logical-left" || resolved2 === "logical-right") return resolved2;
          return null;
        }).filter((value) => Boolean(value));
        if (resolvedSides.length !== childIds.length) return null;
        const unique = new Set(resolvedSides);
        if (unique.size !== 1) return null;
        return unique.has("logical-left") ? "logical-left" : "logical-right";
      };
      const resolved = (() => {
        if (summary.layout) return summary.layout;
        if (inherited === "mindmap-both" || inherited === "mindmap-both-auto") {
          return resolveSummarySideInMindmapBoth() ?? "logical-right";
        }
        if (inherited === "fishbone-left") return "logical-right";
        if (inherited === "fishbone-right") return "logical-left";
        return inherited;
      })();
      memo2[id] = resolved;
      visiting.delete(id);
      return resolved;
    }
    visiting.delete(id);
    return "logical-right";
  };
  for (const id of Object.keys(doc3.nodes)) {
    resolve(id);
  }
  for (const summary of doc3.summaries) {
    resolve(summary.id);
  }
  return memo2;
}

// ../react/src/mindmap-editor/utils/context-menu-selection.ts
function resolveNodeSelectionForContextMenu(args) {
  if (args.selectedNodeIds.has(args.nodeId)) return args.selectedNodeIds;
  return /* @__PURE__ */ new Set([args.nodeId]);
}

// ../react/src/mindmap-editor/utils/root-create-position.ts
var TEMP_NEW_ROOT_NODE_ID = "__kmind_new_root_measure__";
function measureNewRootSize(args) {
  const maxWidth = clampNodeMainWidth(args.maxWidth ?? defaultMaxWidth);
  const measurer = args.measure ?? null;
  const measurerOptions = toMeasurerOptions({ layout: args.theme.layout, cssText: nodeRichTextCssText });
  const fallback = () => {
    const base2 = {
      width: Math.max(60, Math.round(args.theme.layout.nodeMinWidth ?? 60)),
      height: Math.max(34, Math.round(args.theme.layout.nodeMinHeight ?? 34))
    };
    return args.nodeBodyLayout === "card-v1" ? inflateCardV1NodeSizeForShape(base2, args.theme.nodeShape) : base2;
  };
  if (!measurer) return fallback();
  const tempDoc = {
    ...args.doc,
    nodes: {
      ...args.doc.nodes,
      [TEMP_NEW_ROOT_NODE_ID]: {
        id: TEMP_NEW_ROOT_NODE_ID,
        text: "",
        children: [],
        contentWidth: { mode: "auto", wrapWidth: maxWidth }
      }
    }
  };
  const html = buildNodeMeasureHtml(
    tempDoc,
    TEMP_NEW_ROOT_NODE_ID,
    { contentWidth: { mode: "auto", wrapWidth: maxWidth } },
    { nodeBodyLayout: args.nodeBodyLayout }
  );
  const paddingX = measurerOptions?.paddingX ?? args.theme.layout.paddingX ?? nodePaddingX;
  const measureMaxWidth = args.nodeBodyLayout === "card-v1" ? maxWidth + cardV1SideAllowance + paddingX * 2 : maxWidth;
  const measured = measurer({
    html,
    text: "",
    maxWidth: measureMaxWidth,
    options: measurerOptions
  });
  return args.nodeBodyLayout === "card-v1" ? inflateCardV1NodeSizeForShape(measured, args.theme.nodeShape) : measured;
}
function resolveRootCreatePosition(args) {
  return {
    x: args.center.x - args.size.width / 2,
    y: args.center.y - args.size.height / 2
  };
}

// ../react/src/mindmap-editor/utils/node-content-commit.ts
init_src();
var defaultCreateRichtextBlockId = () => createKmindId("rt");
function resolveNodeContentCommit(params) {
  const richtext = resolveProseMirrorRichtext(params.payloadContent);
  if (!richtext) return params.payloadContent;
  const current = params.currentContent;
  if (!current || current.schemaVersion !== 1 || current.kind !== "blocks") return params.payloadContent;
  let hasRichtextBlock = false;
  const blocks = current.blocks.map((block) => {
    if (block.type !== "richtext") return block;
    if (block.engine !== "prosemirror") return block;
    hasRichtextBlock = true;
    return { ...block, doc: richtext.doc, html: richtext.html };
  });
  if (!hasRichtextBlock) {
    blocks.unshift({
      id: (params.createRichtextBlockId ?? defaultCreateRichtextBlockId)(),
      type: "richtext",
      region: "main",
      order: 0,
      engine: "prosemirror",
      doc: richtext.doc,
      html: richtext.html
    });
  }
  return { ...current, blocks };
}
function resolveProseMirrorRichtext(content) {
  if (content.schemaVersion !== 1) return null;
  if (content.kind === "blocks") {
    const block = content.blocks.find((b2) => b2.type === "richtext");
    if (!block || block.engine !== "prosemirror") return null;
    return { doc: block.doc, html: block.html };
  }
  if (content.kind === "richtext" && content.engine === "prosemirror") {
    return { doc: content.doc, html: content.html };
  }
  return null;
}

// ../react/src/mindmap-editor/utils/rect-spatial-index.ts
function rectsOverlap(a2, b2) {
  return a2.x < b2.x + b2.width && a2.x + a2.width > b2.x && a2.y < b2.y + b2.height && a2.y + a2.height > b2.y;
}
function buildRectSpatialIndex(rects, options) {
  const cellSize = Math.max(1, Math.floor(options.cellSize));
  const cellMap = /* @__PURE__ */ new Map();
  const addToCell = (cellX, cellY, id) => {
    const key = `${cellX},${cellY}`;
    const bucket = cellMap.get(key);
    if (bucket) bucket.push(id);
    else cellMap.set(key, [id]);
  };
  const resolveCellRange = (rect) => {
    const minCellX = Math.floor(rect.x / cellSize);
    const maxCellX = Math.floor((rect.x + rect.width) / cellSize);
    const minCellY = Math.floor(rect.y / cellSize);
    const maxCellY = Math.floor((rect.y + rect.height) / cellSize);
    return { minCellX, maxCellX, minCellY, maxCellY };
  };
  for (const [id, rect] of Object.entries(rects)) {
    const { minCellX, maxCellX, minCellY, maxCellY } = resolveCellRange(rect);
    for (let cx = minCellX; cx <= maxCellX; cx += 1) {
      for (let cy = minCellY; cy <= maxCellY; cy += 1) {
        addToCell(cx, cy, id);
      }
    }
  }
  const query = (rect) => {
    const { minCellX, maxCellX, minCellY, maxCellY } = resolveCellRange(rect);
    const seen = /* @__PURE__ */ new Set();
    const results = [];
    for (let cx = minCellX; cx <= maxCellX; cx += 1) {
      for (let cy = minCellY; cy <= maxCellY; cy += 1) {
        const key = `${cx},${cy}`;
        const bucket = cellMap.get(key);
        if (!bucket) continue;
        for (const id of bucket) {
          if (seen.has(id)) continue;
          seen.add(id);
          results.push(id);
        }
      }
    }
    return results;
  };
  return { cellSize, totalItems: Object.keys(rects).length, query };
}

// ../react/src/mindmap-editor/utils/minimap.ts
function buildMinimapModel(args) {
  const maxPoints = Math.max(1, Math.min(2e3, args.maxPoints ?? 400));
  const roots = Array.isArray(args.roots) ? args.roots.slice() : [];
  const rootSet = new Set(roots);
  const points = [];
  const addNodePoint = (nodeId) => {
    const layout = args.layout.nodes[nodeId];
    if (!layout) return;
    points.push({
      id: nodeId,
      kind: "node",
      x: layout.x + layout.width / 2,
      y: layout.y + layout.height / 2
    });
  };
  const addSummaryPoint = (summaryId) => {
    const summary = args.layout.summaries[summaryId];
    if (!summary) return;
    points.push({
      id: summaryId,
      kind: "summary",
      x: summary.x + summary.width / 2,
      y: summary.y + summary.height / 2
    });
  };
  for (const rootId of roots) {
    if (points.length >= maxPoints) break;
    addNodePoint(rootId);
  }
  const summaryIds = Object.keys(args.layout.summaries);
  for (const summaryId of summaryIds) {
    if (points.length >= maxPoints) break;
    addSummaryPoint(summaryId);
  }
  const nodeIds = Object.keys(args.layout.nodes);
  const remainingIds = nodeIds.filter((id) => !rootSet.has(id));
  const remainingCapacity = Math.max(0, maxPoints - points.length);
  const sampled = remainingIds.length > remainingCapacity;
  if (remainingCapacity > 0) {
    if (remainingIds.length <= remainingCapacity) {
      for (const nodeId of remainingIds) addNodePoint(nodeId);
    } else {
      const step = Math.max(1, Math.ceil(remainingIds.length / remainingCapacity));
      for (let index = 0; index < remainingIds.length && points.length < maxPoints; index += step) {
        const nodeId = remainingIds[index];
        if (!nodeId) continue;
        addNodePoint(nodeId);
      }
    }
  }
  return { bounds: args.layout.bounds, points, roots, sampled };
}

// ../react/src/mindmap-editor/hooks/use-scene-layout.ts
var import_react44 = __toESM(require_react(), 1);
init_src();
var nowMs2 = () => typeof performance !== "undefined" ? performance.now() : Date.now();
function createTidyLayoutCache(maxEntries) {
  return {
    rootSubtrees: /* @__PURE__ */ new Map(),
    nodeSubtrees: /* @__PURE__ */ new Map(),
    summarySubtrees: /* @__PURE__ */ new Map(),
    maxEntries
  };
}
function prepareTidyLayoutCache(cache, options) {
  if (!options.enabled) {
    cache.rootSubtrees.clear();
    cache.nodeSubtrees.clear();
    cache.summarySubtrees.clear();
    return void 0;
  }
  cache.maxEntries = options.maxEntries;
  return cache;
}
function useResolvedEditorLayoutOptions(layoutOptions) {
  return (0, import_react44.useMemo)(() => {
    const base2 = {
      horizontalGap: 90,
      verticalGap: 22,
      rootGap: 80,
      tidy: {
        logicalAlign: "level",
        packing: "relaxed"
      }
    };
    const override = layoutOptions;
    if (!override) return base2;
    return {
      horizontalGap: override.horizontalGap ?? base2.horizontalGap,
      verticalGap: override.verticalGap ?? base2.verticalGap,
      rootGap: override.rootGap ?? base2.rootGap,
      ...override.rootOptions ? { rootOptions: override.rootOptions } : {},
      tidy: {
        logicalAlign: override.tidy?.logicalAlign ?? base2.tidy.logicalAlign,
        packing: override.tidy?.packing ?? base2.tidy.packing
      }
    };
  }, [layoutOptions]);
}
function useBaseSceneLayout(args) {
  const { doc: doc3, nodeSizes, summarySizes, layoutEngine, layoutOptions, layoutCache, perfStatsRef } = args;
  const tidyLayoutCacheRef = (0, import_react44.useRef)(createTidyLayoutCache(layoutCache?.maxEntries));
  const layoutCacheEnabled = layoutCache?.enabled !== false;
  const layoutCacheMaxEntries = layoutCache?.maxEntries;
  return (0, import_react44.useMemo)(() => {
    const startedAt = nowMs2();
    const tidyCache = layoutEngine === "legacy" ? void 0 : prepareTidyLayoutCache(tidyLayoutCacheRef.current, { enabled: layoutCacheEnabled, maxEntries: layoutCacheMaxEntries });
    const result = layoutMindMap(doc3, nodeSizes, summarySizes, {
      horizontalGap: layoutOptions.horizontalGap,
      verticalGap: layoutOptions.verticalGap,
      rootGap: layoutOptions.rootGap,
      rootOptions: layoutOptions.rootOptions,
      engine: layoutEngine ?? "tidy",
      tidy: layoutEngine === "legacy" ? layoutOptions.tidy : { ...layoutOptions.tidy, cache: tidyCache }
    });
    const perf = perfStatsRef?.current;
    if (perf) perf.layout.layoutMs = nowMs2() - startedAt;
    return result;
  }, [doc3, layoutCacheEnabled, layoutCacheMaxEntries, layoutEngine, layoutOptions, nodeSizes, perfStatsRef, summarySizes]);
}
function useDragPreviewLayout(args) {
  const { doc: doc3, dragUi, nodeSizes, summarySizes, layoutEngine, layoutOptions, layoutCache, perfStatsRef } = args;
  const previewIdGenerator = (0, import_react44.useMemo)(() => new DefaultIdGenerator(), []);
  const tidyLayoutCacheRef = (0, import_react44.useRef)(createTidyLayoutCache(layoutCache?.dragPreviewMaxEntries ?? layoutCache?.maxEntries));
  const dragPreviewLayoutCacheEnabled = layoutCache?.dragPreviewEnabled ?? layoutCache?.enabled ?? true;
  const dragPreviewLayoutCacheMaxEntries = layoutCache?.dragPreviewMaxEntries ?? layoutCache?.maxEntries;
  const dragPreviewKey = dragUi && dragUi.kind === "node" && !dragUi.detached && dragUi.intent.kind === "as-sibling" && dragUi.intent.parent.type !== "root" ? `${dragUi.nodeId}::${dragUi.intent.parent.type}:${dragUi.intent.parent.id}:${dragUi.intent.index}:${dragUi.intent.branchSide ?? ""}` : null;
  return (0, import_react44.useMemo)(() => {
    if (!dragPreviewKey) {
      const perf2 = perfStatsRef?.current;
      if (perf2) perf2.layout.dragPreviewLayoutMs = 0;
      return null;
    }
    const startedAt = nowMs2();
    const [nodeIdPart, rest] = dragPreviewKey.split("::");
    const [parentType, parentId, indexPart, branchSidePart] = rest ? rest.split(":") : [];
    const index = Number(indexPart);
    if (!nodeIdPart || parentType !== "node" && parentType !== "summary" || !parentId || !Number.isFinite(index)) {
      const perf2 = perfStatsRef?.current;
      if (perf2) perf2.layout.dragPreviewLayoutMs = nowMs2() - startedAt;
      return null;
    }
    const command2 = parentType === "node" ? {
      type: "move_node",
      payload: {
        nodeId: nodeIdPart,
        to: {
          type: "node",
          parentId,
          index,
          ...branchSidePart === "left" || branchSidePart === "right" ? { branchSide: branchSidePart } : {}
        }
      }
    } : { type: "move_node", payload: { nodeId: nodeIdPart, to: { type: "summary", summaryId: parentId, index } } };
    const applied = applyCommand(doc3, command2, previewIdGenerator);
    if (!applied.result.ok) {
      const perf2 = perfStatsRef?.current;
      if (perf2) perf2.layout.dragPreviewLayoutMs = nowMs2() - startedAt;
      return null;
    }
    const tidyCache = layoutEngine === "legacy" ? void 0 : prepareTidyLayoutCache(tidyLayoutCacheRef.current, {
      enabled: dragPreviewLayoutCacheEnabled,
      maxEntries: dragPreviewLayoutCacheMaxEntries
    });
    const result = layoutMindMap(applied.doc, nodeSizes, summarySizes, {
      horizontalGap: layoutOptions.horizontalGap,
      verticalGap: layoutOptions.verticalGap,
      rootGap: layoutOptions.rootGap,
      rootOptions: layoutOptions.rootOptions,
      engine: layoutEngine ?? "tidy",
      tidy: layoutEngine === "legacy" ? layoutOptions.tidy : { ...layoutOptions.tidy, cache: tidyCache }
    });
    const perf = perfStatsRef?.current;
    if (perf) perf.layout.dragPreviewLayoutMs = nowMs2() - startedAt;
    return result;
  }, [
    doc3,
    dragPreviewKey,
    dragPreviewLayoutCacheEnabled,
    dragPreviewLayoutCacheMaxEntries,
    layoutEngine,
    layoutOptions,
    nodeSizes,
    perfStatsRef,
    previewIdGenerator,
    summarySizes
  ]);
}

// ../react/src/mindmap-editor/hooks/use-editor-model.ts
function useEditorModel(props) {
  const t = useT();
  const state = useMindMapState(props.core);
  const baseDoc = state.document;
  const readOnly = Boolean(props.interaction?.readOnly);
  const embedRegistry = props.embedRegistry ?? defaultEmbedRegistry;
  const nodeBodyLayout = props.nodeBodyLayout ?? "classic";
  const dialog = (0, import_react45.useMemo)(() => props.dialog ?? createFallbackDialogPort(), [props.dialog]);
  const clipboard = (0, import_react45.useMemo)(() => props.clipboard ?? createFallbackClipboardPort(), [props.clipboard]);
  const storage = (0, import_react45.useMemo)(() => props.storage ?? createFallbackStoragePort(), [props.storage]);
  const assetUrls = useAssetUrls({ doc: baseDoc, assetUrls: props.assetUrls });
  const assetObjectUrlById = assetUrls.assetObjectUrlById;
  const assetObjectUrlVersion = assetUrls.version;
  const [collapsedOverrides, setCollapsedOverrides] = (0, import_react45.useState)({});
  (0, import_react45.useEffect)(() => {
    if (readOnly) return;
    setCollapsedOverrides((prev) => Object.keys(prev).length === 0 ? prev : {});
  }, [readOnly]);
  (0, import_react45.useEffect)(() => {
    setCollapsedOverrides({});
  }, [props.documentId]);
  const doc3 = (0, import_react45.useMemo)(() => {
    if (!readOnly) return baseDoc;
    const overrides = collapsedOverrides;
    const overrideKeys = Object.keys(overrides);
    if (overrideKeys.length === 0) return baseDoc;
    const merged = { ...baseDoc.viewState?.collapsedNodeIds ?? {} };
    for (const key of overrideKeys) {
      const nodeId = key;
      const collapsed = overrides[nodeId];
      if (collapsed) merged[nodeId] = true;
      else delete merged[nodeId];
    }
    const nextViewState = { ...baseDoc.viewState ?? {} };
    if (Object.keys(merged).length > 0) nextViewState.collapsedNodeIds = merged;
    else delete nextViewState.collapsedNodeIds;
    return { ...baseDoc, viewState: Object.keys(nextViewState).length > 0 ? nextViewState : void 0 };
  }, [baseDoc, collapsedOverrides, readOnly]);
  const performance2 = props.performance;
  const themeResolveMode = performance2?.themeResolver?.mode ?? "optimized";
  const viewportCullEnabled = Boolean(performance2?.viewportCull?.enabled);
  const viewportCullMargin = Math.max(0, performance2?.viewportCull?.margin ?? 600);
  const viewportCullCellSize = Math.max(200, performance2?.viewportCull?.cellSize ?? 800);
  const nodeHtmlCacheEnabled = performance2?.nodeHtmlCache?.enabled !== false;
  const nodeHtmlCacheMaxEntries = Math.max(0, performance2?.nodeHtmlCache?.maxEntries ?? 2e3);
  const optimizeEmbedMounting = performance2?.optimizeEmbedMounting !== false;
  const layoutCache = performance2?.layoutCache;
  const perfStatsRef = (0, import_react45.useRef)({
    version: 0,
    updatedAt: Date.now(),
    doc: { roots: 0, nodes: 0, summaries: 0, relations: 0, edges: 0 },
    viewport: null,
    culling: { enabled: false, margin: 0, renderedNodes: 0, renderedEdges: 0, renderedSummaries: 0, renderedRelations: 0 },
    nodeHtml: { cacheEnabled: false, cacheEntries: 0, cacheHits: 0, cacheMisses: 0, buildCount: 0 },
    embeds: { mounts: 0 },
    measure: {
      nodeSizeMs: 0,
      nodeSizeScanned: 0,
      nodeSizeMeasured: 0,
      summarySizeMs: 0,
      summarySizeScanned: 0,
      summarySizeMeasured: 0,
      autoWidthMs: 0,
      autoWidthScanned: 0,
      autoWidthMeasured: 0
    },
    layout: {
      engine: props.layoutEngine ?? "tidy",
      layoutMs: 0,
      dragPreviewLayoutMs: 0,
      nodes: 0,
      summaries: 0,
      edges: 0,
      relations: 0,
      bounds: { width: 0, height: 0 },
      previewActive: false
    },
    theme: { mode: themeResolveMode, resolveMs: 0 },
    export: { usesDedicatedExportScene: false, active: false }
  });
  const externalPerfStatsRef = performance2?.perfStatsRef;
  const perfEnabled = Boolean(externalPerfStatsRef);
  (0, import_react45.useEffect)(() => {
    if (externalPerfStatsRef) externalPerfStatsRef.current = perfStatsRef.current;
  }, [externalPerfStatsRef]);
  const svgRef = (0, import_react45.useRef)(null);
  const canvasRef = (0, import_react45.useRef)(null);
  const viewportSize = useViewportSize({ ref: canvasRef, watch: props.canvasHeight });
  const { selection, setSelection, hoveredNodeId, setHoveredNodeId, selectedNodeIds, setSelectedNodeIds, editing, setEditing } = useSelectionState({
    doc: doc3,
    documentId: props.documentId,
    initialSelection: props.initialSelection,
    readOnly,
    onSelectionChange: props.onSelectionChange
  });
  const selectedNodeId = selection?.type === "node" ? selection.id : null;
  const richTextEditorRef = (0, import_react45.useRef)(null);
  const [pendingRelationFromId, setPendingRelationFromId] = (0, import_react45.useState)(null);
  const [internalEditingLayoutMode, setInternalEditingLayoutMode] = (0, import_react45.useState)("stable");
  const [internalDragGhostMode, setInternalDragGhostMode] = (0, import_react45.useState)("light");
  const [internalEditTabEnterBehavior, setInternalEditTabEnterBehavior] = (0, import_react45.useState)("exit");
  const editingLayoutMode = props.editingLayoutMode ?? internalEditingLayoutMode;
  const dragGhostMode = props.dragGhostMode ?? internalDragGhostMode;
  const editTabEnterBehavior = props.editTabEnterBehavior ?? internalEditTabEnterBehavior;
  const [editingDraftSize, setEditingDraftSize] = (0, import_react45.useState)(null);
  const { blurViewState, setBlurViewState } = useBlurViewState({ core: props.core, doc: doc3, storage });
  (0, import_react45.useEffect)(() => {
    setEditingDraftSize(null);
  }, [editing?.type, editing?.id]);
  const [contextMenu, setContextMenu] = (0, import_react45.useState)(null);
  (0, import_react45.useEffect)(() => {
    if (!contextMenu) return;
    if (editing) setContextMenu(null);
  }, [contextMenu, editing]);
  const pendingRevealRef = (0, import_react45.useRef)(null);
  const [resizeDraft, setResizeDraft] = (0, import_react45.useState)(null);
  const [embedResizeDraft, setEmbedResizeDraft] = (0, import_react45.useState)(null);
  const [relationCurveDraft, setRelationCurveDraft] = (0, import_react45.useState)(null);
  const [relationLabelEditing, setRelationLabelEditing] = (0, import_react45.useState)(null);
  const [selectionToolbarHighlightNodeId, setSelectionToolbarHighlightNodeId] = (0, import_react45.useState)(null);
  const [revealHighlightNodeId, setRevealHighlightNodeId] = (0, import_react45.useState)(null);
  const revealHighlightTimerRef = (0, import_react45.useRef)(null);
  const [revealHighlightSummaryId, setRevealHighlightSummaryId] = (0, import_react45.useState)(null);
  const revealHighlightSummaryTimerRef = (0, import_react45.useRef)(null);
  const selectionToolbarPopoverRequestSeqRef = (0, import_react45.useRef)(0);
  const [selectionToolbarPopoverRequest, setSelectionToolbarPopoverRequest] = (0, import_react45.useState)(null);
  const selectionToolbarActionRequestSeqRef = (0, import_react45.useRef)(0);
  const [selectionToolbarActionRequest, setSelectionToolbarActionRequest] = (0, import_react45.useState)(null);
  const closeHoverPeekOverlaysRef = (0, import_react45.useRef)(() => {
  });
  const [relationEndpointsDraft, setRelationEndpointsDraft] = (0, import_react45.useState)(null);
  const spaceDownRef = (0, import_react45.useRef)(false);
  const [spaceDown, setSpaceDown] = (0, import_react45.useState)(false);
  const spaceGestureRef = (0, import_react45.useRef)(null);
  const requestSelectionToolbarPopover = (0, import_react45.useCallback)(
    (request) => {
      try {
        closeHoverPeekOverlaysRef.current();
      } catch {
      }
      selectionToolbarPopoverRequestSeqRef.current += 1;
      setSelectionToolbarPopoverRequest({ requestId: `stp_${selectionToolbarPopoverRequestSeqRef.current}`, ...request });
    },
    []
  );
  const onSelectionToolbarPopoverRequestHandled = (0, import_react45.useCallback)((requestId) => {
    setSelectionToolbarPopoverRequest((prev) => prev?.requestId === requestId ? null : prev);
  }, []);
  const requestSelectionToolbarAction = (0, import_react45.useCallback)((request) => {
    selectionToolbarActionRequestSeqRef.current += 1;
    setSelectionToolbarActionRequest({ requestId: `sta_${selectionToolbarActionRequestSeqRef.current}`, ...request });
  }, []);
  const onSelectionToolbarActionRequestHandled = (0, import_react45.useCallback)((requestId) => {
    setSelectionToolbarActionRequest((prev) => prev?.requestId === requestId ? null : prev);
  }, []);
  (0, import_react45.useEffect)(() => {
    return () => {
      const id = revealHighlightTimerRef.current;
      if (id) {
        revealHighlightTimerRef.current = null;
        try {
          window.clearTimeout(id);
        } catch {
        }
      }
      const summaryId = revealHighlightSummaryTimerRef.current;
      if (summaryId) {
        revealHighlightSummaryTimerRef.current = null;
        try {
          window.clearTimeout(summaryId);
        } catch {
        }
      }
    };
  }, []);
  (0, import_react45.useEffect)(() => {
    setSelectionToolbarPopoverRequest((prev) => {
      if (!prev) return prev;
      if (editing || relationLabelEditing) return null;
      if (!selectedNodeId) return null;
      if (prev.nodeId !== selectedNodeId) return null;
      return prev;
    });
  }, [editing, relationLabelEditing, selectedNodeId]);
  (0, import_react45.useEffect)(() => {
    setSelectionToolbarActionRequest((prev) => {
      if (!prev) return prev;
      if (editing || relationLabelEditing) return null;
      if (!selectedNodeId) return null;
      if (prev.nodeId !== selectedNodeId) return null;
      return prev;
    });
  }, [editing, relationLabelEditing, selectedNodeId]);
  const themeEnv = useThemeResolverEnv(doc3.theme?.appearance);
  const depthIndex = (0, import_react45.useMemo)(() => buildNodeDepthIndex(doc3), [doc3]);
  const baseDocumentTheme = (0, import_react45.useMemo)(() => resolveDocumentTheme(doc3, themeEnv), [doc3, themeEnv]);
  const documentTheme = (0, import_react45.useMemo)(() => {
    const rawOverride = props.canvasBackgroundColor;
    const override = typeof rawOverride === "string" ? rawOverride.trim() : "";
    if (!override) return baseDocumentTheme;
    return {
      ...baseDocumentTheme,
      background: { ...baseDocumentTheme.background ?? {}, color: override }
    };
  }, [baseDocumentTheme, props.canvasBackgroundColor]);
  const documentThemeRef = (0, import_react45.useRef)(documentTheme);
  (0, import_react45.useEffect)(() => {
    documentThemeRef.current = documentTheme;
  }, [documentTheme]);
  const { nodeThemeById, nodeThemeResolveMs } = (0, import_react45.useMemo)(() => {
    const now = () => typeof globalThis.performance !== "undefined" && typeof globalThis.performance.now === "function" ? globalThis.performance.now() : Date.now();
    const startedAt = now();
    const themes = themeResolveMode === "optimized" ? resolveNodeThemes(doc3, themeEnv, { depthIndex }) : (() => {
      const next = {};
      for (const nodeId of Object.keys(doc3.nodes)) {
        next[nodeId] = resolveNodeTheme(doc3, nodeId, themeEnv, { depthIndex });
      }
      return next;
    })();
    const elapsed = now() - startedAt;
    const resolveMs = Number.isFinite(elapsed) ? Math.max(0, Math.round(elapsed * 100) / 100) : 0;
    return { nodeThemeById: themes, nodeThemeResolveMs: resolveMs };
  }, [depthIndex, doc3, themeEnv, themeResolveMode]);
  const rootThemeById = (0, import_react45.useMemo)(() => {
    const next = {};
    for (const rootId of doc3.roots) {
      next[rootId] = resolveRootTheme(doc3, rootId, themeEnv);
    }
    return next;
  }, [doc3.roots, doc3, themeEnv]);
  const summaryThemeById = (0, import_react45.useMemo)(() => {
    const summaryById = new Map(doc3.summaries.map((summary) => [summary.id, summary]));
    const resolveAnchorNodeId = (summaryId) => {
      const visited = /* @__PURE__ */ new Set();
      let cursor = summaryById.get(summaryId);
      while (cursor) {
        if (visited.has(cursor.id)) return null;
        visited.add(cursor.id);
        const parentId = cursor.parentId;
        if (typeof parentId !== "string") return null;
        if (doc3.nodes[parentId]) return parentId;
        cursor = summaryById.get(parentId);
      }
      return null;
    };
    const next = {};
    for (const summary of doc3.summaries) {
      const anchor = resolveAnchorNodeId(summary.id);
      const rootId = anchor ? getNodeRootId(doc3, anchor) : null;
      const theme = rootId ? rootThemeById[rootId] : documentTheme;
      next[summary.id] = theme ?? documentTheme;
    }
    return next;
  }, [doc3, documentTheme, rootThemeById]);
  const supportsExternal = Boolean(props.external);
  const supportsSubmap = Boolean(props.submap);
  const canGoBack = Boolean(props.submap?.canGoBack);
  const submapBackAnchorByDocIdRef = (0, import_react45.useRef)(/* @__PURE__ */ new Map());
  const submapBackAnchorNodeId = (() => {
    if (!supportsSubmap || !canGoBack) return null;
    const override = props.submap?.backAnchorNodeId;
    if (override && doc3.roots.includes(override)) return override;
    const key = props.documentId ?? props.core.id;
    const stored = submapBackAnchorByDocIdRef.current.get(key);
    if (stored && doc3.roots.includes(stored)) return stored;
    const first2 = doc3.roots[0] ?? null;
    if (first2) submapBackAnchorByDocIdRef.current.set(key, first2);
    return first2;
  })();
  const submap = (0, import_react45.useMemo)(() => {
    if (!props.submap) return void 0;
    return { ...props.submap, backAnchorNodeId: submapBackAnchorNodeId ?? void 0 };
  }, [props.submap, submapBackAnchorNodeId]);
  const backlinksIndex = (0, import_react45.useMemo)(() => {
    const local = buildBacklinksIndex(doc3);
    const external = props.backlinksIndex;
    if (!external) return local;
    const merged = {};
    const normalizeDocId = (value) => typeof value === "string" ? value.trim() : "";
    const normalizeRef = (ref) => ({
      docId: normalizeDocId(ref.docId) || void 0,
      nodeId: ref.nodeId
    });
    const addRefs = (nodeId, refs) => {
      const existing = merged[nodeId];
      const list = existing ? existing.slice() : [];
      const seen = new Set(list.map((ref) => `${normalizeDocId(ref.docId)}#${ref.nodeId}`));
      for (const ref of refs) {
        const normalized = normalizeRef(ref);
        const key = `${normalizeDocId(normalized.docId)}#${normalized.nodeId}`;
        if (seen.has(key)) continue;
        seen.add(key);
        list.push(normalized);
      }
      merged[nodeId] = list;
    };
    for (const [nodeId, refs] of Object.entries(external))
      addRefs(nodeId, refs);
    for (const [nodeId, refs] of Object.entries(local))
      addRefs(nodeId, refs);
    return merged;
  }, [doc3, props.backlinksIndex]);
  const { autoMainWidthByNodeId, effectiveNodeSizes, measurerRef, nodeSizes, summarySizes } = useSceneSizes({
    doc: doc3,
    sharedResources: props.sharedResources,
    embedRegistry,
    nodeBodyLayout,
    externalLinkPlacement: props.nodeChrome?.externalLinkPlacement,
    nodeThemeById,
    summaryThemeById,
    backlinksIndex,
    supportsExternal,
    supportsSubmap,
    canGoBack,
    submapBackAnchorNodeId,
    resizeDraft,
    embedResizeDraft,
    editingLayoutMode,
    editing,
    editingDraftSize,
    perfStatsRef: perfEnabled ? perfStatsRef : null
  });
  const editorLayoutOptions = useResolvedEditorLayoutOptions(props.layoutOptions);
  const layout = useBaseSceneLayout({
    doc: doc3,
    nodeSizes: effectiveNodeSizes,
    summarySizes,
    layoutEngine: props.layoutEngine,
    layoutOptions: editorLayoutOptions,
    layoutCache,
    perfStatsRef: perfEnabled ? perfStatsRef : null
  });
  const minimapModel = (0, import_react45.useMemo)(() => buildMinimapModel({ layout, roots: doc3.roots, maxPoints: 400 }), [doc3.roots, layout]);
  const { cameraRef, setCameraVersion, viewBox, viewBoxRef, zoomIn, zoomOut, fitView } = useCamera({
    layout,
    viewportSize,
    scopeId: props.documentId,
    storage: props.storage ?? null,
    persistMode: readOnly ? "zoom-only" : "full"
  });
  const onCameraChangeRef = (0, import_react45.useRef)(props.onCameraChange);
  (0, import_react45.useEffect)(() => {
    onCameraChangeRef.current = props.onCameraChange;
  }, [props.onCameraChange]);
  (0, import_react45.useEffect)(() => {
    onCameraChangeRef.current?.({ ...cameraRef.current, viewBox, viewport: viewportSize });
  }, [cameraRef, viewBox.height, viewBox.width, viewBox.x, viewBox.y]);
  const onMinimapChangeRef = (0, import_react45.useRef)(props.onMinimapChange);
  (0, import_react45.useEffect)(() => {
    onMinimapChangeRef.current = props.onMinimapChange;
  }, [props.onMinimapChange]);
  (0, import_react45.useEffect)(() => {
    onMinimapChangeRef.current?.(minimapModel);
  }, [minimapModel]);
  const {
    svgExportMode,
    setSvgExportMode,
    pngExportMode,
    setPngExportMode,
    exportScope,
    setExportScope,
    hasCollapsedNodes,
    exportExpandedEnabled,
    exportExpandedDoc,
    exportExpandedLayout,
    exportExpandedSvgRef,
    exportActive,
    exportFullActive,
    exportFullSvgRef,
    exportSvgFromCanvas,
    exportPngFromCanvas
  } = useExportController({
    doc: doc3,
    layout,
    effectiveNodeSizes,
    summarySizes,
    layoutEngine: props.layoutEngine,
    layoutOptions: editorLayoutOptions,
    svgRef,
    exportFullSceneEnabled: viewportCullEnabled,
    documentThemeRef
  });
  const containerLayoutTypeById = (0, import_react45.useMemo)(
    () => buildResolvedContainerLayoutTypeById(doc3, layout),
    [doc3, layout]
  );
  const exportExpandedContainerLayoutTypeById = (0, import_react45.useMemo)(
    () => buildResolvedContainerLayoutTypeById(exportExpandedDoc, exportExpandedLayout),
    [exportExpandedDoc, exportExpandedLayout]
  );
  const subtreeExportSvgRef = (0, import_react45.useRef)(null);
  const [subtreeExportNodeId, setSubtreeExportNodeId] = (0, import_react45.useState)(null);
  const subtreeExportSceneRef = (0, import_react45.useRef)(null);
  const subtreeExportDoc = (0, import_react45.useMemo)(() => {
    if (!subtreeExportNodeId) return null;
    const { nodeIds, summaryIds } = collectSubtreeElements(doc3, subtreeExportNodeId);
    const nodes = {};
    for (const nodeId of nodeIds) {
      const node = doc3.nodes[nodeId];
      if (!node) continue;
      nodes[nodeId] = { ...node, children: node.children.filter((childId) => nodeIds.has(childId)) };
    }
    const rootNode = nodes[subtreeExportNodeId];
    if (rootNode) {
      const resolvedLayout = containerLayoutTypeById[subtreeExportNodeId] ?? null;
      nodes[subtreeExportNodeId] = {
        ...rootNode,
        parentId: void 0,
        parentSummaryId: void 0,
        ...resolvedLayout ? { layout: resolvedLayout } : {}
      };
    }
    const summaries = doc3.summaries.filter((summary) => summaryIds.has(summary.id)).map((summary) => ({
      ...summary,
      childIds: summary.childIds.filter((childId) => nodeIds.has(childId)),
      children: summary.children.filter((childId) => nodeIds.has(childId))
    }));
    const relations = doc3.relations.filter((rel2) => {
      const fromInSubtree = rel2.from.kind === "summary" ? summaryIds.has(rel2.from.summaryId) : nodeIds.has(rel2.from.nodeId);
      const toInSubtree = rel2.to.kind === "summary" ? summaryIds.has(rel2.to.summaryId) : nodeIds.has(rel2.to.nodeId);
      return fromInSubtree && toInSubtree;
    });
    const viewState = (() => {
      const current = doc3.viewState;
      if (!current) return void 0;
      const { collapsedNodeIds: _removed, ...rest } = current;
      return Object.keys(rest).length > 0 ? rest : void 0;
    })();
    return {
      ...doc3,
      roots: [subtreeExportNodeId],
      nodes,
      summaries,
      relations,
      rootPositions: { [subtreeExportNodeId]: { x: 0, y: 0 } },
      viewState
    };
  }, [containerLayoutTypeById, doc3, subtreeExportNodeId]);
  const subtreeExportLayout = (0, import_react45.useMemo)(() => {
    if (!subtreeExportNodeId || !subtreeExportDoc) return null;
    const subtreeNodeSizes = {};
    for (const nodeId of Object.keys(subtreeExportDoc.nodes)) {
      const size = effectiveNodeSizes[nodeId];
      if (size) subtreeNodeSizes[nodeId] = size;
    }
    const subtreeSummarySizes = {};
    for (const summary of subtreeExportDoc.summaries) {
      const size = summarySizes[summary.id];
      if (size) subtreeSummarySizes[summary.id] = size;
    }
    return layoutMindMap(subtreeExportDoc, subtreeNodeSizes, subtreeSummarySizes, {
      horizontalGap: editorLayoutOptions.horizontalGap,
      verticalGap: editorLayoutOptions.verticalGap,
      rootGap: editorLayoutOptions.rootGap,
      rootOptions: editorLayoutOptions.rootOptions,
      engine: props.layoutEngine ?? "tidy",
      tidy: editorLayoutOptions.tidy
    });
  }, [effectiveNodeSizes, editorLayoutOptions.horizontalGap, editorLayoutOptions.rootGap, editorLayoutOptions.rootOptions, editorLayoutOptions.tidy, editorLayoutOptions.verticalGap, props.layoutEngine, subtreeExportDoc, subtreeExportNodeId, summarySizes]);
  const subtreeExportContainerLayoutTypeById = (0, import_react45.useMemo)(() => {
    if (!subtreeExportDoc || !subtreeExportLayout) return null;
    return buildResolvedContainerLayoutTypeById(subtreeExportDoc, subtreeExportLayout);
  }, [subtreeExportDoc, subtreeExportLayout]);
  (0, import_react45.useEffect)(() => {
    if (!subtreeExportNodeId || !subtreeExportDoc || !subtreeExportLayout) {
      subtreeExportSceneRef.current = null;
      return;
    }
    subtreeExportSceneRef.current = { nodeId: subtreeExportNodeId, doc: subtreeExportDoc, layout: subtreeExportLayout };
  }, [subtreeExportDoc, subtreeExportLayout, subtreeExportNodeId]);
  const nextFrame = (0, import_react45.useMemo)(
    () => () => new Promise((resolve) => {
      const raf = typeof requestAnimationFrame === "function" ? requestAnimationFrame : (fn) => setTimeout(fn, 16);
      raf(() => resolve());
    }),
    []
  );
  const exportPngSubtreeFromCanvas = (0, import_react45.useMemo)(
    () => async (exportArgs) => {
      const mode = exportArgs.mode === "accurate" ? "accurate" : "fast";
      const scale = Math.max(0.5, Math.min(6, exportArgs.scale ?? 2));
      const nodeId = exportArgs.nodeId;
      try {
        setSubtreeExportNodeId(nodeId);
        for (let i = 0; i < 30; i += 1) {
          await nextFrame();
          const svg2 = subtreeExportSvgRef.current;
          const scene2 = subtreeExportSceneRef.current;
          if (svg2 && scene2 && scene2.nodeId === nodeId) break;
        }
        const svg = subtreeExportSvgRef.current;
        const scene = subtreeExportSceneRef.current;
        if (!svg || !scene || scene.nodeId !== nodeId) throw new Error("Subtree export view is not ready.");
        const theme = documentThemeRef.current;
        const background = theme.background?.color ?? theme.paint.bg;
        return await exportMindMapPngBlob(svg, { doc: scene.doc, layout: scene.layout }, {
          mode,
          scale,
          background,
          padding: exportPadding,
          textStyle: {
            fontFamily: theme.layout.fontFamily,
            fontSize: theme.layout.fontSize,
            lineHeight: theme.layout.lineHeight,
            paddingX: theme.layout.paddingX,
            paddingY: theme.layout.paddingY,
            color: theme.paint.text
          },
          beautify: exportArgs.beautify
        });
      } finally {
        setSubtreeExportNodeId((prev) => prev === nodeId ? null : prev);
      }
    },
    [documentThemeRef, nextFrame, exportPadding]
  );
  const progressByNodeId = (0, import_react45.useMemo)(() => {
    const map2 = {};
    for (const node of Object.values(doc3.nodes)) {
      const content = node.content;
      if (!content || content.schemaVersion !== 1 || content.kind !== "blocks") continue;
      const progressBlock = content.blocks.find(
        (block) => block.type === "progress"
      );
      if (!progressBlock) continue;
      const stats = computeTaskStats(doc3, node.id);
      map2[node.id] = { ...stats, variant: progressBlock.variant ?? "ring" };
    }
    return map2;
  }, [doc3]);
  const editingLayout = editing?.type === "node" ? layout.nodes[editing.id] : editing?.type === "summary" ? layout.summaries[editing.id] : void 0;
  const clearNodeSelection2 = () => {
    setSelectedNodeIds((prev) => prev.size === 0 ? prev : /* @__PURE__ */ new Set());
  };
  const clearSelection = () => {
    if (readOnly) return;
    setSelection(null);
    clearNodeSelection2();
  };
  const selectSingleNode = (nodeId) => {
    if (readOnly) return;
    setSelection({ type: "node", id: nodeId });
    setSelectedNodeIds(/* @__PURE__ */ new Set([nodeId]));
  };
  const selectNodeForContextMenu = (nodeId) => {
    if (readOnly) return;
    setSelection({ type: "node", id: nodeId });
    setSelectedNodeIds((prev) => resolveNodeSelectionForContextMenu({ nodeId, selectedNodeIds: prev }));
  };
  const selectSummary = (summaryId) => {
    if (readOnly) return;
    setSelection({ type: "summary", id: summaryId });
    clearNodeSelection2();
  };
  const selectRelation = (relationId) => {
    if (readOnly) return;
    setSelection({ type: "relation", id: relationId });
    clearNodeSelection2();
  };
  const onRelationLabelDoubleClick = (args) => {
    if (readOnly) return;
    if (editing) return;
    const relation = doc3.relations.find((item) => item.id === args.relationId);
    if (!relation) return;
    selectRelation(args.relationId);
    const initialValue = relation.label?.schemaVersion === 1 && relation.label.kind === "plain-text" ? relation.label.text : "";
    setRelationLabelEditing({ relationId: args.relationId, anchor: args.anchor, initialValue });
  };
  const commitRelationLabelEditing = (text5) => {
    if (readOnly) return;
    const current = relationLabelEditing;
    if (!current) return;
    const nextText = String(text5 ?? "");
    const result = props.core.dispatch({
      type: "set_relation_label",
      payload: {
        relationId: current.relationId,
        label: nextText.trim().length > 0 ? { schemaVersion: 1, kind: "plain-text", text: nextText } : null
      }
    });
    if (!result.ok) {
      void dialog.alert(result.error);
      return;
    }
    setRelationLabelEditing(null);
    focusCanvas();
  };
  const cancelRelationLabelEditing = () => {
    setRelationLabelEditing(null);
    focusCanvas();
  };
  const isMultiSelectModifier = (event) => event.ctrlKey || event.metaKey;
  const startEditNode = (nodeId, options) => {
    if (readOnly) return;
    setRelationLabelEditing(null);
    const node = doc3.nodes[nodeId];
    if (node?.attrs?.locked || node?.attrs?.readonly) {
      void dialog.alert("\u8BE5\u8282\u70B9\u5DF2\u9501\u5B9A/\u53EA\u8BFB\uFF0C\u65E0\u6CD5\u7F16\u8F91\u3002");
      return;
    }
    if (node?.content?.schemaVersion === 1 && node.content.kind === "blocks") {
      const hasExclusiveEmbed = node.content.blocks.some((block) => {
        if (block.type !== "embed") return false;
        if (block.region !== "main") return false;
        const props2 = block.embed.props;
        if (!props2 || typeof props2 !== "object" || Array.isArray(props2)) return false;
        return props2.exclusive === true;
      });
      if (hasExclusiveEmbed) return;
    }
    selectSingleNode(nodeId);
    setEditing({ type: "node", id: nodeId });
    pendingRevealRef.current = options?.reveal === false ? null : { type: "node", id: nodeId };
  };
  const startEditSummary = (summaryId) => {
    if (readOnly) return;
    setRelationLabelEditing(null);
    const summary = doc3.summaries.find((item) => item.id === summaryId);
    if (summary?.attrs?.locked || summary?.attrs?.readonly) {
      void dialog.alert(t("editor.summary.edit.readonly"));
      return;
    }
    selectSummary(summaryId);
    setEditing({ type: "summary", id: summaryId });
    pendingRevealRef.current = { type: "summary", id: summaryId };
  };
  const stopEdit = () => {
    setRelationLabelEditing(null);
    setEditing(null);
    const el = canvasRef.current;
    if (!el) return;
    try {
      el.focus();
    } catch {
    }
  };
  const cancelEdit = () => {
    stopEdit();
  };
  (0, import_react45.useEffect)(() => {
    if (!editing) return;
    if (editing.type === "node" && !doc3.nodes[editing.id]) {
      setRelationLabelEditing(null);
      setEditing(null);
      const el = canvasRef.current;
      if (el) {
        try {
          el.focus();
        } catch {
        }
      }
      return;
    }
    if (editing.type === "summary" && !doc3.summaries.some((item) => item.id === editing.id)) {
      setRelationLabelEditing(null);
      setEditing(null);
      const el = canvasRef.current;
      if (el) {
        try {
          el.focus();
        } catch {
        }
      }
    }
  }, [doc3.nodes, doc3.summaries, editing]);
  const addChild = () => {
    if (!selection) return;
    if (selection.type === "node") {
      const ids = selectedNodeIds.size > 0 ? Array.from(selectedNodeIds) : [selection.id];
      if (ids.length <= 1) {
        const command2 = {
          type: "add_child",
          payload: { parentId: selection.id, node: { text: "" } }
        };
        const result = props.core.dispatch(command2);
        if (!result.ok) {
          void dialog.alert(result.error);
          return;
        }
        if ("createdNodeId" in result) {
          startEditNode(result.createdNodeId);
        }
        return;
      }
      const ordered = [selection.id, ...ids.filter((id) => id !== selection.id)];
      const batch = props.core.dispatchBatch(
        ordered.map((parentId) => ({
          type: "add_child",
          payload: { parentId, node: { text: "" } }
        }))
      );
      if (!batch.ok) {
        void dialog.alert(batch.error);
        return;
      }
      const firstResult = batch.results[0];
      if (firstResult && "createdNodeId" in firstResult) {
        startEditNode(firstResult.createdNodeId);
      }
      return;
    }
    if (selection.type === "summary") {
      const result = props.core.dispatch({
        type: "add_summary_child",
        payload: { summaryId: selection.id, node: { text: "" } }
      });
      if (!result.ok) {
        void dialog.alert(result.error);
        return;
      }
      if ("createdNodeId" in result) {
        startEditNode(result.createdNodeId);
      }
    }
  };
  const addSibling = () => {
    if (!selection) return;
    if (selection.type !== "node") return;
    const node = doc3.nodes[selection.id];
    if (!node) return;
    if (node.parentId) {
      const parent = doc3.nodes[node.parentId];
      if (!parent) return;
      const selectedIndex = parent.children.indexOf(node.id);
      const insertIndex2 = selectedIndex >= 0 ? selectedIndex + 1 : parent.children.length;
      const result2 = props.core.dispatch({
        type: "add_child",
        payload: { parentId: parent.id, node: { text: "" } }
      });
      if (!result2.ok) {
        void dialog.alert(result2.error);
        return;
      }
      if ("createdNodeId" in result2) {
        props.core.dispatch({
          type: "move_node",
          payload: { nodeId: result2.createdNodeId, to: { type: "node", parentId: parent.id, index: insertIndex2 } }
        });
        startEditNode(result2.createdNodeId);
      }
      return;
    }
    if (node.parentSummaryId) {
      const summary = doc3.summaries.find((item) => item.id === node.parentSummaryId);
      if (!summary) return;
      const selectedIndex = summary.children.indexOf(node.id);
      const insertIndex2 = selectedIndex >= 0 ? selectedIndex + 1 : summary.children.length;
      const result2 = props.core.dispatch({
        type: "add_summary_child",
        payload: { summaryId: summary.id, node: { text: "" } }
      });
      if (!result2.ok) {
        void dialog.alert(result2.error);
        return;
      }
      if ("createdNodeId" in result2) {
        props.core.dispatch({
          type: "move_node",
          payload: { nodeId: result2.createdNodeId, to: { type: "summary", summaryId: summary.id, index: insertIndex2 } }
        });
        startEditNode(result2.createdNodeId);
      }
      return;
    }
    const selectedRootIndex = doc3.roots.indexOf(node.id);
    const insertIndex = selectedRootIndex >= 0 ? selectedRootIndex + 1 : doc3.roots.length;
    const result = props.core.dispatch({
      type: "add_root",
      payload: { node: { text: "", maxWidth: defaultMaxWidth } }
    });
    if (!result.ok) {
      void dialog.alert(result.error);
      return;
    }
    if ("createdNodeId" in result) {
      props.core.dispatch({
        type: "move_node",
        payload: { nodeId: result.createdNodeId, to: { type: "root", index: insertIndex } }
      });
      startEditNode(result.createdNodeId);
    }
  };
  const deleteSelected = () => {
    if (!selection) return;
    if (selection.type === "node") {
      const selected = selectedNodeIds.size > 0 ? new Set(selectedNodeIds) : /* @__PURE__ */ new Set([selection.id]);
      const summaryById = new Map(doc3.summaries.map((summary) => [summary.id, summary]));
      const resolveParentNodeId2 = (nodeId) => {
        const node = doc3.nodes[nodeId];
        if (!node) return null;
        if (node.parentId) return node.parentId;
        if (node.parentSummaryId) {
          let cursor = node.parentSummaryId;
          const visited = /* @__PURE__ */ new Set();
          while (cursor) {
            if (visited.has(cursor)) break;
            visited.add(cursor);
            const summary = summaryById.get(cursor);
            if (!summary) break;
            const parentId = summary.parentId;
            if (doc3.nodes[parentId]) return parentId;
            if (typeof parentId === "string") {
              cursor = parentId;
              continue;
            }
            break;
          }
        }
        return null;
      };
      const hasSelectedAncestor = (nodeId) => {
        const visited = /* @__PURE__ */ new Set();
        let cursor = nodeId;
        while (cursor) {
          const parent = resolveParentNodeId2(cursor);
          if (!parent) return false;
          if (selected.has(parent)) return true;
          if (visited.has(parent)) return false;
          visited.add(parent);
          cursor = parent;
        }
        return false;
      };
      const candidates = Array.from(selected).filter((nodeId) => Boolean(doc3.nodes[nodeId]));
      const pruned = candidates.filter((nodeId) => !hasSelectedAncestor(nodeId));
      if (pruned.length === 0) return;
      const nextRoots = doc3.roots.filter((rootId2) => !pruned.includes(rootId2));
      if (nextRoots.length === 0) {
        void dialog.alert("\u81F3\u5C11\u9700\u8981\u4FDD\u7559\u4E00\u4E2A Root \u8282\u70B9\uFF0C\u65E0\u6CD5\u5220\u9664\u6240\u6709 Root\u3002");
        return;
      }
      const nextSelectionId = resolveNextNodeSelectionAfterDelete({
        doc: doc3,
        layout: sceneLayout,
        anchorId: selection.id,
        deletedNodeIds: new Set(pruned)
      });
      const batch = props.core.dispatchBatch(pruned.map((nodeId) => ({ type: "delete_node", payload: { nodeId } })));
      if (!batch.ok) {
        void dialog.alert(batch.error);
        return;
      }
      setPendingRelationFromId(null);
      stopEdit();
      const nextDoc2 = props.core.getState().document;
      const fallbackRoot = nextDoc2.roots.find((id) => Boolean(nextDoc2.nodes[id]));
      const nextId = nextSelectionId && nextDoc2.nodes[nextSelectionId] ? nextSelectionId : fallbackRoot ?? null;
      if (nextId) selectSingleNode(nextId);
      else clearSelection();
      return;
    }
    if (selection.type === "summary") {
      const summaryById = new Map(doc3.summaries.map((summary) => [summary.id, summary]));
      const resolveSummaryAnchorNodeId = (summaryId) => {
        let cursor = summaryById.get(summaryId);
        const visited = /* @__PURE__ */ new Set();
        while (cursor) {
          if (visited.has(cursor.id)) break;
          visited.add(cursor.id);
          const parentId = cursor.parentId;
          if (doc3.nodes[parentId]) return parentId;
          cursor = summaryById.get(parentId);
        }
        return null;
      };
      const nextSelectionId = resolveSummaryAnchorNodeId(selection.id);
      const command3 = {
        type: "delete_summary",
        payload: { summaryId: selection.id }
      };
      const result2 = props.core.dispatch(command3);
      if (!result2.ok) {
        void dialog.alert(result2.error);
        return;
      }
      const nextDoc2 = props.core.getState().document;
      const fallbackRoot = nextDoc2.roots.find((id) => Boolean(nextDoc2.nodes[id]));
      const nextId = nextSelectionId && nextDoc2.nodes[nextSelectionId] ? nextSelectionId : fallbackRoot ?? null;
      if (nextId) selectSingleNode(nextId);
      else clearSelection();
      stopEdit();
      return;
    }
    const command2 = {
      type: "delete_relation",
      payload: { relationId: selection.id }
    };
    const result = props.core.dispatch(command2);
    if (!result.ok) {
      void dialog.alert(result.error);
      return;
    }
    const nextDoc = props.core.getState().document;
    const rootId = nextDoc.roots.find((id) => Boolean(nextDoc.nodes[id]));
    if (rootId) selectSingleNode(rootId);
    else clearSelection();
    stopEdit();
  };
  const addRoot = () => {
    const result = props.core.dispatch({
      type: "add_root",
      payload: { node: { text: "", maxWidth: defaultMaxWidth } }
    });
    if (!result.ok) return;
    if ("createdNodeId" in result) {
      startEditNode(result.createdNodeId);
    }
  };
  const createRootAt = (center3) => {
    if (!Number.isFinite(center3.x) || !Number.isFinite(center3.y)) return;
    focusCanvas();
    const size = measureNewRootSize({
      doc: doc3,
      nodeBodyLayout,
      theme: baseDocumentTheme,
      measure: measurerRef.current?.measure,
      maxWidth: defaultMaxWidth
    });
    const position = resolveRootCreatePosition({ center: center3, size });
    const result = props.core.dispatch({
      type: "add_root",
      payload: { node: { text: "", maxWidth: defaultMaxWidth }, position }
    });
    if (!result.ok) return;
    if ("createdNodeId" in result) {
      startEditNode(result.createdNodeId, { reveal: false });
    }
  };
  const undo2 = () => {
    const result = props.core.dispatch({ type: "undo" });
    if (!result.ok) {
      void dialog.alert(result.error);
    }
  };
  const redo2 = () => {
    const result = props.core.dispatch({ type: "redo" });
    if (!result.ok) {
      void dialog.alert(result.error);
    }
  };
  const getRootId = (nodeId) => {
    let current = nodeId;
    const visited = /* @__PURE__ */ new Set();
    while (current) {
      if (visited.has(current)) break;
      visited.add(current);
      const currentNode = doc3.nodes[current];
      if (!currentNode) break;
      if (!currentNode.parentId && !currentNode.parentSummaryId) return current;
      if (currentNode.parentId) {
        current = currentNode.parentId;
        continue;
      }
      const parentSummary = doc3.summaries.find(
        (item) => item.id === currentNode.parentSummaryId
      );
      if (!parentSummary) break;
      current = parentSummary.parentId;
    }
    return null;
  };
  const moveRoot = (direction) => {
    if (selection?.type !== "node") return;
    const rootId = getRootId(selection.id);
    if (!rootId) return;
    props.core.dispatch({ type: "move_root", payload: { rootId, direction } });
  };
  const toggleLayout = () => {
    if (!selection) return;
    if (selection.type === "node") {
      const node = doc3.nodes[selection.id];
      if (!node) return;
      const next = node.layout === "tree-down" ? "logical-right" : "tree-down";
      props.core.dispatch({ type: "set_node_layout", payload: { nodeId: selection.id, layout: next } });
      return;
    }
    if (selection.type === "summary") {
      const summary = doc3.summaries.find((item) => item.id === selection.id);
      if (!summary) return;
      const next = summary.layout === "tree-down" ? "logical-right" : "tree-down";
      props.core.dispatch({ type: "set_summary_layout", payload: { summaryId: selection.id, layout: next } });
    }
  };
  const createSummary = () => {
    if (selection?.type !== "node") return;
    const rawChildIds = selectedNodeIds.size > 0 ? Array.from(selectedNodeIds) : [selection.id];
    const childIds = rawChildIds.filter((nodeId) => Boolean(doc3.nodes[nodeId]));
    if (childIds.length === 0) return;
    const firstId = childIds[0];
    if (!firstId) return;
    const firstNode = doc3.nodes[firstId];
    if (!firstNode) return;
    const parentId = firstNode.parentId ?? firstNode.parentSummaryId;
    if (!parentId) {
      void dialog.alert(t("editor.summary.create.error.rootUnsupported"));
      return;
    }
    for (const nodeId of childIds) {
      const node = doc3.nodes[nodeId];
      if (!node) continue;
      const containerId = node.parentId ?? node.parentSummaryId;
      if (containerId !== parentId) {
        void dialog.alert(t("editor.summary.create.error.siblingContainerRequired"));
        return;
      }
    }
    const result = props.core.dispatch({
      type: "create_summary",
      payload: { parentId, childIds, summary: { text: "", maxWidth: defaultMaxWidth } }
    });
    if (result.ok && "createdSummaryId" in result) {
      startEditSummary(result.createdSummaryId);
    } else if (!result.ok) {
      void dialog.alert(result.error);
    }
  };
  const startRelation = () => {
    if (selection?.type === "node") {
      setPendingRelationFromId({ kind: "node", nodeId: selection.id, port: "right" });
      return;
    }
    if (selection?.type === "summary") {
      setPendingRelationFromId({ kind: "summary", summaryId: selection.id, port: "right" });
    }
  };
  const {
    linksPanel,
    closeLinksPanel,
    openLinksPanel,
    onRequestLinksPanelModeChange,
    onLinksPanelHoverChange,
    onLinksPanelIconHoverChange,
    metaPopover,
    metaPopoverCommitRef,
    closeMetaPopover,
    openMetaPopover,
    onMetaPopoverHoverChange,
    onRequestMetaPopoverModeChange,
    onNodeHoverChange: onOverlayNodeHoverChange,
    onNodePointerMove: onOverlayNodePointerMove,
    isMetaPopoverEditing
  } = useNodeOverlays({
    doc: doc3,
    isEditing: Boolean(editing) || Boolean(relationLabelEditing),
    readOnly
  });
  (0, import_react45.useEffect)(() => {
    closeHoverPeekOverlaysRef.current = () => {
      closeLinksPanel();
      closeMetaPopover();
    };
  }, [closeLinksPanel, closeMetaPopover]);
  const focusCanvas = () => {
    const el = canvasRef.current;
    if (!el) return;
    try {
      el.focus();
    } catch {
    }
  };
  const {
    dragUi,
    isPanning,
    marqueeRect,
    onNodePointerDown,
    onSummaryPointerDown,
    onNodeResizeHandlePointerDown,
    onRelationControlHandlePointerDown,
    onSvgPointerCancel,
    onSvgPointerDownCapture,
    onSvgPointerMove,
    onSvgPointerUp
  } = useCanvasGestures({
    core: props.core,
    dialog,
    external: props.external,
    crossPaneDrag: props.crossPaneDrag,
    onNodeAction: props.onNodeAction,
    readOnly,
    doc: doc3,
    layout,
    containerLayoutTypeById,
    autoMainWidthByNodeId,
    svgRef,
    viewBoxRef,
    cameraRef,
    setCameraVersion,
    focusCanvas,
    stopEdit,
    startEditNode,
    startEditSummary,
    onBlankDoublePress: props.interaction?.blankDoubleClickAction === "add-root" ? (center3) => {
      createRootAt({ x: center3.x, y: center3.y });
    } : void 0,
    selection,
    setSelection,
    selectedNodeIds,
    setSelectedNodeIds,
    setHoveredNodeId,
    setResizeDraft,
    setEmbedResizeDraft,
    setRelationCurveDraft,
    setRelationEndpointsDraft,
    pendingRelationFromId,
    setPendingRelationFromId,
    isEditing: Boolean(editing) || Boolean(relationLabelEditing),
    isMetaPopoverEditing,
    openMetaPopover,
    requestSelectionToolbarPopover: props.appUi ? requestSelectionToolbarPopover : void 0,
    setBlurViewState,
    spaceDownRef,
    spaceGestureRef,
    clearSelection,
    selectSingleNode,
    selectSummary
  });
  const wheelZoomDisabledRef = (0, import_react45.useRef)(false);
  const lastPointerRatioRef = (0, import_react45.useRef)(null);
  (0, import_react45.useEffect)(() => {
    wheelZoomDisabledRef.current = Boolean(editing) || Boolean(relationLabelEditing) || isMetaPopoverEditing;
  }, [editing, isMetaPopoverEditing, relationLabelEditing]);
  (0, import_react45.useEffect)(() => {
    const svg = svgRef.current;
    if (!svg) return;
    const updateRatio = (clientX, clientY, target2) => {
      if (!isNodeLike(target2)) return;
      if (!svg.contains(target2)) return;
      const rect = svg.getBoundingClientRect();
      if (!rect.width || !rect.height) return;
      const ratioX = (clientX - rect.left) / rect.width;
      const ratioY = (clientY - rect.top) / rect.height;
      if (!Number.isFinite(ratioX) || !Number.isFinite(ratioY)) return;
      lastPointerRatioRef.current = {
        x: Math.max(0, Math.min(1, ratioX)),
        y: Math.max(0, Math.min(1, ratioY))
      };
    };
    const onPointerMove = (event) => updateRatio(event.clientX, event.clientY, event.target);
    const onPointerDown = (event) => updateRatio(event.clientX, event.clientY, event.target);
    svg.addEventListener("pointermove", onPointerMove, { passive: true });
    svg.addEventListener("pointerdown", onPointerDown, { passive: true });
    return () => {
      svg.removeEventListener("pointermove", onPointerMove);
      svg.removeEventListener("pointerdown", onPointerDown);
    };
  }, [svgRef]);
  (0, import_react45.useEffect)(() => {
    const svg = svgRef.current;
    if (!svg) return;
    const isInteractiveTarget = (target2) => {
      if (!isElementLike(target2)) return false;
      return Boolean(target2.closest("[data-node-id],[data-summary-id],[data-relation-id]"));
    };
    const onWheel = (event) => {
      if (wheelZoomDisabledRef.current) return;
      if (event.defaultPrevented) return;
      if (isInteractiveTarget(event.target)) return;
      event.preventDefault();
      event.stopPropagation();
      const rect = svg.getBoundingClientRect();
      if (!rect.width || !rect.height) return;
      const ratioX = (event.clientX - rect.left) / rect.width;
      const ratioY = (event.clientY - rect.top) / rect.height;
      if (!Number.isFinite(ratioX) || !Number.isFinite(ratioY)) return;
      lastPointerRatioRef.current = {
        x: Math.max(0, Math.min(1, ratioX)),
        y: Math.max(0, Math.min(1, ratioY))
      };
      let deltaY = event.deltaY;
      if (event.deltaMode === WheelEvent.DOM_DELTA_LINE) deltaY *= 16;
      if (event.deltaMode === WheelEvent.DOM_DELTA_PAGE) deltaY *= rect.height;
      if (!Number.isFinite(deltaY) || deltaY === 0) return;
      const zoomFactor = Math.exp(-deltaY / 320);
      const current = cameraRef.current;
      const nextZoom = clampCameraZoom(current.zoom * zoomFactor);
      if (Math.abs(nextZoom - current.zoom) < 1e-5) return;
      const nextCamera = resolveAnchoredCamera({
        current,
        currentView: viewBoxRef.current,
        viewport: viewportSize,
        nextZoom,
        anchorRatio: { x: ratioX, y: ratioY }
      });
      cameraRef.current = nextCamera;
      const nextView = resolveViewBoxFromCamera(nextCamera, viewportSize);
      viewBoxRef.current = nextView;
      setSvgViewBox(svg, nextView);
      setCameraVersion((version2) => version2 + 1);
    };
    svg.addEventListener("wheel", onWheel, { passive: false });
    return () => {
      svg.removeEventListener("wheel", onWheel);
    };
  }, [cameraRef, setCameraVersion, viewportSize, viewBoxRef]);
  const zoomTo = (0, import_react45.useCallback)(
    (nextZoomRaw) => {
      const svg = svgRef.current;
      if (!svg) return;
      if (viewportSize.width <= 1 || viewportSize.height <= 1) return;
      const nextZoom = clampCameraZoom(nextZoomRaw);
      const current = cameraRef.current;
      if (Math.abs(nextZoom - current.zoom) < 1e-5) return;
      const ratio = lastPointerRatioRef.current ?? { x: 0.5, y: 0.5 };
      const nextCamera = resolveAnchoredCamera({
        current,
        currentView: viewBoxRef.current,
        viewport: viewportSize,
        nextZoom,
        anchorRatio: ratio
      });
      cameraRef.current = nextCamera;
      const nextView = resolveViewBoxFromCamera(nextCamera, viewportSize);
      viewBoxRef.current = nextView;
      setSvgViewBox(svg, nextView);
      setCameraVersion((version2) => version2 + 1);
    },
    [cameraRef, setCameraVersion, svgRef, viewportSize.height, viewportSize.width, viewBoxRef]
  );
  const panTo = (0, import_react45.useCallback)(
    (args) => {
      const svg = svgRef.current;
      if (!svg) return;
      if (viewportSize.width <= 1 || viewportSize.height <= 1) return;
      const current = cameraRef.current;
      const viewWidth = viewportSize.width / current.zoom;
      const viewHeight = viewportSize.height / current.zoom;
      const nextCamera = {
        ...current,
        x: Math.round(args.x - viewWidth / 2),
        y: Math.round(args.y - viewHeight / 2)
      };
      cameraRef.current = nextCamera;
      const nextView = resolveViewBoxFromCamera(nextCamera, viewportSize);
      viewBoxRef.current = nextView;
      setSvgViewBox(svg, nextView);
      setCameraVersion((version2) => version2 + 1);
    },
    [cameraRef, setCameraVersion, svgRef, viewportSize.height, viewportSize.width, viewBoxRef]
  );
  const panByViewportDelta = (0, import_react45.useCallback)(
    (args) => {
      const svg = svgRef.current;
      if (!svg) return;
      if (viewportSize.width <= 1 || viewportSize.height <= 1) return;
      if (!Number.isFinite(args.dx) || !Number.isFinite(args.dy)) return;
      if (Math.abs(args.dx) < 0.5 && Math.abs(args.dy) < 0.5) return;
      const current = viewBoxRef.current;
      const next = {
        ...current,
        x: Math.round(current.x + args.dx * (current.width / viewportSize.width)),
        y: Math.round(current.y + args.dy * (current.height / viewportSize.height))
      };
      viewBoxRef.current = next;
      cameraRef.current = { ...cameraRef.current, x: next.x, y: next.y };
      setSvgViewBox(svg, next);
      setCameraVersion((version2) => version2 + 1);
    },
    [cameraRef, setCameraVersion, svgRef, viewportSize.height, viewportSize.width, viewBoxRef]
  );
  const selectNodeAndReveal = (nodeId) => {
    if (!doc3.nodes[nodeId]) return;
    setRevealHighlightNodeId(nodeId);
    if (revealHighlightTimerRef.current) {
      try {
        window.clearTimeout(revealHighlightTimerRef.current);
      } catch {
      }
      revealHighlightTimerRef.current = null;
    }
    try {
      revealHighlightTimerRef.current = window.setTimeout(() => {
        setRevealHighlightNodeId((prev) => prev === nodeId ? null : prev);
      }, 900);
    } catch {
    }
    const summaryById = new Map(doc3.summaries.map((summary) => [summary.id, summary]));
    const collapsedNodeIds = doc3.viewState?.collapsedNodeIds ?? {};
    const expandNodeIds = [];
    const visited = /* @__PURE__ */ new Set();
    let cursor = { kind: "node", id: nodeId };
    while (cursor) {
      const key = `${cursor.kind}:${cursor.id}`;
      if (visited.has(key)) break;
      visited.add(key);
      if (cursor.kind === "node") {
        const currentNode = doc3.nodes[cursor.id];
        if (!currentNode) break;
        if (currentNode.parentId) {
          if (collapsedNodeIds[currentNode.parentId] === true) expandNodeIds.push(currentNode.parentId);
          cursor = { kind: "node", id: currentNode.parentId };
          continue;
        }
        if (currentNode.parentSummaryId) {
          cursor = { kind: "summary", id: currentNode.parentSummaryId };
          continue;
        }
        break;
      }
      const summary = summaryById.get(cursor.id);
      if (!summary) break;
      const parentId = String(summary.parentId);
      if (doc3.nodes[parentId]) {
        if (collapsedNodeIds[parentId] === true) expandNodeIds.push(parentId);
        cursor = { kind: "node", id: parentId };
        continue;
      }
      cursor = { kind: "summary", id: parentId };
    }
    if (expandNodeIds.length > 0) {
      props.core.dispatchBatch(
        Array.from(new Set(expandNodeIds)).map(
          (id) => ({
            type: "set_node_collapsed",
            payload: { nodeId: id, collapsed: false }
          })
        )
      );
    }
    pendingRevealRef.current = { type: "node", id: nodeId };
    selectSingleNode(nodeId);
  };
  const selectSummaryAndReveal = (summaryId) => {
    const summaryById = new Map(doc3.summaries.map((summary) => [summary.id, summary]));
    if (!summaryById.get(summaryId)) return;
    setRevealHighlightSummaryId(summaryId);
    if (revealHighlightSummaryTimerRef.current) {
      try {
        window.clearTimeout(revealHighlightSummaryTimerRef.current);
      } catch {
      }
      revealHighlightSummaryTimerRef.current = null;
    }
    try {
      revealHighlightSummaryTimerRef.current = window.setTimeout(() => {
        setRevealHighlightSummaryId((prev) => prev === summaryId ? null : prev);
      }, 900);
    } catch {
    }
    const collapsedNodeIds = doc3.viewState?.collapsedNodeIds ?? {};
    const expandNodeIds = [];
    const visited = /* @__PURE__ */ new Set();
    let cursor = { kind: "summary", id: summaryId };
    while (cursor) {
      const key = `${cursor.kind}:${cursor.id}`;
      if (visited.has(key)) break;
      visited.add(key);
      if (cursor.kind === "node") {
        const currentNode = doc3.nodes[cursor.id];
        if (!currentNode) break;
        if (currentNode.parentId) {
          if (collapsedNodeIds[currentNode.parentId] === true) expandNodeIds.push(currentNode.parentId);
          cursor = { kind: "node", id: currentNode.parentId };
          continue;
        }
        if (currentNode.parentSummaryId) {
          cursor = { kind: "summary", id: currentNode.parentSummaryId };
          continue;
        }
        break;
      }
      const summary = summaryById.get(cursor.id);
      if (!summary) break;
      const parentId = String(summary.parentId);
      if (doc3.nodes[parentId]) {
        if (collapsedNodeIds[parentId] === true) expandNodeIds.push(parentId);
        cursor = { kind: "node", id: parentId };
        continue;
      }
      cursor = { kind: "summary", id: parentId };
    }
    if (expandNodeIds.length > 0) {
      props.core.dispatchBatch(
        Array.from(new Set(expandNodeIds)).map(
          (id) => ({
            type: "set_node_collapsed",
            payload: { nodeId: id, collapsed: false }
          })
        )
      );
    }
    pendingRevealRef.current = { type: "summary", id: summaryId };
    selectSummary(summaryId);
  };
  const apiSelectNode = (nodeId) => {
    selectNodeAndReveal(nodeId);
  };
  const apiSelectSummary = (summaryId) => {
    selectSummaryAndReveal(summaryId);
  };
  (0, import_react45.useEffect)(() => {
    const apiRef = props.canvasApiRef;
    if (!apiRef) return;
    apiRef.current = {
      zoomIn,
      zoomOut,
      zoomTo,
      panTo,
      fitView,
      focus: focusCanvas,
      selectNode: apiSelectNode,
      selectSummary: apiSelectSummary,
      deleteSelection: () => {
        deleteSelected();
        focusCanvas();
      },
      createSummary,
      startRelation,
      exportSvg: exportSvgFromCanvas,
      exportPng: exportPngFromCanvas,
      exportPngSubtree: exportPngSubtreeFromCanvas,
      startEditNode: (nodeId) => {
        startEditNode(nodeId);
        focusCanvas();
      },
      openNodeMetaPopover: (args) => {
        openMetaPopover(args);
      },
      openSelectedNodeContextMenuAt,
      createRootAt: (center3) => {
        createRootAt({ x: center3.x, y: center3.y });
      }
    };
    return () => {
      apiRef.current = null;
    };
  }, [
    apiSelectNode,
    apiSelectSummary,
    createRootAt,
    createSummary,
    deleteSelected,
    exportPngFromCanvas,
    exportPngSubtreeFromCanvas,
    exportSvgFromCanvas,
    fitView,
    focusCanvas,
    openMetaPopover,
    openSelectedNodeContextMenuAt,
    panTo,
    props.canvasApiRef,
    startEditNode,
    startRelation,
    zoomIn,
    zoomOut,
    zoomTo
  ]);
  (0, import_react45.useEffect)(() => {
    if (!relationLabelEditing) return;
    if (doc3.relations.some((item) => item.id === relationLabelEditing.relationId)) return;
    setRelationLabelEditing(null);
  }, [doc3.relations, relationLabelEditing]);
  const previewLayout = useDragPreviewLayout({
    doc: doc3,
    dragUi,
    nodeSizes,
    summarySizes,
    layoutEngine: props.layoutEngine,
    layoutOptions: editorLayoutOptions,
    layoutCache,
    perfStatsRef: perfEnabled ? perfStatsRef : null
  });
  const sceneLayout = previewLayout ?? layout;
  const { linksPanelPosition, metaPopoverPosition } = useNodeOverlayPositions({
    layout: sceneLayout,
    viewBox,
    viewportSize,
    linksPanel,
    metaPopover
  });
  const hiddenNodeIds = dragUi ? new Set(dragUi.subtreeNodeIds) : null;
  const hiddenSummaryIds = dragUi ? new Set(dragUi.subtreeSummaryIds) : null;
  const { onCanvasBlur, onCanvasKeyDownCapture, onCanvasKeyUpCapture } = useCanvasShortcuts({
    core: props.core,
    doc: doc3,
    layout: sceneLayout,
    containerLayoutTypeById,
    selection,
    readOnly,
    isEditing: Boolean(editing) || Boolean(relationLabelEditing),
    isDragging: Boolean(dragUi),
    isPanning,
    pendingRelationFromId,
    setPendingRelationFromId,
    keymapOverride: props.keymapOverride,
    undo: undo2,
    redo: redo2,
    addChild,
    addSibling,
    deleteSelected,
    startEditNode,
    startEditSummary,
    selectSingleNode,
    spaceDownRef,
    setSpaceDown,
    spaceGestureRef
  });
  const viewportCullRect = (0, import_react45.useMemo)(
    () => ({
      x: viewBox.x - viewportCullMargin,
      y: viewBox.y - viewportCullMargin,
      width: viewBox.width + viewportCullMargin * 2,
      height: viewBox.height + viewportCullMargin * 2
    }),
    [viewBox.height, viewBox.width, viewBox.x, viewBox.y, viewportCullMargin]
  );
  const nodeRectIndex = (0, import_react45.useMemo)(
    () => buildRectSpatialIndex(sceneLayout.nodes, { cellSize: viewportCullCellSize }),
    [sceneLayout.nodes, viewportCullCellSize]
  );
  const summaryRectIndex = (0, import_react45.useMemo)(
    () => buildRectSpatialIndex(sceneLayout.summaries, { cellSize: viewportCullCellSize }),
    [sceneLayout.summaries, viewportCullCellSize]
  );
  const visibleNodeIds = (0, import_react45.useMemo)(() => {
    if (!viewportCullEnabled) return null;
    const candidates = nodeRectIndex.query(viewportCullRect);
    const set = /* @__PURE__ */ new Set();
    for (const nodeIdRaw of candidates) {
      const nodeId = nodeIdRaw;
      const rect = sceneLayout.nodes[nodeId];
      if (!rect) continue;
      if (rectsOverlap(rect, viewportCullRect)) set.add(nodeId);
    }
    return set;
  }, [nodeRectIndex, sceneLayout.nodes, viewportCullEnabled, viewportCullRect]);
  const visibleSummaryIds = (0, import_react45.useMemo)(() => {
    if (!viewportCullEnabled) return null;
    const candidates = summaryRectIndex.query(viewportCullRect);
    const set = /* @__PURE__ */ new Set();
    for (const summaryIdRaw of candidates) {
      const summaryId = summaryIdRaw;
      const rect = sceneLayout.summaries[summaryId];
      if (!rect) continue;
      if (rectsOverlap(rect, viewportCullRect)) set.add(summaryId);
    }
    return set;
  }, [sceneLayout.summaries, summaryRectIndex, viewportCullEnabled, viewportCullRect]);
  const closeContextMenu = () => {
    setContextMenu(null);
  };
  const openNodeContextMenuAt = (pos) => {
    if (!props.appUi) return;
    focusCanvas();
    void props.appUi.dispatchCommand("clipboard.refresh");
    setContextMenu({ scope: "node", x: pos.x, y: pos.y, world: null, nodeId: pos.nodeId ?? selectedNodeId ?? null });
  };
  const openSummaryContextMenuAt = (pos) => {
    if (!props.appUi) return;
    focusCanvas();
    selectSummary(pos.summaryId);
    setContextMenu({ scope: "summary", x: pos.x, y: pos.y, world: null, summaryId: pos.summaryId });
  };
  function openSelectedNodeContextMenuAt(pos) {
    if (!props.appUi) return false;
    if (!selectedNodeId) return false;
    const canvas = canvasRef.current;
    if (!canvas) return false;
    const rect = canvas.getBoundingClientRect();
    openNodeContextMenuAt({
      x: pos.clientX - rect.left,
      y: pos.clientY - rect.top,
      nodeId: selectedNodeId
    });
    return true;
  }
  const onCanvasContextMenu = (event) => {
    if (!props.appUi) return;
    if (isTypingTarget(event.target)) return;
    event.preventDefault();
    event.stopPropagation();
    focusCanvas();
    void props.appUi.dispatchCommand("clipboard.refresh");
    const el = canvasRef.current;
    if (!el) return;
    const rect = el.getBoundingClientRect();
    const x5 = event.clientX - rect.left;
    const y = event.clientY - rect.top;
    const svg = svgRef.current;
    const world = svg ? clientToWorldPoint({ svg, viewBox, clientX: event.clientX, clientY: event.clientY }) : null;
    const hitSummary = world ? hitTestSummaryId({ layout: sceneLayout, world, hiddenSummaryIds }) : null;
    if (hitSummary) {
      selectSummary(hitSummary);
      setContextMenu({ scope: "summary", x: x5, y, world, summaryId: hitSummary });
      return;
    }
    const hit = world ? hitTestNodeId({ layout: sceneLayout, world, hiddenNodeIds, ignoreNodeIds: void 0 }) : null;
    if (hit) {
      selectNodeForContextMenu(hit);
      setContextMenu({ scope: "node", x: x5, y, world, nodeId: hit });
      return;
    }
    clearSelection();
    setContextMenu({ scope: "canvas", x: x5, y, world });
  };
  const onSvgDoubleClick = (0, import_react45.useCallback)((event) => {
    if (props.interaction?.blankDoubleClickAction !== "add-root") return;
    if (isTypingTarget(event.target)) return;
    if (editing) return;
    const target2 = event.target;
    if (isElementLike(target2)) {
      if (target2.closest("[data-km-node-resize-handle]")) return;
      if (target2.closest("[data-node-id]")) return;
      if (target2.closest("[data-summary-id]")) return;
      if (target2.closest("[data-relation-id]")) return;
    }
    const svg = svgRef.current;
    if (!svg) return;
    const world = clientToWorldPoint({ svg, viewBox, clientX: event.clientX, clientY: event.clientY });
    if (!world) return;
    const hit = hitTestNodeId({ layout: sceneLayout, world, hiddenNodeIds, ignoreNodeIds: void 0 });
    if (hit) return;
    event.preventDefault();
    event.stopPropagation();
    createRootAt({ x: world.x, y: world.y });
  }, [createRootAt, editing, hiddenNodeIds, props.interaction?.blankDoubleClickAction, sceneLayout, viewBox]);
  const dropHighlight = (() => {
    if (!dragUi || dragUi.kind !== "node") return null;
    if (dragUi.detached) return null;
    if (dragUi.intent.kind === "as-child") {
      return dragUi.intent.target.type === "node" ? { type: "node", id: dragUi.intent.target.id } : { type: "summary", id: dragUi.intent.target.id };
    }
    if (dragUi.intent.kind === "as-sibling") {
      if (dragUi.intent.parent.type === "node") return { type: "node", id: dragUi.intent.parent.id };
      if (dragUi.intent.parent.type === "summary") return { type: "summary", id: dragUi.intent.parent.id };
    }
    return null;
  })();
  const ghostDelta = (() => {
    if (!dragUi) return null;
    const baseline = layout.nodes[dragUi.nodeId];
    if (!baseline) return null;
    return { dx: dragUi.ghost.x - baseline.x, dy: dragUi.ghost.y - baseline.y };
  })();
  const interactionActive = Boolean(dragUi) || isPanning || Boolean(marqueeRect);
  (0, import_react45.useEffect)(() => {
    if (!interactionActive) return;
    const previous = document.body.style.userSelect;
    document.body.style.userSelect = "none";
    return () => {
      document.body.style.userSelect = previous;
    };
  }, [interactionActive]);
  (0, import_react45.useEffect)(() => {
    const pending = pendingRevealRef.current;
    if (!pending) return;
    const targetLayout = pending.type === "node" ? layout.nodes[pending.id] : layout.summaries[pending.id];
    if (!targetLayout) return;
    const padding = 64;
    const current = viewBoxRef.current;
    const left = targetLayout.x;
    const top = targetLayout.y;
    const right = left + targetLayout.width;
    const bottom = top + targetLayout.height;
    const visibleLeft = current.x;
    const visibleTop = current.y;
    const visibleRight = current.x + current.width;
    const visibleBottom = current.y + current.height;
    const isOutside = left < visibleLeft + padding || right > visibleRight - padding || top < visibleTop + padding || bottom > visibleBottom - padding;
    if (isOutside) {
      const next = {
        ...current,
        x: Math.round((left + right) / 2 - current.width / 2),
        y: Math.round((top + bottom) / 2 - current.height / 2)
      };
      viewBoxRef.current = next;
      cameraRef.current = { ...cameraRef.current, x: next.x, y: next.y };
      setSvgViewBox(svgRef.current, next);
      setCameraVersion((version2) => version2 + 1);
    }
    pendingRevealRef.current = null;
  }, [layout, viewBox]);
  const { copyNodeContent, pasteNodeContent, copySubtree, pasteSubtree } = useClipboardController({
    core: props.core,
    doc: doc3,
    dialog,
    clipboard,
    selectedNodeId
  });
  const createId = (0, import_react45.useCallback)((prefix) => {
    return createKmindId(prefix);
  }, []);
  const ensureBlocksContent = (node) => {
    const plainText = node.text;
    const content = node.content;
    if (!content || content.schemaVersion !== 1) return { plainText, content: { schemaVersion: 1, kind: "blocks", blocks: [] } };
    if (content.kind === "blocks") return { plainText, content };
    if (content.kind === "richtext") {
      return {
        plainText,
        content: {
          schemaVersion: 1,
          kind: "blocks",
          blocks: [
            {
              id: createId("rt"),
              type: "richtext",
              region: "main",
              order: 0,
              engine: "prosemirror",
              doc: content.doc,
              html: content.html
            }
          ]
        }
      };
    }
    return { plainText, content: { schemaVersion: 1, kind: "blocks", blocks: [] } };
  };
  const resolveNextOrder = (blocks, region) => {
    let max = -1;
    for (const block of blocks) {
      if (block.region !== region) continue;
      if (typeof block.order !== "number" || !Number.isFinite(block.order)) continue;
      max = Math.max(max, block.order);
    }
    return max + 1;
  };
  const readFileAsDataUrl = async (file) => {
    return await new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.onload = () => resolve(String(reader.result ?? ""));
      reader.onerror = () => reject(new Error("read file failed"));
      reader.readAsDataURL(file);
    });
  };
  const readImageSizeFromDataUrl = async (dataUrl) => {
    if (!dataUrl.startsWith("data:image/")) return null;
    return await new Promise((resolve) => {
      const img = new Image();
      img.onload = () => resolve({ width: img.naturalWidth, height: img.naturalHeight });
      img.onerror = () => resolve(null);
      img.src = dataUrl;
    });
  };
  const pasteImageFile = (0, import_react45.useCallback)(async (file) => {
    const mimeType = typeof file.type === "string" && file.type.length > 0 ? file.type : "image/png";
    const dataUrl = await readFileAsDataUrl(file);
    const size = await readImageSizeFromDataUrl(dataUrl);
    const selectionNodeId = selection?.type === "node" ? selection.id : null;
    const targetNodeId = selectionNodeId;
    if (targetNodeId) {
      const node = doc3.nodes[targetNodeId];
      if (!node) return;
      if (node.attrs?.locked || node.attrs?.readonly) {
        await dialog.alert("\u8BE5\u8282\u70B9\u5DF2\u9501\u5B9A/\u53EA\u8BFB\uFF0C\u65E0\u6CD5\u7C98\u8D34\u56FE\u7247\u3002");
        return;
      }
      if (props.appUi?.dispatchCommand) {
        const bytes = (() => {
          const candidate = file;
          if (typeof candidate.arrayBuffer === "function") return candidate.arrayBuffer();
          return new Promise((resolve, reject) => {
            const reader = new FileReader();
            reader.onload = () => resolve(reader.result);
            reader.onerror = () => reject(new Error("read file failed"));
            reader.readAsArrayBuffer(file);
          });
        })();
        try {
          await props.appUi.dispatchCommand("node.image.paste", {
            nodeId: targetNodeId,
            name: file.name,
            mimeType,
            bytes: new Uint8Array(await bytes),
            width: size?.width,
            height: size?.height
          });
        } catch (error) {
          await dialog.alert(error instanceof Error ? error.message : "\u7C98\u8D34\u56FE\u7247\u5931\u8D25\u3002");
        }
        return;
      }
      const assetId2 = createId("asset");
      const asset2 = {
        id: assetId2,
        kind: "image",
        mimeType,
        dataUrl,
        width: size?.width,
        height: size?.height
      };
      const { content, plainText } = ensureBlocksContent(node);
      const existingImage = content.blocks.find((block2) => block2.type === "image") ?? null;
      const region = existingImage && existingImage.region !== "main" ? existingImage.region : "top";
      const order = existingImage ? existingImage.order : resolveNextOrder(content.blocks, region);
      const nextBlockId = existingImage ? existingImage.id : createId("img");
      const fit = existingImage?.fit ?? "contain";
      const width = existingImage?.width ?? 240;
      const height = existingImage?.height ?? 160;
      const nextBlocks = [
        ...content.blocks.filter((block2) => block2.type !== "image"),
        {
          id: nextBlockId,
          type: "image",
          region,
          order,
          assetId: assetId2,
          alt: file.name,
          fit,
          width,
          height
        }
      ];
      const result2 = props.core.dispatch({
        type: "set_node_content",
        payload: { nodeId: targetNodeId, content: { ...content, blocks: nextBlocks }, plainText, assets: { [assetId2]: asset2 } }
      });
      if (!result2.ok) {
        await dialog.alert(result2.error);
      }
      return;
    }
    if (props.appUi?.dispatchCommand) {
      const bytes = (() => {
        const candidate = file;
        if (typeof candidate.arrayBuffer === "function") return candidate.arrayBuffer();
        return new Promise((resolve, reject) => {
          const reader = new FileReader();
          reader.onload = () => resolve(reader.result);
          reader.onerror = () => reject(new Error("read file failed"));
          reader.readAsArrayBuffer(file);
        });
      })();
      try {
        await props.appUi.dispatchCommand("node.image.pasteAsRoot", {
          name: file.name,
          mimeType,
          bytes: new Uint8Array(await bytes),
          width: size?.width,
          height: size?.height
        });
      } catch (error) {
        await dialog.alert(error instanceof Error ? error.message : "\u7C98\u8D34\u56FE\u7247\u5931\u8D25\u3002");
      }
      return;
    }
    const assetId = createId("asset");
    const asset = {
      id: assetId,
      kind: "image",
      mimeType,
      dataUrl,
      width: size?.width,
      height: size?.height
    };
    const block = {
      id: createId("img"),
      type: "image",
      region: "top",
      order: 0,
      assetId,
      alt: file.name,
      fit: "contain",
      width: 240,
      height: 160
    };
    const subtree = {
      roots: ["img_root"],
      nodes: {
        img_root: {
          id: "img_root",
          children: [],
          text: "",
          content: { schemaVersion: 1, kind: "blocks", blocks: [{ ...block, order: 0 }] }
        }
      },
      assets: { [assetId]: asset }
    };
    const result = props.core.dispatch({
      type: "insert_subtree",
      payload: { parentId: null, subtree }
    });
    if (!result.ok) await dialog.alert(result.error);
  }, [createId, dialog, doc3.nodes, ensureBlocksContent, props.appUi, props.core, selection]);
  const onCanvasCopy = (0, import_react45.useCallback)((event) => {
    if (!props.interaction?.smartPaste) return;
    if (isTypingTarget(event.target)) return;
    if (editing) return;
    const selected = Array.from(selectedNodeIds);
    if (selected.length === 0) return;
    const summaryById = new Map(doc3.summaries.map((summary) => [summary.id, summary]));
    const selectedSet = new Set(selected);
    const isUnderSelectedAncestor = (nodeId) => {
      const visited = /* @__PURE__ */ new Set();
      let cursor = { kind: "node", id: nodeId };
      while (cursor) {
        const key = `${cursor.kind}:${cursor.id}`;
        if (visited.has(key)) break;
        visited.add(key);
        if (cursor.kind === "node") {
          const currentNode = doc3.nodes[cursor.id];
          if (!currentNode) return false;
          if (currentNode.parentId) {
            if (selectedSet.has(currentNode.parentId)) return true;
            cursor = { kind: "node", id: currentNode.parentId };
            continue;
          }
          if (currentNode.parentSummaryId) {
            cursor = { kind: "summary", id: currentNode.parentSummaryId };
            continue;
          }
          return false;
        }
        const summary = summaryById.get(cursor.id);
        if (!summary) return false;
        const parentId = summary.parentId;
        if (doc3.nodes[parentId]) {
          if (selectedSet.has(parentId)) return true;
          cursor = { kind: "node", id: parentId };
          continue;
        }
        cursor = { kind: "summary", id: parentId };
      }
      return false;
    };
    const roots = selected.filter((id) => !isUnderSelectedAncestor(id));
    if (roots.length === 0) return;
    const subtreeIds = /* @__PURE__ */ new Set();
    for (const rootId of roots) {
      for (const id of collectSubtreeNodeIds(doc3, rootId)) subtreeIds.add(id);
    }
    const nodes = {};
    for (const id of subtreeIds) {
      const node = doc3.nodes[id];
      if (node) nodes[id] = node;
    }
    const assets = collectReferencedAssets(doc3, Array.from(subtreeIds));
    const payload = {
      type: "kmind-subtree@2",
      roots,
      nodes,
      assets,
      sourceDocId: props.documentId ?? props.appUi?.snapshot.documents.activeId ?? void 0,
      sourceRootId: props.appUi?.snapshot.navigation.rootId ?? void 0
    };
    let json = "";
    try {
      json = JSON.stringify(payload);
    } catch {
      return;
    }
    event.preventDefault();
    event.stopPropagation();
    try {
      event.clipboardData?.setData("application/x-kmind-subtree+json", json);
    } catch {
    }
    event.clipboardData?.setData("text/plain", json);
  }, [
    doc3,
    editing,
    props.appUi?.dispatchCommand,
    props.appUi?.snapshot.documents.activeId,
    props.appUi?.snapshot.navigation.rootId,
    props.documentId,
    props.interaction?.smartPaste,
    selectedNodeIds
  ]);
  const onCanvasPaste = (0, import_react45.useCallback)((event) => {
    if (!props.interaction?.smartPaste) return;
    if (readOnly) return;
    if (isTypingTarget(event.target)) return;
    if (editing) return;
    const clipboardData = event.clipboardData;
    if (!clipboardData) return;
    const files = Array.from(clipboardData.files ?? []);
    const imageFile = files.find((file) => typeof file.type === "string" && file.type.startsWith("image/")) ?? null;
    if (imageFile) {
      event.preventDefault();
      event.stopPropagation();
      void pasteImageFile(imageFile);
      return;
    }
    const subtreeRaw = clipboardData.getData("application/x-kmind-subtree+json");
    const textRaw = subtreeRaw || clipboardData.getData("text/plain");
    const text5 = String(textRaw ?? "");
    const parentId = selection?.type === "node" ? selection.id : null;
    const tryPasteSubtree = () => {
      try {
        const parsed = JSON.parse(text5);
        if (parsed.type !== "kmind-subtree@2") return false;
        if (!Array.isArray(parsed.roots) || !parsed.nodes) return false;
        if (props.appUi?.dispatchCommand) {
          void props.appUi.dispatchCommand("node.clipboard.pasteSubtree", { nodeId: parentId ?? void 0, text: text5 });
          return true;
        }
        const result = props.core.dispatch({
          type: "insert_subtree",
          payload: { parentId, subtree: { roots: parsed.roots, nodes: parsed.nodes, assets: parsed.assets ?? {} } }
        });
        if (!result.ok) void dialog.alert(result.error);
        return true;
      } catch {
        return false;
      }
    };
    const tryPasteMarkdownHeadings = () => {
      const subtree = buildSubtreeFromMarkdownHeadings(text5);
      if (!subtree) return false;
      const result = props.core.dispatch({
        type: "insert_subtree",
        payload: { parentId, subtree: { roots: subtree.roots, nodes: subtree.nodes, assets: {} } }
      });
      if (!result.ok) void dialog.alert(result.error);
      return true;
    };
    const tryPasteSmartText = () => {
      const handler = props.interaction?.smartPasteText;
      if (!handler) return false;
      const result = handler({
        text: text5,
        selectedNodeId: parentId,
        selectedNodeIds: [...selectedNodeIds]
      });
      if (!result) return false;
      if (result.kind === "external-link") {
        const url = String(result.url ?? "").trim();
        if (!url) return false;
        const label = typeof result.label === "string" && result.label.trim().length > 0 ? result.label.trim() : void 0;
        const iconId = typeof result.iconId === "string" && result.iconId.trim().length > 0 ? result.iconId.trim() : void 0;
        const targetNodeIds = selectedNodeIds.size > 0 ? [...selectedNodeIds] : parentId ? [parentId] : [];
        if (targetNodeIds.length > 0) {
          if (!props.appUi?.dispatchCommand) return false;
          for (const nodeId2 of targetNodeIds) {
            void props.appUi.dispatchCommand("node.link.addExternal", {
              nodeId: nodeId2,
              url,
              ...label ? { label } : null,
              ...iconId ? { iconId } : null
            });
          }
          return true;
        }
        const nodeId = createKmindId("node");
        const nodeText = typeof result.nodeText === "string" && result.nodeText.trim().length > 0 ? result.nodeText.trim() : label ?? url;
        const subtree = {
          roots: [nodeId],
          nodes: {
            [nodeId]: {
              id: nodeId,
              children: [],
              text: nodeText,
              content: {
                schemaVersion: 1,
                kind: "blocks",
                blocks: [
                  {
                    id: createKmindId("links"),
                    type: "links",
                    region: "top",
                    order: 0,
                    links: [
                      {
                        kind: "external",
                        id: createKmindId("link"),
                        url,
                        ...label ? { label } : null,
                        ...iconId ? { iconId } : null
                      }
                    ]
                  }
                ]
              }
            }
          },
          assets: {}
        };
        const insert2 = props.core.dispatch({ type: "insert_subtree", payload: { parentId: null, subtree } });
        if (!insert2.ok) void dialog.alert(insert2.error);
        return true;
      }
      return false;
    };
    const tryPastePlainText = () => {
      if (text5.trim().length === 0) return false;
      const title = text5.replace(/\r\n/g, "\n").replace(/\n+$/g, "");
      const subtree = {
        roots: ["plain_root"],
        nodes: { plain_root: { id: "plain_root", children: [], text: title } },
        assets: {}
      };
      const result = props.core.dispatch({ type: "insert_subtree", payload: { parentId, subtree } });
      if (!result.ok) void dialog.alert(result.error);
      return true;
    };
    event.preventDefault();
    event.stopPropagation();
    if (tryPasteSubtree()) return;
    if (tryPasteSmartText()) return;
    if (tryPasteMarkdownHeadings()) return;
    void tryPastePlainText();
  }, [buildSubtreeFromMarkdownHeadings, dialog, editing, pasteImageFile, props.appUi?.dispatchCommand, props.core, props.interaction?.smartPaste, props.interaction?.smartPasteText, selectedNodeIds, selection]);
  const importFreeMind = async (file) => {
    try {
      const text5 = await file.text();
      const imported = parseFreeMind(text5);
      props.core.fromJSON(imported);
      const rootId = imported.roots[0];
      if (rootId) {
        selectSingleNode(rootId);
      } else {
        clearSelection();
      }
    } catch (error) {
      await dialog.alert(error instanceof Error ? error.message : "\u5BFC\u5165\u5931\u8D25");
    }
  };
  const exportSvg = () => {
    if (!svgRef.current) return;
    const useExpanded = exportScope === "expanded" && hasCollapsedNodes;
    void (async () => {
      const blob = await exportSvgFromCanvas({ mode: svgExportMode, scope: exportScope });
      downloadBlob(blob, `kmind.${svgExportMode}${useExpanded ? ".expanded" : ""}.svg`);
    })();
  };
  const exportPng = async (scale) => {
    if (!svgRef.current) return;
    const useExpanded = exportScope === "expanded" && hasCollapsedNodes;
    const result = await exportPngFromCanvas({ mode: pngExportMode, scale, scope: exportScope });
    if (result.usedFallback) {
      void dialog.alert("accurate PNG \u5BFC\u51FA\u5931\u8D25\uFF0C\u5DF2\u81EA\u52A8\u56DE\u9000\u4E3A fast \u6A21\u5F0F\uFF08\u7EAF\u6587\u672C\u964D\u7EA7\uFF09\u3002");
    }
    downloadBlob(result.blob, `kmind.${pngExportMode}${useExpanded ? ".expanded" : ""}@${scale}x.png`);
  };
  const themeVars = (0, import_react45.useMemo)(
    () => ({
      "--km-bg": documentTheme.paint.bg,
      "--km-panel": documentTheme.paint.panel,
      "--km-text": documentTheme.paint.text,
      "--km-muted": documentTheme.paint.muted,
      "--km-border": documentTheme.paint.border,
      "--km-node-fill": documentTheme.paint.nodeFill,
      "--km-node-fill-selected": documentTheme.paint.nodeFillSelected,
      "--km-node-stroke": documentTheme.paint.nodeStroke,
      "--km-node-stroke-selected": documentTheme.paint.nodeStrokeSelected,
      "--km-edge-stroke": documentTheme.paint.edgeStroke,
      "--km-relation-stroke": documentTheme.paint.relationStroke,
      "--km-relation-stroke-selected": documentTheme.paint.relationStrokeSelected,
      "--km-summary-stroke": documentTheme.paint.summaryStroke,
      "--km-code-bg": documentTheme.variantId === "dark" ? "rgba(0, 0, 0, 0.24)" : "rgba(15, 23, 42, 0.06)",
      "--km-code-border": documentTheme.variantId === "dark" ? "rgba(226, 232, 240, 0.14)" : "rgba(148, 163, 184, 0.35)",
      "--km-code-token-keyword": documentTheme.variantId === "dark" ? "rgba(196, 181, 253, 0.95)" : "rgba(124, 58, 237, 0.95)",
      "--km-code-token-string": documentTheme.variantId === "dark" ? "rgba(125, 211, 252, 0.95)" : "rgba(2, 132, 199, 0.95)",
      "--km-code-token-number": documentTheme.variantId === "dark" ? "rgba(253, 186, 116, 0.95)" : "rgba(234, 88, 12, 0.95)",
      "--km-code-token-comment": documentTheme.variantId === "dark" ? "rgba(148, 163, 184, 0.78)" : "rgba(100, 116, 139, 0.85)",
      "--km-code-token-property": documentTheme.variantId === "dark" ? "rgba(147, 197, 253, 0.95)" : "rgba(29, 78, 216, 0.95)",
      "--km-code-token-punct": documentTheme.variantId === "dark" ? "rgba(226, 232, 240, 0.92)" : "rgba(51, 65, 85, 0.88)"
    }),
    [documentTheme.paint, documentTheme.variantId]
  );
  const uiVars = (0, import_react45.useMemo)(
    () => ({
      "--km-bg": "var(--km-ui-bg, #ffffff)",
      "--km-panel": "var(--km-ui-panel, #ffffff)",
      "--km-text": "var(--km-ui-text, #0f172a)",
      "--km-muted": "var(--km-ui-muted, #475569)",
      "--km-border": "var(--km-ui-border, #e2e8f0)",
      "--km-node-fill": "var(--km-ui-node-fill, #ffffff)",
      "--km-node-fill-selected": "var(--km-ui-node-fill-selected, rgba(14, 165, 233, 0.10))",
      "--km-node-stroke": "var(--km-ui-node-stroke, #0ea5e9)",
      "--km-node-stroke-selected": "var(--km-ui-node-stroke-selected, #22c55e)",
      "--km-edge-stroke": "var(--km-ui-edge-stroke, #0ea5e9)",
      "--km-relation-stroke": "var(--km-ui-relation-stroke, #f59e0b)",
      "--km-relation-stroke-selected": "var(--km-ui-relation-stroke-selected, #fb7185)",
      "--km-summary-stroke": "var(--km-ui-summary-stroke, rgba(14, 165, 233, 0.45))",
      "--km-code-bg": "rgba(15, 23, 42, 0.06)",
      "--km-code-border": "rgba(148, 163, 184, 0.35)",
      "--km-code-token-keyword": "rgba(124, 58, 237, 0.95)",
      "--km-code-token-string": "rgba(2, 132, 199, 0.95)",
      "--km-code-token-number": "rgba(234, 88, 12, 0.95)",
      "--km-code-token-comment": "rgba(100, 116, 139, 0.85)",
      "--km-code-token-property": "rgba(29, 78, 216, 0.95)",
      "--km-code-token-punct": "rgba(51, 65, 85, 0.88)"
    }),
    []
  );
  const emptySelectedNodeIds = (0, import_react45.useMemo)(() => /* @__PURE__ */ new Set(), []);
  const chrome2 = props.chrome ?? "full";
  const isCanvasOnly = chrome2 === "canvas";
  const toggleNodeCollapsed = (nodeId) => {
    focusCanvas();
    if (readOnly) {
      const baseCollapsed = baseDoc.viewState?.collapsedNodeIds?.[nodeId] === true;
      setCollapsedOverrides((prev) => {
        const current = Object.prototype.hasOwnProperty.call(prev, nodeId) ? Boolean(prev[nodeId]) : baseCollapsed;
        const nextCollapsed = !current;
        if (nextCollapsed === baseCollapsed) {
          if (!Object.prototype.hasOwnProperty.call(prev, nodeId)) return prev;
          const { [nodeId]: _removed, ...rest } = prev;
          return rest;
        }
        if (prev[nodeId] === nextCollapsed) return prev;
        return { ...prev, [nodeId]: nextCollapsed };
      });
      return;
    }
    selectSingleNode(nodeId);
    props.core.dispatch({ type: "toggle_node_collapsed", payload: { nodeId } });
  };
  const onCommitNodeRichText = (payload) => {
    if (!editing || editing.type !== "node") return false;
    const nodeId = editing.id;
    const current = props.core.getState().document.nodes[nodeId];
    if (!current) return false;
    const nextContent = resolveNodeContentCommit({
      payloadContent: payload.content,
      currentContent: current.content
    });
    const result = props.core.dispatch({
      type: "set_node_content",
      payload: { nodeId, content: nextContent, plainText: payload.plainText }
    });
    if (!result.ok) {
      void dialog.alert(result.error);
      return false;
    }
    stopEdit();
    return true;
  };
  const onCommitSummaryRichText = (payload) => {
    if (!editing || editing.type !== "summary") return false;
    const summaryId = editing.id;
    const current = props.core.getState().document.summaries.find((item) => item.id === summaryId);
    if (!current) return false;
    const nextContent = resolveNodeContentCommit({
      payloadContent: payload.content,
      currentContent: current.content
    });
    const result = props.core.dispatch({
      type: "set_summary_content",
      payload: { summaryId, content: nextContent, plainText: payload.plainText }
    });
    if (!result.ok) {
      void dialog.alert(result.error);
      return false;
    }
    stopEdit();
    return true;
  };
  if (perfEnabled) {
    const perf = perfStatsRef.current;
    perf.version += 1;
    perf.updatedAt = Date.now();
    perf.doc.roots = doc3.roots.length;
    perf.doc.nodes = Object.keys(doc3.nodes).length;
    perf.doc.summaries = doc3.summaries.length;
    perf.doc.relations = doc3.relations.length;
    perf.doc.edges = layout.edges.length;
    perf.viewport = viewBox;
    perf.culling.enabled = viewportCullEnabled;
    perf.culling.margin = viewportCullMargin;
    perf.culling.renderedNodes = 0;
    perf.culling.renderedEdges = 0;
    perf.culling.renderedSummaries = 0;
    perf.culling.renderedRelations = 0;
    perf.nodeHtml.cacheEnabled = nodeHtmlCacheEnabled;
    perf.layout.engine = props.layoutEngine ?? "tidy";
    perf.layout.nodes = Object.keys(layout.nodes).length;
    perf.layout.summaries = Object.keys(layout.summaries).length;
    perf.layout.edges = layout.edges.length;
    perf.layout.relations = layout.relations.length;
    perf.layout.bounds = { width: layout.bounds.width, height: layout.bounds.height };
    perf.layout.previewActive = Boolean(previewLayout);
    perf.theme.mode = themeResolveMode;
    perf.theme.resolveMs = nodeThemeResolveMs;
    perf.export.usesDedicatedExportScene = viewportCullEnabled;
    perf.export.active = exportActive;
  }
  return {
    props,
    submap,
    state,
    doc: doc3,
    embedRegistry,
    nodeBodyLayout,
    dialog,
    clipboard,
    storage,
    assetObjectUrlById,
    assetObjectUrlVersion,
    perfConfig: {
      enabled: perfEnabled,
      viewportCull: { enabled: viewportCullEnabled, margin: viewportCullMargin, cellSize: viewportCullCellSize },
      nodeHtmlCache: { enabled: nodeHtmlCacheEnabled, maxEntries: nodeHtmlCacheMaxEntries },
      optimizeEmbedMounting,
      themeResolveMode
    },
    perfStatsRef,
    svgRef,
    canvasRef,
    viewBox,
    viewportSize,
    viewportCullRect,
    visibleNodeIds,
    visibleSummaryIds,
    panByViewportDelta,
    selection,
    setSelection,
    contextMenu,
    closeContextMenu,
    openNodeContextMenuAt,
    openSummaryContextMenuAt,
    onCanvasContextMenu,
    hoveredNodeId,
    setHoveredNodeId,
    selectedNodeIds,
    setSelectedNodeIds,
    selectionToolbarHighlightNodeId,
    setSelectionToolbarHighlightNodeId,
    revealHighlightNodeId,
    revealHighlightSummaryId,
    selectionToolbarPopoverRequest,
    selectionToolbarActionRequest,
    requestSelectionToolbarPopover: props.appUi ? requestSelectionToolbarPopover : void 0,
    requestSelectionToolbarAction: props.appUi ? requestSelectionToolbarAction : void 0,
    onSelectionToolbarPopoverRequestHandled,
    onSelectionToolbarActionRequestHandled,
    editing,
    editingLayout,
    pendingRelationFromId,
    editingLayoutMode,
    dragGhostMode,
    editTabEnterBehavior,
    setInternalEditingLayoutMode,
    setInternalDragGhostMode,
    setInternalEditTabEnterBehavior,
    setEditingDraftSize,
    resizeDraft,
    relationCurveDraft,
    relationLabelEditing,
    relationEndpointsDraft,
    blurViewState,
    setBlurViewState,
    documentTheme,
    themeVars,
    uiVars,
    nodeThemeById,
    summaryThemeById,
    backlinksIndex,
    progressByNodeId,
    layout,
    sceneLayout,
    containerLayoutTypeById,
    hiddenNodeIds,
    hiddenSummaryIds,
    dropHighlight,
    ghostDelta,
    dragUi,
    isPanning,
    marqueeRect,
    linksPanel,
    linksPanelPosition,
    closeLinksPanel,
    openLinksPanel,
    onRequestLinksPanelModeChange,
    onLinksPanelHoverChange,
    onLinksPanelIconHoverChange,
    metaPopover,
    metaPopoverPosition,
    metaPopoverCommitRef,
    closeMetaPopover,
    openMetaPopover,
    onMetaPopoverHoverChange,
    onRequestMetaPopoverModeChange,
    onOverlayNodeHoverChange,
    onOverlayNodePointerMove,
    exportExpandedEnabled,
    exportExpandedDoc,
    exportExpandedLayout,
    exportExpandedSvgRef,
    exportExpandedContainerLayoutTypeById,
    exportFullActive,
    exportFullSvgRef,
    subtreeExportNodeId,
    subtreeExportDoc,
    subtreeExportLayout,
    subtreeExportSvgRef,
    subtreeExportContainerLayoutTypeById,
    svgExportMode,
    setSvgExportMode,
    pngExportMode,
    setPngExportMode,
    exportScope,
    setExportScope,
    hasCollapsedNodes,
    spaceDown,
    onCanvasBlur,
    onCanvasCopy,
    onCanvasPaste,
    onCanvasKeyDownCapture,
    onCanvasKeyUpCapture,
    onSvgPointerDownCapture,
    onSvgPointerMove,
    onSvgPointerUp,
    onSvgPointerCancel,
    onSvgDoubleClick,
    onNodePointerDown,
    onSummaryPointerDown,
    onNodeResizeHandlePointerDown,
    onRelationControlHandlePointerDown,
    undo: undo2,
    redo: redo2,
    addChild,
    addSibling,
    addRoot,
    moveRoot,
    toggleLayout,
    createSummary,
    startRelation,
    toggleNodeCollapsed,
    deleteSelected,
    copyNodeContent,
    pasteNodeContent,
    copySubtree,
    pasteSubtree,
    exportSvg,
    exportPng,
    importFreeMind,
    focusCanvas,
    selectNodeAndReveal,
    selectSingleNode,
    selectSummary,
    selectRelation,
    onRelationLabelDoubleClick,
    commitRelationLabelEditing,
    cancelRelationLabelEditing,
    startEditNode,
    startEditSummary,
    stopEdit,
    cancelEdit,
    emptySelectedNodeIds,
    chrome: chrome2,
    isCanvasOnly,
    measurerRef,
    richTextEditorRef,
    onCommitNodeRichText,
    onCommitSummaryRichText
  };
}

// ../react/src/mindmap-editor/editor.tsx
var import_jsx_runtime36 = __toESM(require_jsx_runtime(), 1);
function MindMapCanvas(props) {
  const canvasKeymapOverride = (0, import_react46.useMemo)(
    () => ({
      undo: [],
      redo: [],
      deleteSelection: []
    }),
    []
  );
  const mergedKeymapOverride = (0, import_react46.useMemo)(
    () => ({ ...canvasKeymapOverride, ...props.keymapOverride ?? {} }),
    [canvasKeymapOverride, props.keymapOverride]
  );
  return /* @__PURE__ */ (0, import_jsx_runtime36.jsx)(
    MindMapEditor,
    {
      ...props,
      canvasHeight: props.canvasHeight ?? "100%",
      chrome: "canvas",
      keymapOverride: mergedKeymapOverride
    }
  );
}
function MindMapEditor(props) {
  const model = useEditorModel(props);
  return /* @__PURE__ */ (0, import_jsx_runtime36.jsx)(OverlayPortalProvider, { container: props.overlayPortalContainer, children: /* @__PURE__ */ (0, import_jsx_runtime36.jsx)(EditorView2, { model }) });
}

// ../react/src/performance-config.ts
var KMIND_SAFE_PERFORMANCE_CONFIG = {
  mindMap: {
    viewportCull: {
      enabled: false,
      thresholdNodes: Number.POSITIVE_INFINITY,
      margin: 600,
      cellSize: 800
    },
    nodeHtmlCache: {
      enabled: false,
      maxEntries: 0
    },
    optimizeEmbedMounting: false,
    themeResolver: {
      mode: "legacy"
    },
    sharedResources: {
      enabled: false
    },
    layoutCache: {
      enabled: false,
      maxEntries: 0,
      dragPreviewEnabled: false,
      dragPreviewMaxEntries: 0
    }
  },
  workspace: {
    unmountHiddenMap: false,
    outlineProjectionCache: {
      enabled: false
    },
    continuousOutlineItemIndex: {
      enabled: false
    }
  }
};

// ../react/src/richtext-content-view.tsx
var import_react47 = __toESM(require_react(), 1);
var import_jsx_runtime37 = __toESM(require_jsx_runtime(), 1);

// ../react/src/outline/continuous-outline-tiptap-editor.tsx
var import_react48 = __toESM(require_react(), 1);
init_src();
var import_jsx_runtime38 = __toESM(require_jsx_runtime(), 1);
var OUTLINE_META_ITEM_KINDS = /* @__PURE__ */ new Set(["task", "notes", "comments", "link", "relation", "tag", "submap"]);
function isOutlineMetaItemKind(value) {
  return typeof value === "string" && OUTLINE_META_ITEM_KINDS.has(value);
}
function normalizeOutlineMetaItem(value) {
  if (!value || typeof value !== "object") return null;
  const record = value;
  if (!isOutlineMetaItemKind(record.kind)) return null;
  const label = typeof record.label === "string" ? record.label.trim() : "";
  if (!label) return null;
  const itemValue = typeof record.value === "string" ? record.value.trim() : "";
  return {
    kind: record.kind,
    label,
    value: itemValue || void 0
  };
}
function parseOutlineMetaItems(value) {
  const raw = typeof value === "string" ? value : "";
  if (!raw) return [];
  try {
    const parsed = JSON.parse(raw);
    if (!Array.isArray(parsed)) return [];
    return parsed.map(normalizeOutlineMetaItem).filter((item) => Boolean(item));
  } catch {
    return [];
  }
}
function renderOutlineMetaIndicatorInto(container, hasMeta) {
  while (container.firstChild) container.removeChild(container.firstChild);
  if (!hasMeta) return;
  const ownerDocument = container.ownerDocument;
  const icon = ownerDocument.createElement("span");
  icon.className = "km-continuous-outline-item__meta-icon";
  icon.setAttribute("aria-hidden", "true");
  container.append(icon);
}
var OutlineDocument = Node3.create({
  name: "doc",
  topNode: true,
  content: "outlineItem+"
});
var OutlineItem = Node3.create({
  name: "outlineItem",
  group: "block",
  content: "block+",
  defining: true,
  isolating: true,
  addAttributes() {
    return {
      entityType: { default: "node" },
      entityId: { default: "" },
      rowKey: { default: "" },
      rowKind: { default: "node" },
      depth: { default: 0 },
      orderPath: { default: "" },
      collapsed: { default: false },
      childCount: { default: 0 },
      rootIndex: { default: 0 },
      metaText: { default: "" },
      metaSummary: { default: "" },
      metaItems: { default: "[]" }
    };
  },
  parseHTML() {
    return [{ tag: "section[data-km-outline-item]" }];
  },
  renderHTML({ HTMLAttributes }) {
    const depth = Number.isFinite(Number(HTMLAttributes.depth)) ? Number(HTMLAttributes.depth) : 0;
    const entityType = String(HTMLAttributes.entityType ?? "node");
    const entityId = String(HTMLAttributes.entityId ?? "");
    const rowKind = String(HTMLAttributes.rowKind ?? "node");
    const orderPath = String(HTMLAttributes.orderPath ?? "");
    const metaText = String(HTMLAttributes.metaText ?? "");
    const metaSummary = String(HTMLAttributes.metaSummary ?? metaText);
    const metaItems = parseOutlineMetaItems(HTMLAttributes.metaItems);
    const collapsed = HTMLAttributes.collapsed === true || HTMLAttributes.collapsed === "true";
    const childCount = Number.isFinite(Number(HTMLAttributes.childCount)) ? Number(HTMLAttributes.childCount) : 0;
    const hasMeta = metaItems.length > 0;
    return [
      "section",
      {
        "data-km-outline-item": "true",
        "data-km-outline-entity-key": `${entityType}:${entityId}`,
        "data-km-outline-row-kind": rowKind,
        "data-km-outline-depth": String(depth),
        "data-km-outline-order": orderPath,
        "data-km-outline-collapsed": collapsed ? "true" : "false",
        "data-km-outline-child-count": String(childCount),
        "data-km-outline-can-toggle": childCount > 0 ? "true" : "false",
        class: "km-continuous-outline-item",
        style: `--km-outline-depth:${depth}`
      },
      [
        "div",
        { class: "km-continuous-outline-item__chrome", contenteditable: "false" },
        [
          "button",
          {
            "aria-label": "\u884C\u64CD\u4F5C",
            class: "km-continuous-outline-item__menu",
            "data-km-outline-row-menu": "true",
            "data-km-outline-drag-handle": "true",
            draggable: "true",
            type: "button",
            title: "\u884C\u64CD\u4F5C / \u62D6\u62FD\u6392\u5E8F"
          }
        ],
        [
          "button",
          {
            "aria-label": collapsed ? "\u5C55\u5F00" : "\u6298\u53E0",
            class: "km-continuous-outline-item__toggle",
            "data-km-outline-can-toggle": childCount > 0 ? "true" : "false",
            "data-km-outline-toggle": "true",
            type: "button",
            title: childCount > 0 ? "\u6298\u53E0\u6216\u5C55\u5F00" : ""
          },
          ["span", { "aria-hidden": "true", class: "km-continuous-outline-item__chevron" }]
        ],
        ["span", { class: "km-continuous-outline-item__order", title: orderPath }, orderPath]
      ],
      ["div", { class: "km-continuous-outline-item__body km-node-richtext" }, 0],
      [
        "button",
        {
          "aria-label": metaSummary || "\u8282\u70B9\u72B6\u6001",
          class: "km-continuous-outline-item__meta",
          contenteditable: "false",
          "data-km-outline-meta-empty": hasMeta ? "false" : "true",
          "data-km-outline-meta-trigger": hasMeta ? "true" : "false",
          type: "button",
          title: metaSummary
        },
        ...hasMeta ? [["span", { "aria-hidden": "true", class: "km-continuous-outline-item__meta-icon" }]] : []
      ]
    ];
  },
  addNodeView() {
    if (typeof document === "undefined") return null;
    return ({ node }) => {
      const dom = document.createElement("section");
      const chrome2 = document.createElement("div");
      const menu = document.createElement("button");
      const toggle = document.createElement("button");
      const chevron = document.createElement("span");
      const order = document.createElement("span");
      const contentDOM = document.createElement("div");
      const meta = document.createElement("button");
      dom.className = "km-continuous-outline-item";
      dom.setAttribute("data-km-outline-item", "true");
      chrome2.className = "km-continuous-outline-item__chrome";
      chrome2.contentEditable = "false";
      menu.className = "km-continuous-outline-item__menu";
      menu.type = "button";
      menu.draggable = true;
      menu.setAttribute("aria-label", "\u884C\u64CD\u4F5C");
      menu.setAttribute("data-km-outline-row-menu", "true");
      menu.setAttribute("data-km-outline-drag-handle", "true");
      menu.title = "\u884C\u64CD\u4F5C / \u62D6\u62FD\u6392\u5E8F";
      toggle.className = "km-continuous-outline-item__toggle";
      toggle.type = "button";
      toggle.setAttribute("data-km-outline-toggle", "true");
      chevron.className = "km-continuous-outline-item__chevron";
      chevron.setAttribute("aria-hidden", "true");
      toggle.append(chevron);
      order.className = "km-continuous-outline-item__order";
      contentDOM.className = "km-continuous-outline-item__body km-node-richtext";
      meta.className = "km-continuous-outline-item__meta";
      meta.type = "button";
      meta.contentEditable = "false";
      chrome2.append(menu, toggle, order);
      dom.append(chrome2, contentDOM, meta);
      const updateAttrs = (attrs) => {
        const depth = Number.isFinite(Number(attrs.depth)) ? Number(attrs.depth) : 0;
        const entityType = attrs.entityType === "summary" ? "summary" : "node";
        const entityId = typeof attrs.entityId === "string" ? attrs.entityId : "";
        const rowKind = typeof attrs.rowKind === "string" ? attrs.rowKind : "node";
        const orderPath = typeof attrs.orderPath === "string" ? attrs.orderPath : "";
        const metaText = typeof attrs.metaText === "string" ? attrs.metaText : "";
        const metaSummary = typeof attrs.metaSummary === "string" ? attrs.metaSummary : metaText;
        const metaItems = parseOutlineMetaItems(attrs.metaItems);
        const hasMeta = metaItems.length > 0;
        const collapsed = attrs.collapsed === true || attrs.collapsed === "true";
        const childCount = Number.isFinite(Number(attrs.childCount)) ? Number(attrs.childCount) : 0;
        dom.dataset.kmOutlineEntityKey = `${entityType}:${entityId}`;
        dom.dataset.kmOutlineRowKind = rowKind;
        dom.dataset.kmOutlineDepth = String(depth);
        dom.dataset.kmOutlineOrder = orderPath;
        dom.dataset.kmOutlineCollapsed = collapsed ? "true" : "false";
        dom.dataset.kmOutlineChildCount = String(childCount);
        dom.dataset.kmOutlineCanToggle = childCount > 0 ? "true" : "false";
        dom.style.setProperty("--km-outline-depth", String(depth));
        toggle.dataset.kmOutlineCanToggle = childCount > 0 ? "true" : "false";
        toggle.setAttribute("aria-label", collapsed ? "\u5C55\u5F00" : "\u6298\u53E0");
        toggle.setAttribute("aria-hidden", childCount > 0 ? "false" : "true");
        toggle.title = childCount > 0 ? "\u6298\u53E0\u6216\u5C55\u5F00" : "";
        order.textContent = orderPath;
        order.title = orderPath;
        meta.title = metaSummary;
        meta.setAttribute("aria-label", metaSummary || "\u8282\u70B9\u72B6\u6001");
        meta.dataset.kmOutlineMetaEmpty = hasMeta ? "false" : "true";
        meta.dataset.kmOutlineMetaTrigger = hasMeta ? "true" : "false";
        renderOutlineMetaIndicatorInto(meta, hasMeta);
      };
      updateAttrs(node.attrs);
      return {
        dom,
        contentDOM,
        update: (updatedNode) => {
          if (updatedNode.type.name !== "outlineItem") return false;
          updateAttrs(updatedNode.attrs);
          return true;
        }
      };
    };
  }
});
function outlineItemRefFromNode(node, pos) {
  if (node.type.name !== "outlineItem") return null;
  const attrs = node.attrs;
  const entityType = attrs.entityType === "summary" ? "summary" : "node";
  const entityId = typeof attrs.entityId === "string" ? attrs.entityId : "";
  if (!entityId) return null;
  return {
    key: `${entityType}:${entityId}`,
    target: { type: entityType, id: entityId },
    pos,
    nodeSize: node.nodeSize,
    plainText: node.textContent,
    contentJson: node.content.toJSON(),
    collapsed: attrs.collapsed === true || attrs.collapsed === "true",
    childCount: Number.isFinite(Number(attrs.childCount)) ? Number(attrs.childCount) : 0
  };
}
function buildOutlineItemIndex(doc3) {
  const byKey = /* @__PURE__ */ new Map();
  doc3.descendants((node, pos) => {
    const item = outlineItemRefFromNode(node, pos);
    if (!item) return node.type.name === "outlineItem" ? false : true;
    byKey.set(item.key, item);
    return false;
  });
  const items = Array.from(byKey.values()).sort((a2, b2) => a2.pos - b2.pos);
  return { items, byKey };
}
var outlineItemIndexPluginKey = new PluginKey("kmindContinuousOutlineItemIndex");
var ContinuousOutlineItemIndex = Extension.create({
  name: "kmindContinuousOutlineItemIndex",
  addProseMirrorPlugins() {
    return [
      new Plugin({
        key: outlineItemIndexPluginKey,
        state: {
          init: (_config, state) => buildOutlineItemIndex(state.doc),
          apply: (transaction, previous, _oldState, newState) => {
            if (!transaction.docChanged) return previous;
            const changedRange = changedRangeFromTransaction(transaction);
            if (!changedRange) return buildOutlineItemIndex(newState.doc);
            const byKey = /* @__PURE__ */ new Map();
            for (const item of previous.items) {
              const mapped = transaction.mapping.mapResult(item.pos, 1);
              if (mapped.deleted) continue;
              const node = newState.doc.nodeAt(mapped.pos);
              if (!node) continue;
              const nextItem = outlineItemRefFromNode(node, mapped.pos);
              if (nextItem) byKey.set(nextItem.key, nextItem);
            }
            const docSize = newState.doc.content.size;
            const from2 = Math.max(0, Math.min(changedRange.from, docSize));
            const to = Math.max(from2, Math.min(changedRange.to, docSize));
            newState.doc.nodesBetween(from2, to, (node, pos) => {
              const item = outlineItemRefFromNode(node, pos);
              if (!item) return node.type.name === "outlineItem" ? false : true;
              byKey.set(item.key, item);
              return false;
            });
            return { items: Array.from(byKey.values()).sort((a2, b2) => a2.pos - b2.pos), byKey };
          }
        }
      })
    ];
  }
});
function changedRangeFromTransaction(transaction) {
  if (!transaction || typeof transaction !== "object") return null;
  const tx = transaction;
  if (tx.docChanged !== true || !Array.isArray(tx.mapping?.maps)) return null;
  let from2 = Number.POSITIVE_INFINITY;
  let to = Number.NEGATIVE_INFINITY;
  for (const map2 of tx.mapping.maps) {
    if (typeof map2?.forEach !== "function") continue;
    map2.forEach((_oldStart, _oldEnd, newStart, newEnd) => {
      from2 = Math.min(from2, newStart);
      to = Math.max(to, newEnd);
    });
  }
  if (!Number.isFinite(from2) || !Number.isFinite(to)) return null;
  return { from: Math.max(0, from2 - 1), to: Math.max(from2, to + 1) };
}

// src/render-job-browser.tsx
var import_jsx_runtime39 = __toESM(require_jsx_runtime(), 1);
function setStatus(text5) {
  const target2 = document.getElementById("status-text");
  if (target2) {
    target2.textContent = text5;
  }
  document.documentElement.dataset.renderStatus = text5;
}
async function waitFrames(count) {
  const total = Math.max(1, count);
  for (let index = 0; index < total; index += 1) {
    await new Promise((resolve) => requestAnimationFrame(() => resolve()));
  }
}
async function postFailure(message) {
  const globalWindow = window;
  globalWindow.__KMIND_RENDER_ERROR__ = message;
  try {
    await fetch("/failure", {
      method: "POST",
      headers: { "content-type": "text/plain; charset=utf-8" },
      body: message
    });
  } catch {
  }
}
function App() {
  const [job, setJob] = (0, import_react49.useState)(null);
  const apiRef = (0, import_react49.useRef)(null);
  const core = (0, import_react49.useMemo)(() => {
    if (!job) return null;
    return new MindMapCore({
      id: `kmind-render:${job.title}`,
      initialDocument: job.doc
    });
  }, [job]);
  (0, import_react49.useEffect)(() => {
    let cancelled = false;
    void (async () => {
      try {
        setStatus("Fetching render job\u2026");
        const response = await fetch("/job", { cache: "no-store" });
        if (!response.ok) {
          throw new Error(`Failed to fetch render job: ${response.status}`);
        }
        const payload = await response.json();
        if (!cancelled) {
          setJob(payload);
          setStatus(`Rendering ${payload.format.toUpperCase()} for ${payload.title}\u2026`);
        }
      } catch (error) {
        const message = error instanceof Error ? error.message : "Failed to fetch render job.";
        setStatus(message);
        await postFailure(message);
      }
    })();
    return () => {
      cancelled = true;
    };
  }, []);
  (0, import_react49.useEffect)(() => {
    if (!job || !core) return;
    let cancelled = false;
    void (async () => {
      try {
        await waitFrames(6);
        if (document.fonts?.ready) {
          await document.fonts.ready;
          await waitFrames(2);
        }
        const api = apiRef.current;
        if (!api) {
          throw new Error("Render canvas API is not ready.");
        }
        const blob = job.format === "svg" ? await api.exportSvg({ mode: job.svgMode, scope: "current" }) : (await api.exportPng({ mode: job.pngMode, scale: job.pngScale, scope: "current" })).blob;
        const bytes = new Uint8Array(await blob.arrayBuffer());
        if (cancelled) return;
        setStatus(`Uploading ${job.format.toUpperCase()}\u2026`);
        const response = await fetch("/result", {
          method: "POST",
          headers: {
            "content-type": blob.type || (job.format === "svg" ? "image/svg+xml" : "image/png")
          },
          body: bytes
        });
        if (!response.ok) {
          throw new Error(await response.text());
        }
        const globalWindow = window;
        globalWindow.__KMIND_RENDER_DONE__ = true;
        globalWindow.__KMIND_RENDER_ERROR__ = null;
        setStatus(`Done. ${job.format.toUpperCase()} saved.`);
      } catch (error) {
        const message = error instanceof Error ? error.message : "Browser render failed.";
        setStatus(message);
        await postFailure(message);
      }
    })();
    return () => {
      cancelled = true;
    };
  }, [core, job]);
  return /* @__PURE__ */ (0, import_jsx_runtime39.jsx)("div", { style: { width: "100%", height: "100%" }, children: core && job ? /* @__PURE__ */ (0, import_jsx_runtime39.jsx)(
    MindMapCanvas,
    {
      canvasApiRef: apiRef,
      canvasHeight: job.viewport.height,
      className: "kmind-render-canvas",
      core,
      initialSelection: "none",
      interaction: { readOnly: true },
      nodeBodyLayout: "card-v1",
      performance: { themeResolver: { mode: "optimized" } },
      textEditor: "plain"
    }
  ) : null });
}
var target = document.getElementById("root");
if (!target) {
  throw new Error("Missing #root container.");
}
(0, import_client.createRoot)(target).render(/* @__PURE__ */ (0, import_jsx_runtime39.jsx)(App, {}));
/*! Bundled license information:

react/cjs/react.development.js:
  (**
   * @license React
   * react.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.
   *)

scheduler/cjs/scheduler.development.js:
  (**
   * @license React
   * scheduler.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-dom/cjs/react-dom.development.js:
  (**
   * @license React
   * react-dom.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-dom/cjs/react-dom-client.development.js:
  (**
   * @license React
   * react-dom-client.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/cjs/react-jsx-runtime.development.js:
  (**
   * @license React
   * react-jsx-runtime.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.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.
   *)
*/
//# sourceMappingURL=render-job-browser.js.map
